|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +from pydantic_ai import Agent, RunContext # type: ignore |
| 4 | +from pydantic_ai.mcp import MCPServerStreamableHTTP # type: ignore |
| 5 | +from pydantic_ai.messages import ( # type: ignore |
| 6 | + FunctionToolCallEvent, |
| 7 | +) |
| 8 | + |
| 9 | + |
| 10 | +async def main(): |
| 11 | + """Start a conversation using PydanticAI with an HTTP MCP server.""" |
| 12 | + |
| 13 | + prod_environment_id = os.environ.get("DBT_PROD_ENV_ID", os.getenv("DBT_ENV_ID")) |
| 14 | + token = os.environ.get("DBT_TOKEN") |
| 15 | + host = os.environ.get("DBT_HOST", "cloud.getdbt.com") |
| 16 | + |
| 17 | + # Configure MCP server connection |
| 18 | + mcp_server_url = f"https://{host}/api/ai/v1/mcp/" |
| 19 | + mcp_server_headers = { |
| 20 | + "Authorization": f"token {token}", |
| 21 | + "x-dbt-prod-environment-id": prod_environment_id, |
| 22 | + } |
| 23 | + server = MCPServerStreamableHTTP(url=mcp_server_url, headers=mcp_server_headers) |
| 24 | + |
| 25 | + # Initialize the agent with OpenAI model and MCP tools |
| 26 | + # PydanticAI also supports Anthropic models, Google models, and more |
| 27 | + agent = Agent( |
| 28 | + "openai:gpt-5", |
| 29 | + toolsets=[server], |
| 30 | + system_prompt="You are a helpful AI assistant with access to MCP tools.", |
| 31 | + ) |
| 32 | + |
| 33 | + print("Starting conversation with PydanticAI + MCP server...") |
| 34 | + print("Type 'quit' to exit\n") |
| 35 | + |
| 36 | + async with agent: |
| 37 | + while True: |
| 38 | + try: |
| 39 | + user_input = input("You: ").strip() |
| 40 | + |
| 41 | + if user_input.lower() in ["quit", "exit", "q"]: |
| 42 | + print("Goodbye!") |
| 43 | + break |
| 44 | + |
| 45 | + if not user_input: |
| 46 | + continue |
| 47 | + |
| 48 | + # Event handler for real-time tool call detection |
| 49 | + async def event_handler(ctx: RunContext, event_stream): |
| 50 | + async for event in event_stream: |
| 51 | + if isinstance(event, FunctionToolCallEvent): |
| 52 | + print(f"\n🔧 Tool called: {event.part.tool_name}") |
| 53 | + print(f" Arguments: {event.part.args}") |
| 54 | + print("Assistant: ", end="", flush=True) |
| 55 | + |
| 56 | + # Stream the response with real-time events |
| 57 | + print("Assistant: ", end="", flush=True) |
| 58 | + async with agent.run_stream( |
| 59 | + user_input, event_stream_handler=event_handler |
| 60 | + ) as result: |
| 61 | + async for text in result.stream_text(delta=True): |
| 62 | + print(text, end="", flush=True) |
| 63 | + print() # New line after response |
| 64 | + |
| 65 | + except KeyboardInterrupt: |
| 66 | + print("\nGoodbye!") |
| 67 | + break |
| 68 | + except Exception as e: |
| 69 | + print(f"Error: {e}") |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + asyncio.run(main()) |
0 commit comments