关于 ai
`ai` 是面向 Python 3.12+ 的 AI SDK,用于调用模型、构建带 Python 工具执行能力的 Agent,并管理对话历史。它支持通过 AI Gateway 或直接指定提供方访问模型。
主要功能
- 01调用 AI Gateway 或直连模型提供方
- 02流式执行模型调用
- 03定义可执行 Python 的工具
- 04使用 Agent 管理工具循环与历史
适用场景
- 01在 Python 应用中调用语言模型
- 02构建调用 Python 工具的 Agent
- 03处理模型响应流与对话历史
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ vercel-labs/ ai-python --skill ai安装后在 Claude Code 中输入/ai确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/custom-loops.mdcustom-provider.mddurable.mdserverless.mdstreaming-tools.mdui.md详细介绍
Python AI SDK
包:ai。需要 Python 3.12+。使用 uv add ai 安装。
不带前缀的模型 ID 使用 AI Gateway 和 AI_GATEWAY_API_KEY。直接使用提供商时,
请使用 provider:model、其 API 密钥和一个额外依赖:
uv add "ai[openai]" # OPENAI_API_KEY, ai.get_model("openai:gpt-5")
uv add "ai[anthropic]" # ANTHROPIC_API_KEY, ai.get_model("anthropic:claude-sonnet-4")
基本用法
使用 ai.stream 调用单个模型,不执行 Python 工具:
import ai
model = ai.get_model("anthropic/claude-sonnet-4")
messages = [
ai.system_message("Be concise."),
ai.user_message("Write a haiku about rain."),
]
async with ai.stream(model, messages) as stream:
async for event in stream:
if isinstance(event, ai.events.TextDelta):
print(event.chunk, end="", flush=True)
answer = stream.output
message = stream.message
使用 ai.Agent 创建一个可执行 Python 工具并管理历史记录的循环:
@ai.tool
async def get_weather(city: str) -> str:
"""Get the weather for a city."""
return "Sunny"
agent = ai.Agent(tools=[get_weather])
async with agent.run(model, messages) as run:
async for event in run:
if isinstance(event, ai.events.TextDelta):
print(event.chunk, end="", flush=True)
answer = run.output
history = run.messages
这些示例足以介绍基本的模型调用、消息、工具和 Agent。
高级用法
对于高级任务,请获取 https://ai-python.dev/docs/ 下对应的页面,并在编写代码前阅读列出的本地说明。
| 任务 | 页面 | 本地说明 |
|---|---|---|
| 提供商客户端、选项、发现 | basics/providers.md | — |
| 结构化输出、复杂流 | basics/streaming.md | — |
| 缓冲式大模型调用 | basics/streaming.md | — |
| 图像、视频、语音、嵌入、转录、重排、评估 | basics/model-operations.md | — |
| 事件和序列化 | basics/messages-and-events.md | — |
| 高级工具、流式处理、聚合 | basics/tools.md | streaming-tools.md |
| 高级 Agent 行为 | basics/agents.md | — |
| 确定性模型和 Agent 测试 | basics/testing.md | — |
| 子 Agent 和多 Agent | basics/subagents-and-multi-agent.md | streaming-tools.md |
| 自定义 Agent 循环 | basics/custom-loops.md | custom-loops.md |
| 审批和钩子 | basics/human-in-the-loop.md | — |
| 无服务器恢复 | basics/human-in-the-loop.md | serverless.md |
| 持久化执行 | basics/durable-execution.md | durable.md |
| 遥测和追踪 | basics/telemetry.md | — |
| AI SDK UI 后端 | basics/ai-sdk-ui.md | ui.md |
| 自定义提供商 | basics/providers.md | custom-provider.md |
如需准确的 API 信息,请使用 reference.md 和相关的 reference/*.md 页面。
评论
支持 Markdown