EN

LiteLLM 完整教程 2026:如何用一个 API 调用 100 多个 LLM 提供商

使用 LiteLLM 构建 AI 驱动 API 工作流的分步指南

返回教程列表🌐 Read in English
入门15 分钟

LiteLLM 完整教程 2026:如何用一个 API 调用 100 多个 LLM 提供商

使用 LiteLLM 构建 AI 驱动 API 工作流的分步指南

LiteLLM 完整教程 2026 什么是 LiteLLM? **LiteLLM** 是一个强大的 LLM 代理,让您能够用一个 API 调用 100 多个 LLM 提供商。它已成为 2026 年 AI 开发者工具包中最流行的工具之一。为什么使用 LiteLLM? - 生产力:大幅减少 API 任务耗时 - 集成:无缝连接主流 AI 提供商 - 可靠性:经数千团队生产环境验证 - 社区:丰富的插件和示例生态

LiteLLM 完整教程 2026

什么是 LiteLLM?

LiteLLM 是一个强大的 LLM 代理,让您能够用一个 API 调用 100 多个 LLM 提供商。它已成为 2026 年 AI 开发者工具包中最流行的工具之一。

为什么使用 LiteLLM?

  • 生产力:大幅减少 API 任务耗时
  • 集成:无缝连接主流 AI 提供商
  • 可靠性:经数千团队生产环境验证
  • 社区:丰富的插件和示例生态
  • 快速开始

    安装

    bash
    

    npm/yarn (Node.js 项目)

    npm install litellm

    pip (Python 项目)

    pip install litellm

    或使用托管版本 litellm.com

    配置

    yaml
    

    config.yml

    name: my-litellm-app version: 1.0.0

    integrations: openai: api_key: 1897628437146480647 anthropic: api_key: undefined

    settings: timeout: 30 retry_attempts: 3 log_level: info

    核心概念

    基本工作流

    python
    

    Python 示例

    from litellm import Client, Workflow

    初始化

    client = Client(api_key="your-key")

    创建工作流

    workflow = Workflow() workflow.add_step("input", type="user_message") workflow.add_step("ai_process", model="gpt-4o-mini", type="llm_call") workflow.add_step("output", type="response")

    执行

    result = client.run(workflow, input="您的提示词") print(result.output)

    JavaScript/TypeScript 示例

    typescript
    import { LiteLLMClient } from 'litellm';

    const client = new LiteLLMClient({ apiKey: process.env.LITELLM_API_KEY, });

    main();

    实际用例

    用例 1:用一个 API 调用 100 多个 LLM 提供商

    python
    

    完整示例:用一个 API 调用 100 多个 LLM 提供商

    import os from openai import OpenAI

    openai_client = OpenAI()

    def create_api_pipeline(input_data: dict) -> dict: """ 使用 LiteLLM 实现用一个 API 调用 100 多个 LLM 提供商的管道。 """ # 步骤 1:处理输入 processed = preprocess(input_data) # 步骤 2:AI 分析 response = openai_client.chat.completions.create( model="gpt-4o-mini", messages=[ { "role": "system", "content": f"您是 {t.category} 领域的专家。帮助实现用一个 API 调用 100 多个 LLM 提供商。" }, { "role": "user", "content": str(processed) } ] ) # 步骤 3:后处理 result = { "input": input_data, "analysis": response.choices[0].message.content, "timestamp": datetime.now().isoformat() } return result

    运行

    result = create_api_pipeline({ "topic": "用一个 API 调用 100 多个 LLM 提供商", "context": "构建现代 AI 应用" }) print(result["analysis"])

    用例 2:与其他工具集成

    python
    

    将 LiteLLM 集成到现有技术栈

    import httpx import json

    class LiteLLMIntegration: def __init__(self, api_key: str): self.client = httpx.AsyncClient( base_url="https://api.litellm.com", headers={"Authorization": f"Bearer {api_key}"} ) async def process(self, data: dict) -> dict: response = await self.client.post("/process", json=data) response.raise_for_status() return response.json() async def batch_process(self, items: list) -> list: import asyncio tasks = [self.process(item) for item in items] return await asyncio.gather(*tasks)

    使用

    import asyncio

    async def main(): integration = LiteLLMIntegration( api_key=os.environ["LITELLM_KEY"] ) results = await integration.batch_process([ {"input": "项目 1"}, {"input": "项目 2"}, {"input": "项目 3"}, ]) for r in results: print(r)

    asyncio.run(main())

    高级功能

    监控与日志

    python
    import logging
    from functools import wraps
    import time

    logging.basicConfig(level=logging.INFO) logger = logging.getLogger("litellm")

    def with_logging(func): @wraps(func) async def wrapper(*args, **kwargs): start = time.time() logger.info(f"开始 {func.__name__}") try: result = await func(*args, **kwargs) duration = time.time() - start logger.info(f"完成 {func.__name__},耗时 {duration:.2f} 秒") return result except Exception as e: logger.error(f"{func.__name__} 出错:{e}") raise return wrapper

    @with_logging async def my_workflow(data: dict): # 您的 LiteLLM 工作流 pass

    错误处理

    python
    from tenacity import retry, stop_after_attempt, wait_exponential

    @retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10) ) def reliable_api_call(data: dict) -> dict: """失败时重试,指数退避。""" try: return process(data) except RateLimitError: logger.warning("达到速率限制,正在重试...") raise except APIError as e: if e.status_code >= 500: raise # 服务器错误时重试 raise # 客户端错误时不重试

    定价与套餐

    套餐价格功能

    免费$0有限使用,社区支持 专业版$20-50/月全部功能,优先支持 企业版定制SLA,自定义集成,SSO

    与替代方案对比

    工具LiteLLM替代方案 1替代方案 2

    易用性⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐ 功能⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐ 成本⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐ 社区⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

    结论

    LiteLLM 是一款出色的 LLM 代理,让您能够轻松用一个 API 调用 100 多个 LLM 提供商。其强大的功能与易用性相结合,使其成为 2026 年 AI 开发者的首选工具。

    无论您是构建第一个 AI 应用还是扩展企业系统,LiteLLM 都能提供您成功所需的工具。


    *LiteLLM 最新版本教程 | 2026 年 5 月*

    相关工具

    LiteLLM