aisuite
一句话简介
一个统一的Python客户端库,以一致接口封装多种大语言模型与生成式AI服务,便于跨厂商切换与集成。
标签
适用应用场景
- 快速接入多家LLM厂商的API进行对比测试
- 在应用中按需切换不同底层大模型而无需重写代码
- 搭建统一的AI代理或聊天服务层以屏蔽模型差异
- 用于研究和生产环境中批量调用与评估多种生成式模型
README 中文摘要
aisuite
aisuite 是一个轻量级 Python 库,用于构建基于大语言模型的应用。它分为两层:跨厂商统一的 Chat Completions API,以及在此之上提供工具与工具包的 Agents API。aisuite 还驱动着 OpenWorker——一个桌面 AI 同事应用,已迁移到独立仓库开发。
架构分层
- Chat Completions API:单一接口对接 OpenAI、Anthropic、Google、Mistral、Hugging Face、AWS、Cohere、Ollama、OpenRouter、Requesty 等多个 LLM 厂商。
- Agents API · 工具包 · MCP:赋予模型真实 Python 函数作为工具,启用多轮工具调用循环,挂载预置工具包(文件、git、shell)或任意 MCP 服务,并通过工具策略进行治理。
- OpenWorker:基于 aisuite 构建的桌面 AI 同事应用,封装于独立仓库,承担日常任务。
安装
pip install aisuite # 仅基础包,不含厂商 SDK
pip install 'aisuite[anthropic]' # 额外安装指定厂商 SDK
pip install 'aisuite[all]' # 安装全部厂商 SDK
调用对应厂商前还需配置相应的 API 密钥。
Chat Completions API
模型名采用 <provider>:<model-name> 格式,aisuite 据此路由到对应厂商并适配参数。核心参数如 temperature、max_tokens、tools 等都以厂商无关方式统一处理。
import aisuite as ai
client = ai.Client()
models = ["openai:gpt-4o", "anthropic:claude-3-5-sonnet-20240620"]
messages = [
{"role": "system", "content": "Respond in Pirate English."},
{"role": "user", "content": "Tell me a joke."},
]
for model in models:
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0.75
)
print(response.choices[0].message.content)
流式输出:传入 stream=True 即可获得 OpenAI 形态的分片迭代器,跨厂商使用同一循环。异步版本为 aclient.chat.completions.acreate(..., stream=True),配合 async for 迭代。工具调用同样支持流式增量输出,开发者可自行组装并执行。
Agents API
将工具调用简化为一行代码:直接传入 Python 函数,aisuite 自动生成 schema,执行调用并将结果回传给模型。
def will_it_rain(location: str, time_of_day: str):
"""Check if it will rain in a location at a given time today."""
return "YES"
client = ai.Client()
response = client.chat.completions.create(
model="openai:gpt-4o",
messages=[{"role": "user", "content": "我在旧金山,下午 2 点能野餐吗?"}],
tools=[will_it_rain],
max_turns=2 # 工具调用最大往返轮次
)
print(response.choices[0].message.content)
max_turns 控制自动循环轮次;省略该项则进入手动模式,开发者自行处理模型返回的工具调用请求。
更结构化的 Agent:
from aisuite import Agent, Runner
agent = Agent(
name="repo-helper",
model="anthropic:claude-sonnet-4-6",
instructions="你是代码仓库助手,使用工具从代码中寻找答案。",
tools=[*ai.toolkits.files(root="."), *ai.toolkits.git(root=".")],
)
result = Runner.run(agent, "最近一次提交改了什么?用三条要点概括。")
print(result.final_output)
Agents API 还提供生产级组件:
- 工具策略:
RequireApprovalPolicy、允许/拒绝列表,以及自定义可调用对象裁定哪些工具调用可执行。 - 状态存储:支持内存、文件或 Postgres 后端,跨进程恢复会话。
- 制品与追踪:记录 Agent 产出的内容以及每一步执行轨迹。
MCP 工具
aisuite 原生支持 Model Context Protocol,可将任意 MCP 服务的工具直接交给模型。先安装扩展:pip install 'aisuite[mcp]'。
response = client.chat.completions.create(
model="openai:gpt-4o",
messages=[{"role": "user", "content": "列出当前目录下的文件"}],
tools=[{
"type": "mcp",
"name": "filesystem",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/directory"]
}],
max_turns=3
)
如需复用连接、安全过滤或工具前缀命名,可使用显式 MCPClient。
扩展厂商
新厂商通过实现轻量级适配器接入:模块文件命名为 <provider>_provider.py,类名 <Provider>Provider,即可被自动发现和加载。
许可证
基于 MIT 协议发布,可自由用于商业和非商业用途。
摘要更新于 2026-07-27 00:32:01
· 原文 9737 字符
· md5 e92c43e0bf66…