|
| 1 | +"""CLI command for launching a web chat UI for agents.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import sys |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +from pydantic import BaseModel, ImportString, ValidationError |
| 9 | +from rich.console import Console |
| 10 | + |
| 11 | +from pydantic_ai import Agent |
| 12 | +from pydantic_ai.builtin_tools import AbstractBuiltinTool, get_builtin_tool_cls |
| 13 | +from pydantic_ai.models import infer_model |
| 14 | +from pydantic_ai.ui._web import create_web_app, load_mcp_server_tools |
| 15 | + |
| 16 | +__all__ = ['_run_web_command'] |
| 17 | + |
| 18 | + |
| 19 | +class _AgentLoader(BaseModel): |
| 20 | + """Helper model for loading agents using Pydantic ImportString.""" |
| 21 | + |
| 22 | + agent: ImportString # type: ignore[valid-type] |
| 23 | + |
| 24 | + |
| 25 | +def _load_agent(agent_path: str) -> Agent | None: |
| 26 | + """Load an agent from module path in uvicorn style. |
| 27 | +
|
| 28 | + Args: |
| 29 | + agent_path: Path in format 'module:variable', e.g. 'test_agent:my_agent' |
| 30 | +
|
| 31 | + Returns: |
| 32 | + Agent instance or None if loading fails |
| 33 | + """ |
| 34 | + sys.path.insert(0, str(Path.cwd())) |
| 35 | + try: |
| 36 | + loader = _AgentLoader(agent=agent_path) |
| 37 | + agent = loader.agent # pyright: ignore[reportUnknownVariableType,reportUnknownMemberType] |
| 38 | + if not isinstance(agent, Agent): |
| 39 | + return None |
| 40 | + return agent # pyright: ignore[reportUnknownVariableType] |
| 41 | + except ValidationError: |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +def _run_web_command( # noqa: C901 |
| 46 | + agent_path: str | None = None, |
| 47 | + host: str = '127.0.0.1', |
| 48 | + port: int = 7932, |
| 49 | + models: list[str] | None = None, |
| 50 | + tools: list[str] | None = None, |
| 51 | + instructions: str | None = None, |
| 52 | + mcp: str | None = None, |
| 53 | +) -> int: |
| 54 | + """Run the web command to serve an agent via web UI. |
| 55 | +
|
| 56 | + Args: |
| 57 | + agent_path: Agent path in 'module:variable' format. If None, creates generic agent. |
| 58 | + host: Host to bind the server to. |
| 59 | + port: Port to bind the server to. |
| 60 | + models: List of model strings (e.g., ['openai:gpt-5', 'claude-sonnet-4-5']). |
| 61 | + tools: List of builtin tool IDs (e.g., ['web_search', 'code_execution']). |
| 62 | + instructions: System instructions for generic agent. |
| 63 | + mcp: Path to JSON file with MCP server configurations. |
| 64 | + """ |
| 65 | + console = Console() |
| 66 | + |
| 67 | + if agent_path: |
| 68 | + agent = _load_agent(agent_path) |
| 69 | + if agent is None: |
| 70 | + console.print(f'[red]Error: Could not load agent from {agent_path}[/red]') |
| 71 | + return 1 |
| 72 | + else: |
| 73 | + agent = Agent() |
| 74 | + |
| 75 | + if instructions: |
| 76 | + |
| 77 | + @agent.system_prompt |
| 78 | + def system_prompt() -> str: # pyright: ignore[reportUnusedFunction] |
| 79 | + return instructions # pragma: no cover |
| 80 | + |
| 81 | + if agent.model is None and not models: |
| 82 | + console.print('[red]Error: At least one model (-m) is required when agent has no model[/red]') |
| 83 | + return 1 |
| 84 | + |
| 85 | + # If no CLI models provided but agent has a model, use agent's model |
| 86 | + if not models and agent.model is not None: |
| 87 | + resolved_model = infer_model(agent.model) |
| 88 | + models = [f'{resolved_model.system}:{resolved_model.model_name}'] |
| 89 | + |
| 90 | + # Collect builtin tools: agent's own + CLI-provided |
| 91 | + all_tool_instances: list[AbstractBuiltinTool] = [] |
| 92 | + |
| 93 | + # Add agent's own builtin tools first (these are always enabled) |
| 94 | + all_tool_instances.extend(agent._builtin_tools) # pyright: ignore[reportPrivateUsage] |
| 95 | + |
| 96 | + # Parse and add CLI tools |
| 97 | + if tools: |
| 98 | + for tool_id in tools: |
| 99 | + tool_cls = get_builtin_tool_cls(tool_id) |
| 100 | + if tool_cls is None or tool_id in ('url_context', 'mcp_server'): |
| 101 | + console.print(f'[yellow]Warning: Unknown tool "{tool_id}", skipping[/yellow]') |
| 102 | + continue |
| 103 | + if tool_id == 'memory': |
| 104 | + console.print('[yellow]Warning: MemoryTool requires agent to have memory configured, skipping[/yellow]') |
| 105 | + continue |
| 106 | + all_tool_instances.append(tool_cls()) |
| 107 | + |
| 108 | + # Load MCP server tools if specified |
| 109 | + if mcp: |
| 110 | + try: |
| 111 | + mcp_tools = load_mcp_server_tools(mcp) |
| 112 | + all_tool_instances.extend(mcp_tools) |
| 113 | + console.print(f'[dim]Loaded {len(mcp_tools)} MCP server(s) from {mcp}[/dim]') |
| 114 | + except FileNotFoundError as e: |
| 115 | + console.print(f'[red]Error: {e}[/red]') |
| 116 | + return 1 |
| 117 | + except ValidationError as e: |
| 118 | + console.print(f'[red]Error parsing MCP config: {e}[/red]') |
| 119 | + return 1 |
| 120 | + except ValueError as e: # pragma: no cover |
| 121 | + console.print(f'[red]Error: {e}[/red]') |
| 122 | + return 1 |
| 123 | + |
| 124 | + app = create_web_app( |
| 125 | + agent, |
| 126 | + models=models, |
| 127 | + builtin_tools=all_tool_instances if all_tool_instances else None, |
| 128 | + ) |
| 129 | + |
| 130 | + agent_desc = agent_path if agent_path else 'generic agent' |
| 131 | + console.print(f'\n[green]Starting chat UI for {agent_desc}...[/green]') |
| 132 | + console.print(f'Open your browser at: [link=http://{host}:{port}]http://{host}:{port}[/link]') |
| 133 | + console.print('[dim]Press Ctrl+C to stop the server[/dim]\n') |
| 134 | + |
| 135 | + try: |
| 136 | + import uvicorn |
| 137 | + |
| 138 | + uvicorn.run(app, host=host, port=port) |
| 139 | + return 0 # pragma: no cover |
| 140 | + except KeyboardInterrupt: # pragma: no cover |
| 141 | + console.print('\n[dim]Server stopped.[/dim]') |
| 142 | + return 0 |
| 143 | + except ImportError: # pragma: no cover |
| 144 | + console.print('[red]Error: uvicorn is required to run the chat UI[/red]') |
| 145 | + console.print('[dim]Install it with: pip install uvicorn[/dim]') |
| 146 | + return 1 |
| 147 | + except Exception as e: # pragma: no cover |
| 148 | + console.print(f'[red]Error starting server: {e}[/red]') |
| 149 | + return 1 |
0 commit comments