A streaming AI chat application with generative UI tool components, connecting an Angular (@copilotkit/angular) frontend to a LangGraph Server via the AG-UI protocol and @ag-ui/langgraph on a Hono API.
This sample demonstrates a fully self-hosted deployment on Azure Container Apps using official AG-UI and CopilotKit packages rather than a custom AG-UI protocol implementation.
- App β Angular 22 chat UI (packages/app)
- API β Hono gateway that bridges the UI and the agent (packages/api)
- Agent β LangGraph agent served via LangGraph.js (packages/agent, README)
Each service runs as its own container on Azure Container Apps, backed by Azure AI Foundry (Cognitive Services) model deployments, an Azure Container Registry, Key Vault, and Application Insights.
- Architecture
- AG-UI tool calling example
- Prerequisites
- Dev Container Quick Start
- Local development
- Working with the code
- Clean up
- Cost-Conscious Local Development Setup
- User authentication (OpenID Connect)
- LangGraph config profiles
- Troubleshooting
- References
The core idea: a LangGraph agent, backed by an Azure AI Foundry model deployment, talks to the browser through the CopilotKit runtime (hosted in the Hono API) and the CopilotKit Angular client, using the AG-UI protocol as the wire format between the App and the API.
architecture-beta
group vnet(cloud)[Virtual Network]
group system(server)[system] in vnet
group agentResources(database)[Agent resources] in system
group cae(cloud)[Container Apps Environment] in system
group backPlane(cloud)[Back Plane] in vnet
service agw(internet)[Application Gateway] in cae
service app(server)[App] in cae
service api(server)[API] in cae
service agent(server)[Agent] in cae
align row app api
service pg(database)[PostgreSQL] in agentResources
service redis(database)[Redis] in agentResources
service cog(cloud)[Azure AI Foundry] in agentResources
align row pg redis cog
service monitor(database)[Azure Monitor] in backPlane
service kv(database)[Key Vault] in backPlane
service acr(disk)[Container Registry] in backPlane
align row kv acr monitor
agw:B -- T:app
agw:B -- T:api
api:B -- T:agent
agent:B -- T:cog
agent:B -- T:pg
agent:B -- T:redis
C4Container
System(app, "App", "Angular, @copilotkit/angular")
Enterprise_Boundary(azureBoundary, "Azure") {
System(api, "API", "Hono, CopilotKit Runtime", "AG-UI api")
System(agent, "Agent", "LangGraph Agent Server", "Langgraph agent")
System_Ext(cog, "Azure AI Foundry Model", "LLM completions")
}
BiRel(app, api, "ag-ui")
BiRel(api, agent, "LangChain messages")
BiRel(agent, cog, "OpenAI message")
UpdateLayoutConfig($c4ShapeInRow="2", $c4BoundaryInRow="1")
- App β Angular UI using
@copilotkit/angular. Renders the chat, streams assistant messages, and registers frontend tools. Custom Angular components are rendered inline for specific tool calls (for example, the haiku frontend tool included in the demo app). - API β a Hono server hosting the
CopilotRuntimefrom@copilotkit/runtime. It terminates the AG-UI protocol from the App and forwards the conversation to the LangGraph deployment via@ag-ui/langgraph'sLangGraphAgentadapter (see app.ts). - Agent β a LangGraph.js graph (agent.ts) that
calls an Azure AI Foundry model deployment and can invoke tools, some of
which (like
generate_haiku) are rendered by a matching frontend tool component instead of plain text.
Walkthrough of a user prompt that triggers the generate_haiku tool and how the
result is rendered by a custom Angular component. Auth (Entra ID) is omitted for
clarity β see User authentication below.
sequenceDiagram
autonumber
actor User
participant App as Angular App<br/>(@copilotkit/angular)
participant API as Hono API<br/>(CopilotRuntime)
participant Agent as LangGraph Agent
participant Model as Azure AI Foundry
User->>App: "Write me a haiku"
App->>API: AG-UI request (message + registered frontend tools)
API->>Agent: Forward run via LangGraphAgent adapter
Agent->>Model: Prompt + bound tools (generate_haiku)
Model-->>Agent: tool_call: generate_haiku
Agent->>Agent: ToolNode executes generate_haiku()
Agent-->>API: AG-UI stream: tool call + tool result (japanese/english lines)
API-->>App: Proxied AG-UI stream
App->>App: Match tool name to registered frontend tool
App-->>User: Render HaikuTool with the generated lines
Adding a new tool the same way means: define the tool schema in packages/schemas,
bind the tool to the model in agent.ts, and register a
matching Angular component with registerRenderToolCall in
chat.ts
using the same tool name.
In Azure, App/API/Agent each run as their own Container App behind an Application Gateway, with PostgreSQL, Redis, Key Vault, and Azure AI Foundry reachable only via private endpoints inside a VNet. See infra/main.bicep for the full topology.
- Azure subscription with access to Azure OpenAI.
- Git.
- LangSmith API key from an account with LangGraph Cloud access (free tier works).
azd upwill prompt for it asLANGSMITH_API_KEY. - Service management reference (optional) β
azd upalso prompts forserviceManagementReference. Press Enter to leave it blank unless your organization requires a service-management reference on Entra app registrations. If it does, get the value from your service owner or identity administration team; do not invent one. See the Microsoft Graph application properties for the property definition. To avoid the prompt, create the environment first withazd env new <name>, then runazd env set AZURE_SERVICE_MANAGEMENT_REFERENCE <value>.
- Use the badge above (VS Code Dev Containers) OR create a Codespace.
- Wait for the container to build and install dependencies.
- Sign in
azd config set auth.useAzCliAuth true
az login- Provision the infra and deploy the apps
azd up- Azure Developer CLI (
azd) - Azure CLI
- Node.js 24+
- pnpm 10+
- Docker (if building images locally)
- LangGraph CLI
This repo is set up to use Visual Studio Code and GitHub Copilot but it is not essential.
- Get the code
git clone https://github.com/JayChase/langchain-ag-ui-angular.git
cd langchain-ag-ui-angular- Install the dependencies
pnpm i- Sign in once with Azure CLI
azd config set auth.useAzCliAuth true
az login- Provision the infra and deploy
azd upazure.yaml # azd service + hook definitions
infra/ # Bicep infrastructure (Container Apps, ACR, AI Foundry, Key Vault, monitoring)
packages/
agent/ # LangGraph agent server (LangGraph.js)
api/ # ag-ui api (Hono)
app/ # ag-ui app (Angular with @copilotkit/angular)
Important
Warning: the demo certificate under infra/cert/agw-demo-cert.crt is for non-production/testing use only and must not be used in production.
In VS Code, open Run and Debug and launch π€ agent, πΌ api and
π₯οΈ ng serve. The API's existing dev script loads its local .env file.
Note
azd up will add the local ip address as an allowed address to the Azure Foundry instance but if you do not have a static ip address you may need to add your current address as well.
- Open the app https://localhost:4200 and log in with your Entra account.
- To run the example frontend tool (haiku tool), ask the agent to write a haiku.
Remove all the deployed resources and select Yes when prompted to permanently delete soft-deleted resources.
azd downNote
Run azd down without the --purge flag and confirm the purge interactively when prompted. Passing --purge directly on the command line causes azd to force-delete the Log Analytics workspace before the resource group is removed, which fails with CannotDeleteWorkspaceWhenLinkedToPrivateLinkScopes while the Azure Monitor Private Link Scope is still attached.
[!WARNING]
azd provision will deploy resources on paid SKUs. So please do not leave these running if you are not using them. They will cost you money.
[!WARNING]
azd down will not remove the Entra app registrations. Please delete those manually.
Minimal mode is a lower-cost option for local development. It provisions the Azure services needed to run the Agent, API and App locally, while skipping more expensive application-hosting and production infrastructure. It is not a production deployment or production-ready architecture, and it is not free: Azure AI usage can still incur charges. Use the full deployment for production.
| Minimal mode keeps for local development | Full deployment only |
|---|---|
| Azure AI resource and consumption-based model | Application Gateway, public IP, demo certificate generation |
| Entra API/SPA registrations and developer AI access | Container Apps/environment, ACR, managed identities |
| Resource group | PostgreSQL, Redis, VNet, private endpoints/DNS, Key Vault, certificate storage, monitoring stack |
This project runs a separate LangGraph development server. It uses local development storage, so minimal mode does not provision PostgreSQL or Redis. The omitted monitoring stack includes Application Insights, Log Analytics, the dashboard and Azure Monitor Private Link Scope (AMPLS).
Install dependencies and sign in as described in Local development.
Instead of azd up, create a new azd environment and provision the minimal
resources:
azd env new langchain-minimal
azd env set MINIMAL true
azd provisionWhen azd prompts, select the intended subscription, primary region, and model region. You normally select a subscription in this prompt; you do not need to look up or manually enter its ID.
Recovering an existing environment: If an environment already has deployment outputs but its saved subscription setting is missing, restore the exact subscription used by that deployment before retrying. The provisioning hook reads existing AI firewall rules from that subscription, so do not substitute the Azure CLI's current default subscription.
azd env set AZURE_SUBSCRIPTION_ID <original-subscription-id> --environment langchain-minimal
You need Azure AI model access and quota, Azure resource/RBAC permissions, and
the Microsoft Graph permissions required to create the Entra registrations.
Node.js 24+ is required for the cross-platform provisioning hooks. Have your
LangSmith API key ready for the LANGSMITH_API_KEY provisioning input.
- On a fresh environment, project
preprovisionruns before azd selects the subscription. It discovers your public IPv4 address usingset-my-ipwithout querying Azure resources or choosing an implicit Azure CLI subscription. - Later provisions read and preserve existing AI firewall rules in the selected subscription, adding your current IP to the allowlist.
- Postprovision generates local Angular configuration and Agent/API
.envfiles. No cloud application resources are deployed in minimal mode. MINIMALdefaults tofalse, so existing full deployments keep their architecture andazd upworkflow. Minimal mode supportsazd provisiononly; hooks rejectazd up,azd package,azd deploy, andazd publishwith local-run guidance.
Azure AI uses a public service endpoint restricted to your discovered public IPv4 address and any preserved IP rules. It does not enable an "all Azure services" exception or an internet-wide IP range. Foundry keeps default action Deny and bypass None.
After provisioning, assign your user to the provisioned enterprise applications and grant the required consent as described under User authentication, then follow Running and debugging.
The local Agent uses DefaultAzureCredential with your Azure CLI login.
Entra sign-in and API token/scope validation remain enabled.
Re-run azd provision if your public IP changes. Review and remove obsolete
Foundry IPs in the portal when no longer needed. The preprovision hook aborts on
firewall read errors rather than resetting the allowlist. Do not edit rules
concurrently with provisioning or broaden them to the entire internet to resolve
a timeout.
Postprovision writes the Agent and API settings to ignored
packages/agent/.env and packages/api/.env, and creates the ignored Angular
environment files. Protect .azure/ and the package .env files as credentials:
do not commit or publish their contents. The LangSmith key belongs in the
Agent configuration, never the frontend.
To regenerate local configuration from an already provisioned environment:
azd hooks run postprovision -e langchain-minimalThis overwrites the generated Angular environment files and known Agent/API
configuration values, clears stale cloud identity, telemetry and database
settings managed by the minimal helper, and preserves unrelated .env
settings.
Minimal mode is not free: Azure AI charges depend on model usage. It creates no PostgreSQL or Redis server to stop or start. Any existing full deployment continues billing independently until you remove it.
Use a new azd environment for minimal mode. Switching an existing environment is unsupported and does not remove previously deployed resources or stop their charges. See Clean up to remove an old deployment.
User sign-in is handled by Microsoft Entra ID using the OAuth 2.0 authorization code flow with PKCE. Two app registrations are provisioned by Bicep:
- API registration (infra/api-registration.bicep) β
exposes the delegated scope
app.useunder an app ID URI (api://<clientId>). This is the token audience the API expects.appRoleAssignmentRequiredis set so only users/groups explicitly assigned to the app in Entra can obtain tokens for it. - App registration (infra/app-registration.bicep) β
a public client for the Angular SPA (no client secret). It is granted the
API's
app.usescope and has the local dev redirect URI (https://localhost:4200/redirect). Full mode also adds the deployed gateway redirect URI (https://<agw-public-ip>/redirect).
sequenceDiagram
autonumber
actor User
participant SPA as Angular SPA (MSAL)
participant Entra as Microsoft Entra ID
participant API as Hono API
User->>SPA: Open app (unauthenticated)
SPA->>Entra: Redirect: /authorize (code + PKCE, scope=api://<id>/app.use)
Entra->>User: Sign-in + consent
User-->>Entra: Credentials
Entra-->>SPA: Redirect to /redirect with auth code
SPA->>Entra: POST /token (code + code_verifier)
Entra-->>SPA: access token (iss, aud=api, scp=app.use)
SPA->>API: API call with Authorization: Bearer <token>
API->>Entra: Fetch JWKS (cached) & verify signature
API->>API: Validate iss, aud, scp
alt valid + required scope present
API-->>SPA: 200 + response
else invalid / missing scope
API-->>SPA: 401 / 403
end
App (Angular with msal-angular)
auth.config.ts wires up
@azure/msal-angular:
- Interaction type: redirect (not popup) β works reliably across browsers and with SSR.
- Token cache: session storage β tokens do not survive a browser restart.
MsalGuardprotects app routes; unauthenticated users are redirected to Entra and land back on/redirectafter sign-in.MsalInterceptorsilently acquires and attaches an access token to any request whose URL matches the API URI in theprotectedResourceMap.
The clientId, authority, and API scopes come from the environment files, which
are populated from the azd outputs (NG_APP_CLIENT_ID, NG_ENTRA_AUTHORITY,
NG_API_SCOPES) β so local and deployed configs always match the provisioned
registrations.
bearer-auth.ts validates every
incoming request using hono/jwk:
- Signature β verified against Entra's JWKS endpoint (
RS256). issβ must behttps://login.microsoftonline.com/<tenantId>/v2.0.audβ must be the API registration's identifier URI.scpβ must containapp.use; a missing scope returns403(an invalid or expired token returns401).
Validated claims (sub, tid, scp) are stored on the request context as
authContext, so downstream handlers can identify the caller.
The agent package uses explicit LangGraph config profiles:
packages/agent/langgraph.local.jsonβ local development profilepackages/agent/langgraph.deploy.jsonβ deployment profile- currently matches local profile persistence behavior
Agent scripts are pinned to profiles so they cannot be mixed up accidentally:
pnpm --filter agent run dev(alias ofdev:local) useslanggraph.local.jsonpnpm --filter agent run dev:deployuseslanggraph.deploy.jsonpnpm --filter agent run create-dockerfileuseslanggraph.deploy.json
failed logging into container registry(401) right afterazd provisionβ the deployer's RBAC role assignment on the Container Registry can take a few minutes to propagate. Re-runazd deployafter a short wait; no infrastructure change is needed.ServiceTreeValueNotGuid: Value for ServiceManagementReference must be a valid GUIDwhen creating the app registrations β your tenant requires a service-management reference (a Service Tree GUID in Microsoft-internal tenants). Get the approved value from your service owner, then runazd env set AZURE_SERVICE_MANAGEMENT_REFERENCE <guid>and re-runazd up. See the troubleshooting guide (requires access to Microsoft-internal documentation).- If you are using Git Bash for Windows as your terminal, AZD will try to run the PowerShell hook script. To fix this, manually change the windows scripts to the posix versions in the azure.yaml file.
Every resource that matters (PostgreSQL, Redis, Key Vault, Azure AI Foundry) sits
behind private endpoints inside the VNet (infra/vnet.bicep),
so it isn't reachable from your machine. main.bicep has an
optional terminal container app for reaching those endpoints from inside the
network.
- Deploy it by setting the
deployTerminalparameter totrue: runazd env set DEPLOY_TERMINAL trueand thenazd provision. - It is preloaded with the same connection secrets as the agent container:
DATABASE_URI(Postgres),REDIS_URI, andAZURE_AI_ENDPOINT, plusLANGSMITH_API_KEYwhen set β so you can test connectivity with the exact values the agent uses, without copy-pasting secrets out of Key Vault. - It runs the
nicolaka/netshootimage (dig, curl, psql client tooling, etc.) withdisableIngress: trueβ it has no public endpoint and can only be reached via the Container Apps console in Azure portal or using the az containerapp:
az containerapp exec \
--name <abbrs.appContainerApps>terminal \
--resource-group <abbrs.resourcesResourceGroups><environmentName> \
--command /bin/bashWarning
The terminal container app has no ingress but still runs 24/7 once deployed β
set deployTerminal back to false and redeploy when you're done to avoid
paying for an idle container.

