微信扫码
添加专属顾问
我要投稿
你在调用大语言模型的时候是不是和我一样遇到过这样的问题:
今天给大家介绍一个超赞的开源项目 - LiteLLM,它完美解决了以上所有问题,让调用各家大模型变得像喝水一样自然!
目前这个项目已经收获了15.3k+ Star,为什么这么多开发者喜欢它呢?核心原因是它真正做到了"Write Once, Run Anywhere"(写一次代码,到处运行)。
举个例子,假设你的应用原本使用 OpenAI,代码是这样的:
from litellm import completion# OpenAI调用response = completion(
model="openai/gpt-4",
messages=[{"role": "user", "content": "写一个python快速排序"}]
)某天你想切换到 Anthropic 的 Claude 或者 Google 的 Gemini,只需要改一下model参数就行:
# 换成Anthropicresponse = completion(
model="anthropic/claude-3-sonnet",
messages=[{"role": "user", "content": "写一个python快速排序"}]
)# 换成Googleresponse = completion(
model="google/gemini-pro",
messages=[{"role": "user", "content": "写一个python快速排序"}]
)其他代码完全不用改,输出格式也保持一致,是不是特别优雅?
假设你想在 GPT-4 不可用时自动切换到 Claude:
from litellm import Router# 配置模型列表model_list = [
{"model_name": "gpt-4","litellm_params": {"model": "openai/gpt-4"},
},
{"model_name": "gpt-4","litellm_params": {"model": "anthropic/claude-3-sonnet"},
}
]# 创建路由器router = Router(model_list=model_list)# 自动选择可用模型response = router.completion(
model="gpt-4",
messages=[{"role": "user", "content": "你好"}]
)想知道每个项目花了多少AI费用?LiteLLM内置了多种监控方案:
from litellm import completionimport os# 设置回调os.environ["HELICONE_API_KEY"] = "your-key"litellm.success_callback = ["helicone"]# 调用时会自动记录用量response = completion(
model="openai/gpt-4",
messages=[{"role": "user", "content": "Hi"}],
metadata={"project": "chatbot", "user": "user_123"}
)需要实时展示AI回复?支持!
response = completion(
model="openai/gpt-4",
messages=[{"role": "user", "content": "讲个故事"}],
stream=True)for chunk in response:print(chunk.choices[0].delta.content or "", end="")想搭建自己的AI网关?一行命令搞定:
litellm --model huggingface/bigcode/starcoder
这样就启动了一个兼容OpenAI API的服务器,可以直接用OpenAI的SDK来调用:
import openai
client = openai.OpenAI(
api_key="anything",
base_url="http://localhost:4000")
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "你好"}]
)如果你正在开发AI应用,LiteLLM绝对值得一试:
项目地址:https://github.com/BerriAI/litellm
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2026-02-24
OpenClaw 全球最火的AI助手,到底是什么神仙?
2026-02-23
OpenClaw背后的英雄Pi-mono
2026-02-22
GLM-5 技术报告全解读|a16z:“最好的开源模型”
2026-02-22
AI创业半年复盘:开源我踩过的坑。
2026-02-22
OpenClaw源码解读系列:自动回复管线
2026-02-22
OpenClaw源码解读系列:插件系统
2026-02-22
如何在Mac mini M4上为OpenClaw接入iMessage
2026-02-20
拆解 OpenViking:把 Agent 上下文从"向量碎片"变成"可操作文件系统"
2026-01-27
2026-02-06
2026-01-29
2026-01-30
2026-01-12
2025-12-22
2026-01-27
2026-01-28
2025-12-10
2025-12-23
2026-02-24
2026-02-11
2026-02-05
2026-01-28
2026-01-26
2026-01-21
2026-01-21
2026-01-20