跳转到内容
全部开发指南

aisuite 多模型切换教程:一个字符串换供应商,附 Agents API 与工具调用

AIGoCode发布于 更新于

aisuite 多模型切换教程:一个字符串换供应商,附 Agents API 与工具调用 封面

给应用接多模型时,同一句话想分别丢给 GPT、Claude、Gemini 比一比,听起来像十分钟的活。实际往往卡在三家 SDK:参数名不同、返回结构不同、报错格式也不同,加一家就要再翻一遍文档。

aisuite 是吴恩达(Andrew Ng)团队开源的 Python 库,核心只干一件事:给主流大模型套一层统一的 Chat Completions 接口,换供应商像改一个字符串。GitHub 仓库 andrewyng/aisuite 目前 Star 已超过 1.6 万,协议 MIT。上层还有 Agents API,方便把普通 Python 函数当成工具挂给模型。

aisuite 原文配图 1

它解决什么问题

每家供应商都有自己的 SDK。做 A/B 测试、模型选型,或给用户提供多模型选择时,业务代码里很容易堆出「如果是 OpenAI 就这样调,如果是 Anthropic 就那样调」的分支。

aisuite 对齐大家最熟的 OpenAI Chat Completions 写法,把各家差异藏在底下。你按一种方式写,它负责翻译成对应供应商的请求。OpenAI、Anthropic、Google、Mistral、AWS、Cohere、Ollama、OpenRouter 等都可以用同一套调用面。

aisuite 原文配图 2

换模型:改 供应商:模型名

模型名格式是 provider:model。下面这段示例沿用官方 README 的写法,具体模型 ID 以各家当前文档为准:

import aisuite as ai
client = ai.Client()

models = ["openai:gpt-4.1", "anthropic:claude-sonnet-4"]

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)

同一套 messages 和一个循环,就能跑多家模型;再加一家,往列表里塞新字符串即可。流式输出加 stream=True,chunk 结构仍按 OpenAI 习惯来读。

安装按需装依赖:

pip install aisuite
pip install 'aisuite[anthropic]'
pip install 'aisuite[all]'

PyPI 上近期可见版本为 0.2.0(以 PyPI 页面为准)。各家还要配好对应的 API Key 环境变量。

aisuite 原文配图 3

Agents API:把函数直接当工具

如果只做统一接口,aisuite 已经够用。它还往上长了一层 Agents API:不必手写大段 JSON schema,可以把普通 Python 函数丢进去,由库根据文档字符串生成 schema、执行调用,再把结果喂回模型。

def will_it_rain(location: str, time_of_day: str):
    """Check if it will rain in a location at a given time today.

    Args:
        location (str): Name of the city
        time_of_day (str): Time of the day in HH:MM format.
    """
    return "YES"

client = ai.Client()
response = client.chat.completions.create(
    model="openai:gpt-4.1",
    messages=[{
        "role": "user",
        "content": "I live in San Francisco. Can you check for weather "
                   "and plan an outdoor picnic for me at 2pm?"
    }],
    tools=[will_it_rain],
    max_turns=2,
)
print(response.choices[0].message.content)

tools=[will_it_rain] 加上 max_turns,库会自动跑「模型要调工具 → 执行 → 回填 → 继续」的循环。仓库还提供文件、git、shell 等现成 toolkit(带沙箱),以及更声明式的 Agent / Runner 组织方式,细节见官方 README。

aisuite 原文配图 4

什么时候用它,什么时候不够

适合:应用代码里要快速切换供应商做对比;希望业务层只维护一套 Chat Completions 调用;想少写 tool schema 的原型阶段。

不够用或要另想办法的情况:你已经深度绑定某一家特有能力(例如只在某协议上才有的接口形态);需要统一的额度、计费和 Key 管理网关——那是服务侧的事,不是 SDK 一层能替代的。若你在 AIGoCode 上已经按分组管理多模型,可以到 /models 先看清站内有哪些模型与协议,再决定 aisuite 里写哪些 provider:model 字符串。选型与计价还可以对照 模型目录与定价选择。

小结

aisuite 没有重新发明聊天协议,而是把最熟的 OpenAI 写法铺到多家供应商上,并把工具调用的脏活藏起来。模型迭代很快,让业务代码少被某一家 SDK 绑死,本身就是一种可维护性。

在 AIGoCode 上可以统一拿 Key、选分组,再用 aisuite 这类库在应用里做多模型对比或切换。

参考链接