1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import asyncio import pathlib from openai import AsyncOpenAI from openai.types.responses import ResponseTextDeltaEvent from langsmith.client import Client from langsmith.wrappers import OpenAIAgentsTracingProcessor from agents import ( Agent, Runner, set_default_openai_client, OpenAIChatCompletionsModel, set_trace_processors ) from agents.mcp import MCPServerStdio
client = AsyncOpenAI( base_url="https://openrouter.ai/api/v1", api_key="sk-or-xxx" ) set_default_openai_client(client)
set_trace_processors([ OpenAIAgentsTracingProcessor( client=Client(api_key='lsv2_xxx') ) ])
model = OpenAIChatCompletionsModel( model="anthropic/claude-3.7-sonnet", openai_client=client, )
async def main(): samples_dir = pathlib.Path(__file__).parent / "0416"
async with MCPServerStdio(params={ "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", str(samples_dir)], }) as fs_server:
tools = await fs_server.list_tools() print("tools:", tools)
agent = Agent( name="file agent", model=model, mcp_servers=[fs_server], )
result = Runner.run_streamed( agent, "list all python files, and echo the basenames to a new file, named python-files.txt" )
async for event in result.stream_events(): if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent): print(event.data.delta, end='', flush=True)
if __name__ == "__main__": asyncio.run(main())
|