命令行界面 (CLI)
Pydantic AI 自带一个名为 clai(发音为 "clay")的命令行工具,您可以用它在命令行中与各种大语言模型(LLM)进行交互。它提供了一种便捷的方式,让您可以在终端中与语言模型聊天并快速获得答案。
我们最初开发这个命令行工具是为了自用,但后来发现使用频率非常高,所以决定将其作为 Pydantic AI 软件包的一部分分享出来。
我们计划继续增加新功能,例如与 MCP 服务器的交互、访问工具等。
用法
您需要根据打算使用的提供商设置相应的环境变量。
例如,如果您使用 OpenAI,请设置 OPENAI_API_KEY 环境变量
export OPENAI_API_KEY='your-api-key-here'
然后使用 uvx 运行:
uvx clai
或者,要使用 uv 全局安装 clai,请运行:
uv tool install clai
...
clai
或者使用 pip 运行:
pip install clai
...
clai
无论哪种方式,运行 clai 都会启动一个交互式会话,您可以在其中与 AI 模型聊天。交互模式下可用的特殊命令:
/exit: 退出会话/markdown: 以 markdown 格式显示上一次的响应/multiline: 切换多行输入模式(使用 Ctrl+D 提交)/cp: 将上一次的响应复制到剪贴板
帮助
要获取关于命令行工具的帮助,请使用 --help 标志:
uvx clai --help
选择模型
您可以使用 --model 标志指定要使用的模型:
uvx clai --model anthropic:claude-sonnet-4-0
(可用的模型完整列表可以通过 uvx clai --list-models 打印出来)
自定义代理
您可以使用 --agent 标志并提供模块路径和变量名来指定自定义代理:
from pydantic_ai import Agent
agent = Agent('openai:gpt-4.1', instructions='You always respond in Italian.')
然后运行:
uvx clai --agent custom_agent:agent "What's the weather today?"
格式必须是 module:variable,其中:
module是可导入的 Python 模块路径variable是该模块中 Agent 实例的名称
此外,您可以使用 Agent.to_cli_sync() 直接从 Agent 实例启动命令行模式:
from pydantic_ai import Agent
agent = Agent('openai:gpt-4.1', instructions='You always respond in Italian.')
agent.to_cli_sync()
您也可以使用 Agent.to_cli() 的异步接口:
from pydantic_ai import Agent
agent = Agent('openai:gpt-4.1', instructions='You always respond in Italian.')
async def main():
await agent.to_cli()
(您需要添加 asyncio.run(main()) 来运行 main)
消息历史
Agent.to_cli() 和 Agent.to_cli_sync() 都支持 message_history 参数,允许您继续现有对话或提供对话上下文:
from pydantic_ai import Agent
from pydantic_ai.messages import (
ModelMessage,
ModelRequest,
ModelResponse,
TextPart,
UserPromptPart,
)
agent = Agent('openai:gpt-4.1')
# Create some conversation history
message_history: list[ModelMessage] = [
ModelRequest([UserPromptPart(content='What is 2+2?')]),
ModelResponse([TextPart(content='2+2 equals 4.')])
]
# Start CLI with existing conversation context
agent.to_cli_sync(message_history=message_history)
命令行工具将使用提供的对话历史记录启动,允许代理在整个会话中回顾之前的交流并保持上下文。