链载Ai

标题: 重磅开源:这个15k Star的项目让调用大模型像喝水一样简单! [打印本页]

作者: 链载Ai    时间: 昨天 12:04
标题: 重磅开源:这个15k Star的项目让调用大模型像喝水一样简单!

你在调用大语言模型的时候是不是和我一样遇到过这样的问题:


今天给大家介绍一个超赞的开源项目 - 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绝对值得一试:


项目地址:https://github.com/BerriAI/litellm






欢迎光临 链载Ai (https://www.lianzai.com/) Powered by Discuz! X3.5