|
| 1 | +import asyncio |
| 2 | +from coagent.agents.react_agent import ( |
| 3 | + ReActAgent, |
| 4 | + InputMessage, |
| 5 | + InputMessageTextParam, |
| 6 | + InputMessageImageParam, |
| 7 | + InputHistory, |
| 8 | + OutputMessage, |
| 9 | + MessageOutputItem, |
| 10 | + ToolCallItem, |
| 11 | + ToolCallOutputItem, |
| 12 | + ToolCallProgressItem, |
| 13 | +) |
| 14 | +from coagent.core import AgentSpec, new, init_logger |
| 15 | +from coagent.runtimes import LocalRuntime |
| 16 | + |
| 17 | + |
| 18 | +analyzer = AgentSpec( |
| 19 | + "analyzer", |
| 20 | + new( |
| 21 | + ReActAgent, |
| 22 | + name="reporter", |
| 23 | + system="You are a helpful image analyzer", |
| 24 | + ), |
| 25 | +) |
| 26 | + |
| 27 | + |
| 28 | +async def main(): |
| 29 | + async with LocalRuntime() as runtime: |
| 30 | + await runtime.register(analyzer) |
| 31 | + |
| 32 | + result = await analyzer.run( |
| 33 | + InputHistory( |
| 34 | + messages=[ |
| 35 | + InputMessage( |
| 36 | + role="user", |
| 37 | + content=[ |
| 38 | + InputMessageTextParam( |
| 39 | + type="input_text", text="What’s in this image?" |
| 40 | + ), |
| 41 | + InputMessageImageParam( |
| 42 | + detail="auto", |
| 43 | + type="input_image", |
| 44 | + image_url="https://raw.githubusercontent.com/OpenCSGs/coagent/main/assets/coagent-overview.png", |
| 45 | + ), |
| 46 | + ], |
| 47 | + ) |
| 48 | + ] |
| 49 | + ).encode(), |
| 50 | + stream=True, |
| 51 | + ) |
| 52 | + async for chunk in result: |
| 53 | + msg = OutputMessage.decode(chunk) |
| 54 | + i = msg.item |
| 55 | + match i: |
| 56 | + case MessageOutputItem(): |
| 57 | + print(i.raw_item.content[0].text, end="", flush=True) |
| 58 | + case ToolCallItem(): |
| 59 | + print( |
| 60 | + f"\n[tool#{i.raw_item.call_id} call: {i.raw_item.name}]", |
| 61 | + flush=True, |
| 62 | + ) |
| 63 | + case ToolCallProgressItem(): |
| 64 | + print( |
| 65 | + f"\n[tool#{i.raw_item.call_id} progress: {i.raw_item.message}]", |
| 66 | + flush=True, |
| 67 | + ) |
| 68 | + case ToolCallOutputItem(): |
| 69 | + print( |
| 70 | + f"\n[tool#{i.raw_item.call_id} output: {i.raw_item.output}]", |
| 71 | + flush=True, |
| 72 | + ) |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + init_logger() |
| 77 | + asyncio.run(main()) |
0 commit comments