|
| 1 | +import asyncio |
| 2 | +from coagent.agents.react_agent import ( |
| 3 | + ReActAgent, |
| 4 | + InputMessage, |
| 5 | + InputHistory, |
| 6 | + OutputMessage, |
| 7 | + MessageOutputItem, |
| 8 | + ToolCallItem, |
| 9 | + ToolCallOutputItem, |
| 10 | + ToolCallProgressItem, |
| 11 | +) |
| 12 | +from coagent.core import AgentSpec, new, init_logger |
| 13 | +from coagent.runtimes import LocalRuntime |
| 14 | +import mcputil |
| 15 | + |
| 16 | + |
| 17 | +async def main(): |
| 18 | + async with LocalRuntime() as runtime: |
| 19 | + # Alternative usage: |
| 20 | + # ``` |
| 21 | + # mcp_client = mcputil.Client(mcputil.StreamableHTTP(url="http://localhost:8000")) |
| 22 | + # await mcp_client.connect() |
| 23 | + # ... |
| 24 | + # await mcp_client.close() |
| 25 | + # ``` |
| 26 | + async with mcputil.Client( |
| 27 | + mcputil.StreamableHTTP(url="http://localhost:8000") |
| 28 | + ) as mcp_client: |
| 29 | + reporter = AgentSpec( |
| 30 | + "reporter", |
| 31 | + new( |
| 32 | + ReActAgent, |
| 33 | + name="reporter", |
| 34 | + system="You are a helpful weather reporter", |
| 35 | + tools=[mcp_client], |
| 36 | + ), |
| 37 | + ) |
| 38 | + await runtime.register(reporter) |
| 39 | + |
| 40 | + result = await reporter.run( |
| 41 | + InputHistory( |
| 42 | + messages=[ |
| 43 | + InputMessage( |
| 44 | + role="user", content="What's the weather like in Beijing?" |
| 45 | + ) |
| 46 | + ] |
| 47 | + ).encode(), |
| 48 | + stream=True, |
| 49 | + ) |
| 50 | + async for chunk in result: |
| 51 | + msg = OutputMessage.decode(chunk) |
| 52 | + i = msg.item |
| 53 | + match i: |
| 54 | + case MessageOutputItem(): |
| 55 | + print(i.raw_item.content[0].text, end="", flush=True) |
| 56 | + case ToolCallItem(): |
| 57 | + print( |
| 58 | + f"\n[tool#{i.raw_item.call_id} call: {i.raw_item.name}]", |
| 59 | + flush=True, |
| 60 | + ) |
| 61 | + case ToolCallProgressItem(): |
| 62 | + print( |
| 63 | + f"\n[tool#{i.raw_item.call_id} progress: {i.raw_item.message}]", |
| 64 | + flush=True, |
| 65 | + ) |
| 66 | + case ToolCallOutputItem(): |
| 67 | + print( |
| 68 | + f"\n[tool#{i.raw_item.call_id} output: {i.raw_item.output}]", |
| 69 | + flush=True, |
| 70 | + ) |
| 71 | + |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + init_logger() |
| 75 | + asyncio.run(main()) |
0 commit comments