### Create Pydantic AI Agent with Tools and Convert to FastAPI Source: https://context7.com/ag-ui-protocol/docs/llms.txt Demonstrates creating a Pydantic-based AI agent using OpenAI, adding server-side tools for time retrieval and calculation, and converting it into an AG-UI FastAPI application. This setup allows for easy deployment and interaction with the AI agent via a web API. It requires libraries like `ag-ui-protocol`, `openai`, and `uvicorn`. ```python from ag_ui_protocol.agent import Agent from datetime import datetime from zoneinfo import ZoneInfo # Create Pydantic AI agent agent = Agent( 'openai:gpt-4o-mini', system_prompt="You are a helpful time-aware assistant.", retries=3 ) # Add server-side tools @agent.tool_plain async def get_time(timezone: str = 'UTC') -> str: """Get the current time in a specific timezone.""" tz = ZoneInfo(timezone) return datetime.now(tz=tz).strftime("%Y-%m-%d %H:%M:%S %Z") @agent.tool_plain async def calculate(expression: str) -> float: """Safely evaluate a mathematical expression.""" try: # Safe evaluation (restrict to math operations) return eval(expression, {"__builtins__": {}}, {}) except Exception as e: return f"Error: {str(e)}" # Convert to AG-UI FastAPI app app = agent.to_ag_ui() # Run: uvicorn module:app --host 0.0.0.0 --port 8000 # The endpoint is automatically configured at POST / ``` -------------------------------- ### AG-UI Binary Protocol Buffers Response Format Source: https://context7.com/ag-ui-protocol/docs/llms.txt This example outlines the binary response format used by the AG-UI Protocol, employing Protocol Buffers for efficient data serialization. It specifies a 4-byte length prefix followed by the protobuf-encoded event data. This format is optimized for high-throughput scenarios where minimizing data size and parsing overhead is crucial, such as for RunStartedEvent and TextMessageContentEvent. ```http HTTP/1.1 200 OK Content-Type: application/vnd.ag-ui.event+proto Cache-Control: no-cache Connection: keep-alive [4-byte length prefix: 0x00000042] [66 bytes of protobuf-encoded RunStartedEvent] [4-byte length prefix: 0x00000038] [56 bytes of protobuf-encoded TextMessageStartEvent] [4-byte length prefix: 0x0000002A] [42 bytes of protobuf-encoded TextMessageContentEvent] ... ``` -------------------------------- ### AG-UI SSE Response Format Example Source: https://context7.com/ag-ui-protocol/docs/llms.txt This snippet demonstrates the structure of a Server-Sent Events (SSE) response from the AG-UI Protocol. It shows how different events like RUN_STARTED, TEXT_MESSAGE_CONTENT, TOOL_CALL_START, and STATE_SNAPSHOT are transmitted as JSON objects prefixed with 'data:'. This format is suitable for real-time streaming of conversational data. ```http HTTP/1.1 200 OK Content-Type: text/event-stream Cache-Control: no-cache Connection: keep-alive data: {"type":"RUN_STARTED","threadId":"thread_abc123","runId":"run_xyz789","timestamp":1234567890} data: {"type":"TEXT_MESSAGE_START","messageId":"msg_3","role":"assistant","timestamp":1234567891} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"I'll ","timestamp":1234567892} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"check ","timestamp":1234567893} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"the ","timestamp":1234567894} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"weather ","timestamp":1234567895} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"for ","timestamp":1234567896} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"you.","timestamp":1234567897} data: {"type":"TOOL_CALL_START","toolCallId":"call_001","toolCallName":"get_weather","parentMessageId":"msg_3","timestamp":1234567898} data: {"type":"TOOL_CALL_ARGS","toolCallId":"call_001","delta":"{\"location\":","timestamp":1234567899} data: {"type":"TOOL_CALL_ARGS","toolCallId":"call_001","delta":"\"New York, NY\"}","timestamp":1234567900} data: {"type":"TOOL_CALL_END","toolCallId":"call_001","timestamp":1234567901} data: {"type":"TOOL_CALL_RESULT","messageId":"msg_4","toolCallId":"call_001","content":"72°F, Sunny, Light breeze","role":"tool","timestamp":1234567902} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":" The ","timestamp":1234567903} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"weather ","timestamp":1234567904} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"in ","timestamp":1234567905} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"New ","timestamp":1234567906} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"York ","timestamp":1234567907} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"is ","timestamp":1234567908} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"currently ","timestamp":1234567909} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"72°F ","timestamp":1234567910} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"and ","timestamp":1234567911} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"sunny!","timestamp":1234567912} data: {"type":"TEXT_MESSAGE_END","messageId":"msg_3","timestamp":1234567913} data: {"type":"STATE_SNAPSHOT","snapshot":{"userPreferences":{"theme":"dark"},"sessionData":{"startedAt":1234567890},"lastWeatherCheck":"New York, NY"},"timestamp":1234567914} data: {"type":"RUN_FINISHED","threadId":"thread_abc123","runId":"run_xyz789","result":{"success":true},"timestamp":1234567915} ``` -------------------------------- ### AG-UI Error Response Format Example Source: https://context7.com/ag-ui-protocol/docs/llms.txt This snippet illustrates the Server-Sent Events (SSE) format for error responses within the AG-UI Protocol. It includes a RUN_STARTED event followed by a RUN_ERROR event, specifying the error message, a unique error code, and a timestamp. This format ensures that clients can gracefully handle and report issues that occur during agent execution. ```http HTTP/1.1 200 OK Content-Type: text/event-stream data: {"type":"RUN_STARTED","threadId":"thread_abc123","runId":"run_xyz789"} data: {"type":"RUN_ERROR","message":"Failed to connect to weather API","code":"EXTERNAL_API_ERROR","timestamp":1234567890} ``` -------------------------------- ### Google ADK Middleware Connection Source: https://context7.com/ag-ui-protocol/docs/llms.txt Connects Google Agent Development Kit agents to the AG-UI protocol using middleware. This example sets up a FastAPI application with CORS middleware and integrates ADK agents. Dependencies include `adk_middleware`, `google.adk.agents`, `google.adk.tools`, and `fastapi`. ```python from adk_middleware import ADKAgent, add_adk_fastapi_endpoint from google.adk.agents import Agent from google.adk.tools import Tool from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware ``` -------------------------------- ### Initialize and Run HTTP Agent Client with Streaming Source: https://context7.com/ag-ui-protocol/docs/llms.txt This snippet demonstrates how to initialize an HttpAgent with specific configurations like URL, headers, thread ID, and initial messages. It then shows how to stream chat interactions, handling text message events, tool calls, and state changes. Dependencies include '@ag-ui/client' and Node.js 'crypto'. ```typescript import { HttpAgent } from "@ag-ui/client"; import { randomUUID } from "crypto"; // Initialize agent const agent = new HttpAgent({ url: "http://localhost:8000/agent", headers: { Authorization: "Bearer token" }, threadId: "user-session-123", initialMessages: [ { id: "1", role: "system", content: "You are a helpful assistant." } ], debug: true }); // Run with streaming subscriber async function chat(userMessage: string) { agent.messages.push({ id: randomUUID(), role: "user", content: userMessage }); const result = await agent.runAgent( { tools: [], context: [], forwardedProps: {} }, { onTextMessageStartEvent() { process.stdout.write("\nAssistant: "); }, onTextMessageContentEvent({ event }) { process.stdout.write(event.delta); }, onTextMessageEndEvent() { console.log("\n"); }, onToolCallStartEvent({ event }) { console.log(`\n[Calling: ${event.toolCallName}]`); }, onStateChanged({ state }) { console.log("State updated:", state); } } ); return result; // { result: any, newMessages: Message[] } } await chat("What's the weather in New York?"); ``` -------------------------------- ### Pydantic AI Agent Creation and AG-UI FastAPI App Source: https://context7.com/ag-ui-protocol/docs/llms.txt This section demonstrates how to create a Pydantic AI agent, add server-side tools, and convert it into an AG-UI compatible FastAPI application. ```APIDOC ## Create Pydantic AI agent ```python from datetime import datetime from zoneinfo import ZoneInfo # Assuming Agent is imported from a relevant library # from your_agent_library import Agent agent = Agent( 'openai:gpt-4o-mini', system_prompt="You are a helpful time-aware assistant.", retries=3 ) # Add server-side tools @agent.tool_plain async def get_time(timezone: str = 'UTC') -> str: """Get the current time in a specific timezone.""" tz = ZoneInfo(timezone) return datetime.now(tz=tz).strftime("%Y-%m-%d %H:%M:%S %Z") @agent.tool_plain async def calculate(expression: str) -> float: """Safely evaluate a mathematical expression.""" try: # Safe evaluation (restrict to math operations) return eval(expression, {"__builtins__": {}}, {{}}) except Exception as e: return f"Error: {str(e)}" # Convert to AG-UI FastAPI app app = agent.to_ag_ui() # To run this application, you would typically use a command like: # uvicorn your_module_name:app --host 0.0.0.0 --port 8000 ``` ### Description This code initializes an AI agent with a specific model and system prompt, defines two asynchronous tools (`get_time` and `calculate`) that can be used by the agent, and then converts the agent into a FastAPI application compatible with the AG-UI framework. The tools are registered using the `@agent.tool_plain` decorator. ### Method POST ### Endpoint `/` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **prompt** (string) - Required - The user's input or query to the agent. ### Request Example ```json { "prompt": "What time is it in Tokyo?" } ``` ### Response #### Success Response (200) - **response** (string) - The agent's generated response. #### Response Example ```json { "response": "The current time in Tokyo is 2023-10-27 10:00:00 JST." } ``` ``` -------------------------------- ### Frontend Tool Integration with AG-UI Client Source: https://context7.com/ag-ui-protocol/docs/llms.txt Define and handle client-side tools for AG-UI agents using TypeScript. This involves initializing the HttpAgent, defining tools with JSON Schema for their parameters, and implementing event handlers to manage tool calls, arguments, and execution of corresponding frontend actions. It requires the `@ag-ui/client` library. ```typescript import { HttpAgent } from "@ag-ui/client"; const agent = new HttpAgent({ url: "http://localhost:8000/agent" }); // Define frontend tools with JSON Schema const frontendTools = [ { name: "set_background_color", description: "Changes the background color of the page", parameters: { type: "object", properties: { color: { type: "string", description: "CSS color value" } }, required: ["color"] } }, { name: "show_notification", description: "Shows a notification to the user", parameters: { type: "object", properties: { message: { type: "string" }, type: { type: "string", enum: ["info", "warning", "error"] } }, required: ["message"] } }, { name: "update_chart", description: "Updates a data visualization", parameters: { type: "object", properties: { chartId: { type: "string" }, data: { type: "array", items: { type: "number" } } }, required: ["chartId", "data"] } } ]; // Map to track tool calls const toolCalls = new Map(); // Run with tool handling await agent.runAgent( { tools: frontendTools }, { onToolCallStartEvent({ event }) { toolCalls.set(event.toolCallId, { name: event.toolCallName, args: "" }); }, onToolCallArgsEvent({ event }) { const call = toolCalls.get(event.toolCallId); call.args += event.delta; }, async onToolCallEndEvent({ event }) { const call = toolCalls.get(event.toolCallId); const args = JSON.parse(call.args); // Execute frontend action if (call.name === "set_background_color") { document.body.style.backgroundColor = args.color; } else if (call.name === "show_notification") { showNotification(args.message, args.type); } else if (call.name === "update_chart") { updateChart(args.chartId, args.data); } } } ); ``` -------------------------------- ### Pydantic AI Integration for AG-UI Servers Source: https://context7.com/ag-ui-protocol/docs/llms.txt Demonstrates a simplified approach to integrating Pydantic AI agents with the AG-UI protocol. This code snippet shows a one-line import that enables Pydantic AI agents to function as AG-UI compatible servers. It requires the `pydantic-ai` library and standard Python modules like `datetime` and `zoneinfo`. ```python from pydantic_ai import Agent from datetime import datetime from zoneinfo import ZoneInfo ``` -------------------------------- ### Connect to LangGraph Cloud with Interrupt Handling Source: https://context7.com/ag-ui-protocol/docs/llms.txt Shows how to connect to LangGraph Cloud deployments using the `LangGraphAgent` class, enabling interrupt handling for human-in-the-loop workflows. It details configuration options like `graphId`, `deploymentUrl`, and interrupt points, and demonstrates how to run an agent with custom event handlers for step progression and state changes. This integration is useful for complex, multi-step processes requiring human oversight. ```typescript import { LangGraphAgent } from "@ag-ui/langgraph"; // Connect to LangGraph Cloud const agent = new LangGraphAgent({ graphId: "invoice-processor", deploymentUrl: "https://your-deployment.langgraph.com", langsmithApiKey: process.env.LANGSMITH_API_KEY, threadId: "user-session-456", checkpointId: "latest", interruptBefore: ["approval_step", "review_step"], interruptAfter: [] }); // Run with interrupt handling const result = await agent.runAgent( { messages: [{ id: "msg1", role: "user", content: "Process invoice-2024-001.pdf" }], state: { invoiceId: "inv-001" } }, { onStepStartedEvent({ event }) { console.log(`Starting: ${event.stepName}`); console.log(`Node: ${event.node}, Step: ${event.step}`); }, onStepFinishedEvent({ event }) { console.log(`Completed: ${event.stepName}`); }, onStateChanged({ state }) { // LangGraph state updates console.log("Graph state:", state); if (state.approval_needed) { console.log("⏸️ Waiting for approval:"); console.log("Action:", state.pending_action); console.log("Amount:", state.amount); // Pause execution - user must resume via API } }, onRunFinishedEvent({ event, result }) { console.log("Processing complete:", result); } } ); // Resume after interrupt // POST to LangGraph Cloud API with approval decision ``` -------------------------------- ### FastAPI Server with AG-UI Protocol Source: https://context7.com/ag-ui-protocol/docs/llms.txt Implement an AG-UI compatible server endpoint using FastAPI. This snippet handles content negotiation for Server-Sent Events (SSE) or Protocol Buffers, manages thread states, and streams agent responses including run start/finish events, state snapshots, and text messages. It requires FastAPI and AG-UI core libraries. ```python from fastapi import FastAPI, Request from fastapi.responses import StreamingResponse from ag_ui.core import ( RunAgentInput, EventType, RunStartedEvent, RunFinishedEvent, TextMessageStartEvent, TextMessageContentEvent, TextMessageEndEvent, StateSnapshotEvent ) from ag_ui.encoder import EventEncoder import uuid app = FastAPI() thread_states = {} @app.post("/agent") async def agent_endpoint(input_data: RunAgentInput, request: Request): # Content negotiation: SSE or Protocol Buffers encoder = EventEncoder(accept=request.headers.get("accept")) async def event_generator(): # Retrieve and update state current_state = thread_states.get(input_data.thread_id, {}) current_state.update(input_data.state or {}) current_state["message_count"] = len(input_data.messages) current_state["last_user_message"] = input_data.messages[-1].content # Start run yield encoder.encode(RunStartedEvent( type=EventType.RUN_STARTED, thread_id=input_data.thread_id, run_id=input_data.run_id )) # Send state snapshot yield encoder.encode(StateSnapshotEvent( type=EventType.STATE_SNAPSHOT, snapshot=current_state )) # Stream message response message_id = str(uuid.uuid4()) yield encoder.encode(TextMessageStartEvent( type=EventType.TEXT_MESSAGE_START, message_id=message_id, role="assistant" )) response_text = f"Received {current_state['message_count']} messages" for word in response_text.split(): yield encoder.encode(TextMessageContentEvent( type=EventType.TEXT_MESSAGE_CONTENT, message_id=message_id, delta=word + " " )) yield encoder.encode(TextMessageEndEvent( type=EventType.TEXT_MESSAGE_END, message_id=message_id )) # Save state and finish thread_states[input_data.thread_id] = current_state yield encoder.encode(RunFinishedEvent( type=EventType.RUN_FINISHED, thread_id=input_data.thread_id, run_id=input_data.run_id )) return StreamingResponse( event_generator(), media_type=encoder.get_content_type() ) # Run: uvicorn module:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Mastra Agent Configuration with Memory Persistence Source: https://context7.com/ag-ui-protocol/docs/llms.txt Configures Mastra agents with memory persistence and resource management using various storage options. It defines tools for agent capabilities and integrates with the AG-UI protocol. Dependencies include `@ai-sdk/openai`, `@mastra/core/agent`, `@ag-ui/mastra`, and `@mastra/memory`. ```typescript import { openai } from "@ai-sdk/openai"; import { Agent } from "@mastra/core/agent"; import { MastraAgent } from "@ag-ui/mastra"; import { Memory } from "@mastra/memory"; import { LibSQLStore } from "@mastra/memory/storage"; // Define tools const weatherTool = { name: "get_weather", description: "Get weather for a location", parameters: { type: "object", properties: { location: { type: "string" } } }, async execute({ location }: { location: string }) { // Weather API call return `Weather in ${location}: 72°F, Sunny`; } }; const browserTool = { name: "search_web", description: "Search the web for information", parameters: { type: "object", properties: { query: { type: "string" } } }, async execute({ query }: { query: string }) { // Web search implementation return `Search results for: ${query}`; } }; // Create Mastra agent with memory const mastraAgent = new Agent({ name: "Assistant", instructions: "You are a helpful assistant with access to weather and web search.", model: openai("gpt-4o-mini"), tools: { weatherTool, browserTool }, memory: new Memory({ storage: new LibSQLStore({ url: process.env.DATABASE_URL || "file:./mastra.db" }) }) }); // Wrap with AG-UI protocol const agent = new MastraAgent({ agent: mastraAgent, resourceId: "user-123", threadId: "conversation-456" }); // Use like any AG-UI agent const result = await agent.runAgent({ messages: [ { id: "1", role: "user", content: "What's the weather in Tokyo?" } ] }); console.log(result.newMessages); ``` -------------------------------- ### Binary Response Format (Protocol Buffers) Source: https://context7.com/ag-ui-protocol/docs/llms.txt This section describes the binary response format using Protocol Buffers, including length prefixes for each event. ```APIDOC ## Binary Response Format (Protocol Buffers) ### Description This endpoint returns real-time events using Protocol Buffers encoded data. Each event is preceded by a 4-byte length prefix. ### Method GET ### Endpoint `/events/proto` (Example endpoint) ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Content-Type**: `application/vnd.ag-ui.event+proto` - **Cache-Control**: `no-cache` - **Connection**: `keep-alive` Each message consists of a 4-byte length prefix (big-endian) followed by the Protocol Buffers encoded event data. #### Response Example ``` HTTP/1.1 200 OK Content-Type: application/vnd.ag-ui.event+proto Cache-Control: no-cache Connection: keep-alive [4-byte length prefix: 0x00000042] [66 bytes of protobuf-encoded RunStartedEvent] [4-byte length prefix: 0x00000038] [56 bytes of protobuf-encoded TextMessageStartEvent] ``` ``` -------------------------------- ### LangGraph Cloud Integration Source: https://context7.com/ag-ui-protocol/docs/llms.txt Connect to LangGraph Cloud deployments with interrupt handling for human-in-the-loop workflows. ```APIDOC ## LangGraph Cloud Integration Connect to LangGraph Cloud deployments with interrupt handling for human-in-the-loop workflows. ### Method POST ### Endpoint `/run` (Assumed, as `agent.runAgent` is called) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **messages**: Array of message objects. - **id**: string - **role**: "user" | "assistant" | "system" | "developer" - **content**: string **state**: Any object representing the graph's state. ### Request Example (Client-side setup for running the agent) ```typescript import { LangGraphAgent } from "@ag-ui/langgraph"; // Connect to LangGraph Cloud const agent = new LangGraphAgent({ graphId: "invoice-processor", deploymentUrl: "https://your-deployment.langgraph.com", langsmithApiKey: process.env.LANGSMITH_API_KEY, threadId: "user-session-456", checkpointId: "latest", interruptBefore: ["approval_step", "review_step"], interruptAfter: [] }); // Run with interrupt handling const result = await agent.runAgent( { messages: [{ id: "msg1", role: "user", content: "Process invoice-2024-001.pdf" }], state: { invoiceId: "inv-001" } }, { onStepStartedEvent({ event }) { console.log(`Starting: ${event.stepName}`); console.log(`Node: ${event.node}, Step: ${event.step}`); }, onStepFinishedEvent({ event }) { console.log(`Completed: ${event.stepName}`); }, onStateChanged({ state }) { // LangGraph state updates console.log("Graph state:", state); if (state.approval_needed) { console.log("⏸️ Waiting for approval:"); console.log("Action:", state.pending_action); console.log("Amount:", state.amount); // Pause execution - user must resume via API } }, onRunFinishedEvent({ event, result }) { console.log("Processing complete:", result); } } ); // To resume after an interrupt, you would typically make a POST request // to the LangGraph Cloud API with the necessary approval decision. // Example: // POST /resume// // Body: { "decision": "approved", "amount": 100.50 } ``` ### Response #### Success Response (200) - **result**: Any - The final result of the agent run. - **state**: Any - The final state of the LangGraph. #### Response Example (Conceptual, as the actual response depends on the graph execution) ```json { "result": { "status": "processed", "invoice_number": "2024-001" }, "state": { "invoiceId": "inv-001", "processed": true } } ``` ``` -------------------------------- ### Multi-Agent Orchestration Source: https://context7.com/ag-ui-protocol/docs/llms.txt Demonstrates how to create and route requests to specialized agents for coordinating complex workflows using the AG-UI client. ```APIDOC ## Multi-Agent Orchestration Route requests to specialized agents and coordinate complex workflows. ### Description This section provides a TypeScript example demonstrating the creation of specialized agents (general, technical, creative, data) and intelligent routing of messages to them. It also shows how to orchestrate complex tasks by breaking them down, executing subtasks with appropriate agents, and synthesizing the results. ### Usage Examples **Creating and Routing Agents:** ```typescript // Create specialized agents const agents = { general: new HttpAgent({ url: "/agents/general", description: "General purpose assistant" }), technical: new HttpAgent({ url: "/agents/technical", description: "Technical support specialist" }), creative: new HttpAgent({ url: "/agents/creative", description: "Creative writing assistant" }), data: new HttpAgent({ url: "/agents/data", description: "Data analysis expert" }) }; // Route a message to the appropriate agent based on content async function routeToAgent(message: string, context?: any): Promise<{ agent: string; result: any }> { const agentType = detectAgentType(message); const agent = agents[agentType]; console.log(`Routing to ${agentType} agent`); const result = await agent.runAgent({ messages: [{ id: "1", role: "user", content: message }], context: context ? [{ description: "Context", value: JSON.stringify(context) }] : [] }, { onStepStartedEvent({ event }) { console.log(`[${agentType}] Step: ${event.stepName}`); } }); return { agent: agentType, result }; } function detectAgentType(message: string): keyof typeof agents { // ... implementation for detecting agent type ... return "general"; } ``` **Coordinating Agents for Complex Tasks:** ```typescript // Orchestrate a task involving multiple agents async function coordinateAgents(task: string) { // Step 1: Planning agent breaks down task const plan = await agents.general.runAgent({ messages: [{ id: "1", role: "user", content: `Break down this task into subtasks: ${task}` }] }); // Step 2: Execute subtasks with specialized agents const subtasks = parseSubtasks(plan.result); // Assuming parseSubtasks exists const results = []; for (const subtask of subtasks) { const { agent, result } = await routeToAgent(subtask.description); results.push({ subtask, agent, result }); } // Step 3: Synthesis agent combines results const synthesis = await agents.general.runAgent({ messages: [{ id: "2", role: "user", content: `Synthesize these results: ${JSON.stringify(results)}` }] }); return synthesis; } // Example usage: const result = await coordinateAgents( "Analyze sales data, create visualizations, and write a summary report" ); ``` ### Dependencies - `@ag-ui/client` (for `HttpAgent`) ``` -------------------------------- ### Define ADK Tools and Agent with FastAPI Endpoint Source: https://context7.com/ag-ui-protocol/docs/llms.txt This Python code defines custom tools (SearchTool, CalculatorTool) for an ADK agent, creates the agent, wraps it with AG-UI middleware, and sets up a FastAPI application with a CORS middleware and an AG-UI endpoint. The agent is then run using uvicorn. ```python from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from ag_ui.middleware import ADKAgent from adk.agent import Agent # Define ADK tools class SearchTool(Tool): name = "search" description = "Search for information" def execute(self, query: str) -> str: # Search implementation return f"Search results for: {query}" class CalculatorTool(Tool): name = "calculate" description = "Perform calculations" def execute(self, expression: str) -> float: try: return eval(expression, {"__builtins__": {}}) except Exception as e: return f"Error: {str(e)}" # Create ADK agent adk_agent = Agent( name="assistant", instruction="You are a helpful assistant with search and calculation capabilities.", tools=[SearchTool(), CalculatorTool()] ) # Wrap with AG-UI middleware ag_ui_agent = ADKAgent( adk_agent=adk_agent, app_name="my_app", user_id="user123" ) # Create FastAPI endpoint app = FastAPI() # CORS for browser clients app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Add AG-UI endpoint add_adk_fastapi_endpoint( app, ag_ui_agent, path="/agent" ) # Run: uvicorn module:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### POST /agent - HTTP Protocol Specification Source: https://context7.com/ag-ui-protocol/docs/llms.txt Defines the request and response format for the AG-UI HTTP transport, including SSE and binary encodings. ```APIDOC ## POST /agent ### Description This endpoint handles requests for agent interactions within the AG-UI system. It supports Server-Sent Events (SSE) for streaming responses and can handle binary data. ### Method `POST` ### Endpoint `/agent` ### Headers - `Content-Type`: `application/json` (for request body) - `Accept`: `text/event-stream` (to receive SSE responses) - `Authorization`: `Bearer your-token-here` ### Request Body - **threadId** (string) - Required - Identifier for the conversation thread. - **runId** (string) - Optional - Identifier for a specific run within a thread. - **state** (object) - Optional - Application state to be passed to the agent. - **userPreferences** (object) - Optional - User-specific preferences. - **sessionData** (object) - Optional - Session-related data. - **messages** (array) - Required - Array of message objects for the conversation. - **id** (string) - Required - Unique message ID. - **role** (string) - Required - Role of the message sender (e.g., `system`, `user`, `assistant`). - **content** (string) - Required - The content of the message. - **tools** (array) - Optional - Array of tool definitions available to the agent. - **name** (string) - Required - The name of the tool. - **description** (string) - Optional - A description of what the tool does. - **parameters** (object) - Optional - Tool parameter schema (OpenAPI schema format). - **context** (array) - Optional - Additional context for the agent. - **description** (string) - Required - Description of the context value. - **value** (any) - Required - The context value. - **forwardedProps** (object) - Optional - Properties to be forwarded to the agent or downstream services. - **customerId** (string) - Optional. - **apiVersion** (string) - Optional. ### Request Example ```json { "threadId": "thread_abc123", "runId": "run_xyz789", "state": { "userPreferences": { "theme": "dark" }, "sessionData": { "startedAt": 1234567890 } }, "messages": [ { "id": "msg_1", "role": "system", "content": "You are a helpful assistant." }, { "id": "msg_2", "role": "user", "content": "What's the weather like?" } ], "tools": [ { "name": "get_weather", "description": "Get current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name or coordinates" } }, "required": ["location"] } } ], "context": [ { "description": "User location", "value": "New York, NY" } ], "forwardedProps": { "customerId": "cust_123", "apiVersion": "v1" } } ``` ### Response Responses are typically streamed using Server-Sent Events (SSE). #### Event Stream Format Each event follows the standard SSE format: ``` event: event_name id: event_id data: {"key": "value"} ``` Common `event_name` values include `message_start`, `content_block_start`, `text_delta`, `tool_code_delta`, `tool_code_finish`, `content_block_end`, `message_delta`, `message_done`, `run_done`. #### Error Response Errors are typically communicated via SSE events like `error` or through standard HTTP error codes if the initial request fails. - **400 Bad Request**: Invalid request format. - **401 Unauthorized**: Missing or invalid authentication. - **500 Internal Server Error**: Server-side issue. #### Response Example (Illustrative SSE Stream) ```http event: message_start id: msg_3 data: {"role": "assistant"} event: content_block_start id: cb_1 data: {"type": "text"} event: text_delta id: td_1 data: {"value": "The weather in "} event: text_delta id: td_2 data: {"value": "New York is currently sunny and 75°F."} event: content_block_end id: cb_1 event: message_done id: msg_3 ``` ``` -------------------------------- ### HTTP: AG-UI Request Format Source: https://context7.com/ag-ui-protocol/docs/llms.txt Defines the structure of an HTTP POST request for the AG-UI agent endpoint. It includes fields for thread and run IDs, state, messages, tools, context, and forwarded properties. Supports Server-Sent Events (SSE) for responses. ```http # Request Format POST /agent HTTP/1.1 Host: api.example.com Content-Type: application/json Accept: text/event-stream Authorization: Bearer your-token-here { "threadId": "thread_abc123", "runId": "run_xyz789", "state": { "userPreferences": { "theme": "dark" }, "sessionData": { "startedAt": 1234567890 } }, "messages": [ { "id": "msg_1", "role": "system", "content": "You are a helpful assistant." }, { "id": "msg_2", "role": "user", "content": "What's the weather like?" } ], "tools": [ { "name": "get_weather", "description": "Get current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name or coordinates" } }, "required": ["location"] } } ], "context": [ { "description": "User location", "value": "New York, NY" } ], "forwardedProps": { "customerId": "cust_123", "apiVersion": "v1" } } ``` -------------------------------- ### Event Encoding and Transport with AG-UI Source: https://context7.com/ag-ui-protocol/docs/llms.txt This Python code demonstrates how to use the AG-UI EventEncoder for content negotiation between Server-Sent Events (SSE) and Protocol Buffers. It shows event creation, encoding into different formats, and usage within a FastAPI streaming response. ```python from ag_ui.encoder import EventEncoder from ag_ui.core import TextMessageContentEvent, EventType from fastapi.responses import StreamingResponse # Create encoder with content negotiation encoder = EventEncoder( accept="application/vnd.ag-ui.event+proto, text/event-stream;q=0.9" ) # Create event event = TextMessageContentEvent( type=EventType.TEXT_MESSAGE_CONTENT, message_id="msg_123", delta="Hello, world!" ) # Encode based on negotiated format if encoder.get_content_type() == "text/event-stream": # SSE format sse_data = encoder.encode(event) # Output: "data: {\"type\":\"TEXT_MESSAGE_CONTENT\",\"messageId\":\"msg_123\",\"delta\":\"Hello, world!\"}\n\n" elif encoder.get_content_type().startswith("application/vnd.ag-ui.event+proto"): # Protocol Buffers binary format binary_data = encoder.encode_binary(event) # Output: [4-byte length prefix][protobuf bytes] # Use in FastAPI streaming response async def stream_events(): yield encoder.encode(event) return StreamingResponse( stream_events(), media_type=encoder.get_content_type() ) ``` -------------------------------- ### Server-Sent Events (SSE) Response Format Source: https://context7.com/ag-ui-protocol/docs/llms.txt This section details the format of Server-Sent Events (SSE) responses, including successful and error scenarios. ```APIDOC ## Server-Sent Events (SSE) Response Format ### Description This endpoint returns real-time events using the Server-Sent Events (SSE) protocol. The `Content-Type` is `text/event-stream`. ### Method GET ### Endpoint `/events` (Example endpoint) ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Content-Type**: `text/event-stream` - **Cache-Control**: `no-cache` - **Connection**: `keep-alive` Each event is prefixed with `data: ` followed by a JSON object representing the event details. **Event Types:** - `RUN_STARTED`: Indicates the start of a run. - `TEXT_MESSAGE_START`: Indicates the start of a text message. - `TEXT_MESSAGE_CONTENT`: Contains a piece of text message content. - `TOOL_CALL_START`: Indicates the start of a tool call. - `TOOL_CALL_ARGS`: Contains arguments for a tool call. - `TOOL_CALL_END`: Indicates the end of a tool call. - `TOOL_CALL_RESULT`: Contains the result of a tool call. - `TEXT_MESSAGE_END`: Indicates the end of a text message. - `STATE_SNAPSHOT`: Provides a snapshot of the current state. - `RUN_FINISHED`: Indicates the completion of a run. #### Response Example (Success) ``` HTTP/1.1 200 OK Content-Type: text/event-stream Cache-Control: no-cache Connection: keep-alive data: {"type":"RUN_STARTED","threadId":"thread_abc123","runId":"run_xyz789","timestamp":1234567890} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_3","delta":"I'll ","timestamp":1234567892} data: {"type":"RUN_FINISHED","threadId":"thread_abc123","runId":"run_xyz789","result":{"success":true},"timestamp":1234567915} ``` #### Error Response Example ``` HTTP/1.1 200 OK Content-Type: text/event-stream data: {"type":"RUN_STARTED","threadId":"thread_abc123","runId":"run_xyz789"} data: {"type":"RUN_ERROR","message":"Failed to connect to weather API","code":"EXTERNAL_API_ERROR","timestamp":1234567890} ``` ``` -------------------------------- ### React Component Integration with AG-UI Agents Source: https://context7.com/ag-ui-protocol/docs/llms.txt Integrates AG-UI agents into React applications, handling state management and streaming updates. It uses `HttpAgent` for communication and manages messages, loading states, and agent states. Dependencies include `@ag-ui/client` and `@ag-ui/core`. ```typescript import { HttpAgent } from "@ag-ui/client"; import { useState, useEffect, useRef } from "react"; import type { Message } from "@ag-ui/core"; function ChatComponent() { const [agent] = useState(() => new HttpAgent({ url: "/api/agent", threadId: `user-${Date.now()}` })); const [messages, setMessages] = useState([]); const [currentMessage, setCurrentMessage] = useState(""); const [isLoading, setIsLoading] = useState(false); const [agentState, setAgentState] = useState({}); const sendMessage = async (content: string) => { if (!content.trim()) return; // Add user message const userMsg: Message = { id: crypto.randomUUID(), role: "user", content: content.trim() }; agent.messages.push(userMsg); setMessages([...agent.messages]); setCurrentMessage(""); setIsLoading(true); try { await agent.runAgent( { tools: [ { name: "update_preferences", description: "Update user preferences", parameters: { type: "object", properties: { theme: { type: "string", enum: ["light", "dark"] }, language: { type: "string" } } } } ] }, { onMessagesChanged({ messages }) { setMessages([...messages]); }, onStateChanged({ state }) { setAgentState(state); }, onToolCallResultEvent({ event }) { console.log("Tool executed:", event.toolCallId); } } ); } catch (error) { console.error("Agent error:", error); } finally { setIsLoading(false); } }; return (
{messages.map(msg => (
{msg.role}: {msg.content}
))}
{agentState.userPreferences && (
Theme: {agentState.userPreferences.theme}
)}
setCurrentMessage(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && sendMessage(currentMessage)} disabled={isLoading} placeholder="Type a message..." />
); } export default ChatComponent; ```