mcpField
A
ai

ai

github.com/vercel-labs开发196169 次安装1 天前更新
代码仓库

关于 ai

`ai` 是面向 Python 3.12+ 的 AI SDK,用于调用模型、构建带 Python 工具执行能力的 Agent,并管理对话历史。它支持通过 AI Gateway 或直接指定提供方访问模型。

主要功能

  1. 01调用 AI Gateway 或直连模型提供方
  2. 02流式执行模型调用
  3. 03定义可执行 Python 的工具
  4. 04使用 Agent 管理工具循环与历史

适用场景

  1. 01在 Python 应用中调用语言模型
  2. 02构建调用 Python 工具的 Agent
  3. 03处理模型响应流与对话历史

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/vercel-labs/ai-python --skill ai

安装后在 Claude Code 中输入/ai确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
custom-loops.md
custom-provider.md
durable.md
serverless.md
streaming-tools.md
ui.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.mdstreaming-tools.md
高级 Agent 行为basics/agents.md—
确定性模型和 Agent 测试basics/testing.md—
子 Agent 和多 Agentbasics/subagents-and-multi-agent.mdstreaming-tools.md
自定义 Agent 循环basics/custom-loops.mdcustom-loops.md
审批和钩子basics/human-in-the-loop.md—
无服务器恢复basics/human-in-the-loop.mdserverless.md
持久化执行basics/durable-execution.mddurable.md
遥测和追踪basics/telemetry.md—
AI SDK UI 后端basics/ai-sdk-ui.mdui.md
自定义提供商basics/providers.mdcustom-provider.md

如需准确的 API 信息,请使用 reference.md 和相关的 reference/*.md 页面。

评论

支持 Markdown