|
| 1 | +"""AG-UI LangGraph agent with Gateway MCP tools, Memory, and Code Interpreter. |
| 2 | +
|
| 3 | +Uses copilotkit's LangGraphAGUIAgent to produce native AG-UI SSE events. |
| 4 | +AgentCore proxies these unchanged when deployed with --protocol AGUI. |
| 5 | +""" |
| 6 | + |
| 7 | +import logging |
| 8 | +import os |
| 9 | + |
| 10 | +from ag_ui.core import RunAgentInput, RunErrorEvent |
| 11 | +from bedrock_agentcore.runtime import BedrockAgentCoreApp, RequestContext |
| 12 | +from copilotkit import CopilotKitMiddleware, LangGraphAGUIAgent |
| 13 | +from langchain.agents import create_agent |
| 14 | +from langchain_aws import ChatBedrock |
| 15 | +from langgraph_checkpoint_aws import AgentCoreMemorySaver |
| 16 | + |
| 17 | +from tools.code_interpreter import LangGraphCodeInterpreterTools |
| 18 | +from tools.gateway import create_gateway_mcp_client |
| 19 | +from utils.auth import extract_user_id_from_context |
| 20 | + |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | + |
| 23 | +app = BedrockAgentCoreApp() |
| 24 | + |
| 25 | +SYSTEM_PROMPT = ( |
| 26 | + "You are a helpful assistant with access to tools via the Gateway and Code Interpreter. " |
| 27 | + "When asked about your tools, list them and explain what they do." |
| 28 | +) |
| 29 | + |
| 30 | + |
| 31 | +def _build_model() -> ChatBedrock: |
| 32 | + return ChatBedrock( |
| 33 | + model_id="us.anthropic.claude-sonnet-4-5-20250929-v1:0", |
| 34 | + temperature=0.1, |
| 35 | + streaming=True, |
| 36 | + beta_use_converse_api=True, |
| 37 | + ) |
| 38 | + |
| 39 | + |
| 40 | +def _create_checkpointer() -> AgentCoreMemorySaver: |
| 41 | + memory_id = os.environ.get("MEMORY_ID") |
| 42 | + if not memory_id: |
| 43 | + raise ValueError("MEMORY_ID environment variable is required") |
| 44 | + return AgentCoreMemorySaver( |
| 45 | + memory_id=memory_id, |
| 46 | + region_name=os.environ.get("AWS_DEFAULT_REGION", "us-east-1"), |
| 47 | + ) |
| 48 | + |
| 49 | + |
| 50 | +async def create_langgraph_agent(): |
| 51 | + """Create a LangGraph agent with Gateway tools, Memory, and Code Interpreter.""" |
| 52 | + mcp_client = await create_gateway_mcp_client() |
| 53 | + tools = await mcp_client.get_tools() |
| 54 | + |
| 55 | + region = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") |
| 56 | + code_tools = LangGraphCodeInterpreterTools(region) |
| 57 | + tools.append(code_tools.execute_python_securely) |
| 58 | + |
| 59 | + return create_agent( |
| 60 | + model=_build_model(), |
| 61 | + tools=tools, |
| 62 | + checkpointer=_create_checkpointer(), |
| 63 | + middleware=[CopilotKitMiddleware()], |
| 64 | + system_prompt=SYSTEM_PROMPT, |
| 65 | + ) |
| 66 | + |
| 67 | + |
| 68 | +class ActorAwareLangGraphAgent(LangGraphAGUIAgent): |
| 69 | + """LangGraphAGUIAgent that creates the graph per-request with fresh tokens.""" |
| 70 | + |
| 71 | + async def run(self, input: RunAgentInput): |
| 72 | + self.graph = await create_langgraph_agent() |
| 73 | + async for event in super().run(input): |
| 74 | + yield event |
| 75 | + |
| 76 | + |
| 77 | +@app.entrypoint |
| 78 | +async def invocations(payload: dict, context: RequestContext): |
| 79 | + input_data = RunAgentInput.model_validate(payload) |
| 80 | + |
| 81 | + user_id = extract_user_id_from_context(context) |
| 82 | + |
| 83 | + agent = ActorAwareLangGraphAgent( |
| 84 | + name="agui_langgraph_agent", |
| 85 | + description="AG-UI LangGraph agent with Gateway MCP tools and Memory", |
| 86 | + graph=None, |
| 87 | + config={"configurable": {"actor_id": user_id}}, |
| 88 | + ) |
| 89 | + |
| 90 | + try: |
| 91 | + async for event in agent.run(input_data): |
| 92 | + if event is not None: |
| 93 | + yield event.model_dump(mode="json", by_alias=True, exclude_none=True) |
| 94 | + except Exception as exc: |
| 95 | + logger.exception("Agent run failed") |
| 96 | + yield RunErrorEvent( |
| 97 | + message=str(exc) or type(exc).__name__, |
| 98 | + code=type(exc).__name__, |
| 99 | + ).model_dump(mode="json", by_alias=True, exclude_none=True) |
| 100 | + |
| 101 | + |
| 102 | +if __name__ == "__main__": |
| 103 | + app.run() |
0 commit comments