|
你在调用大语言模型的时候是不是和我一样遇到过这样的问题: - 项目中要对接多个AI供应商,代码里充斥着各种适配逻辑
- 不同平台的API调用方式各异,每换一个都要重新学习
- 想要监控AI调用成本,但统计起来特别麻烦
今天给大家介绍一个超赞的开源项目 - LiteLLM,它完美解决了以上所有问题,让调用各家大模型变得像喝水一样自然! 
为什么它这么受欢迎?目前这个项目已经收获了15.3k+ Star,为什么这么多开发者喜欢它呢?核心原因是它真正做到了"Write Once, Run Anywhere"(写一次代码,到处运行)。 
举个例子,假设你的应用原本使用 OpenAI,代码是这样的: fromlitellmimportcompletion#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快速排序"}]
)其他代码完全不用改,输出格式也保持一致,是不是特别优雅? 实用案例分享1. 智能模型路由假设你想在 GPT-4 不可用时自动切换到 Claude: fromlitellmimportRouter#配置模型列表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":"你好"}]
)2. 成本监控想知道每个项目花了多少AI费用?LiteLLM内置了多种监控方案: fromlitellmimportcompletionimportos#设置回调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"}
)3. 流式输出需要实时展示AI回复?支持! response=completion(
model="openai/gpt-4",
messages=[{"role":"user","content":"讲个故事"}],
stream=True)forchunkinresponse:print(chunk.choices[0].delta.contentor"",end="")部署也超简单想搭建自己的AI网关?一行命令搞定: litellm--modelhuggingface/bigcode/starcoder 这样就启动了一个兼容OpenAI API的服务器,可以直接用OpenAI的SDK来调用: importopenai
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绝对值得一试: - 支持20+主流AI平台
- 统一的调用方式
- 完善的监控功能
- 活跃的社区支持
- 企业级的可靠性
项目地址:https://github.com/BerriAI/litellm |