支持私有化部署
AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


一键在本地调用上百种大模型,私密、高效、超低成本,详解LiteLLM+Ollama用法

发布日期:2025-06-23 09:51:42 浏览次数: 1542
作者:小匠很忙

微信搜一搜,关注“小匠很忙”

推荐语

本地运行大模型从未如此简单!LiteLLM+Ollama组合让你轻松调用上百种模型,兼顾隐私与效率。

核心内容:
1. LiteLLM的统一接口优势与核心功能
2. Ollama本地运行大模型的便捷特性
3. 组合方案的三大实践价值与配置指南

杨芳贤
53AI创始人/腾讯云(TVP)最具价值专家

 

 

大模型(LLM)已改变了我们的应用开发,但延迟、成本、数据隐私及离线需求等因素,常使本地运行模型成为更优选。

Ollama 是本地运行大模型的主流工具,可以轻松在 macOS、Linux、Windows 上本地运行 Llama 3、Mistral、Phi-3 等强大开源的大模型。

然而,调用大模型API时,需要编写特定代码,LiteLLM 正为此而生。

LiteLLM 提供了标准化、轻量级接口,可一键调用超百种 LLM API(含 Ollama、OpenAI 等)。只需设置好,即可切换不同大模型API,包括本地 Ollama 模型,且改动极小。

本文将详述讲述如何设置 LiteLLM,并演示如何用它来操作本地的 Ollama 模型。

 

为什么选择 LiteLLM 和 Ollama?

在深入技术步骤之前,让我们了解一下我们正在使用的工具以及它们组合的强大之处。

什么是 LiteLLM?

LiteLLM 是一个轻量级的 Python 库,充当与各种 LLM API 交互的统一接口。

你无需学习和实现 OpenAI、Anthropic、Cohere、Google Gemini、Azure OpenAI、Replicate、Hugging Face 和本地模型如 Ollama 的不同 SDK 或 API 请求格式,而是使用一个单一且一致的函数调用:litellm.completion()

LiteLLM 处理将你的请求转换为目标模型提供者所需的特定格式的底层复杂性。

LiteLLM 的主要特性:

  • • 统一接口: 在 100 多个 LLM 提供商中,API 调用一致(litellm.completionlitellm.embedding)。
  • • 轻松切换各种模型: 通过更改单个模型字符串,轻松在模型之间切换(例如,从 gpt-4o 切换到 ollama/llama3)。
  • • 鲁棒性: 内置支持超时、重试和回退。
  • • 可观察性: 集成日志记录、回调,并支持 Langfuse、Helicone 和 PromptLayer 等平台。
  • • 代理服务器: 提供独立的代理服务器,用于集中管理 API 密钥、负载均衡、路由以及在不同应用程序或服务之间的一致访问。
  • • 成本跟踪: 帮助监控各种 LLM API 的支出。

为什么要将 LiteLLM 与 Ollama 结合使用?

结合 Ollama 和 LiteLLM 提供了几个优势:

  1. 1. 无缝切换各种模型:使用 LiteLLM 的标准接口编写应用逻辑,使你能够无缝切换本地 Ollama 模型(用于开发、隐私、离线使用)和强大的云模型(用于生产、特定功能),而无需重写核心代码。
  2. 2. 简化本地集成:LiteLLM 使得在你的 Python 应用程序中与 Ollama 的 API 交互变得简单,处理请求格式和响应解析。
  3. 3. 灵活性:只需在 LiteLLM 调用中更改模型名称(例如,ollama/llama3 与 ollama/mistral),即可轻松尝试 Ollama 提供的不同本地模型。
  4. 4. 利用 LiteLLM 功能: 即使在使用本地 Ollama 模型时,也能享受 LiteLLM 的功能,如重试、回退、日志记录和成本跟踪。
  5. 5. 混合方法: 构建能够根据成本、延迟或任务要求等因素智能路由请求到本地 Ollama 模型或远程 API 的应用程序,所有这些都通过 LiteLLM(特别是通过其代理)进行管理。

准备使用 LiteLLM 和 Ollama

在我们开始之前,请确保已安装并设置好必要的工具。

LiteLLM 是一个 Python 库,因此你需要在系统上安装 Python。LiteLLM 要求 Python 3.8 或更高版本。

  • • 验证安装: 打开终端或命令提示符并运行:
python --version
# or
python3 --version
  • • 安装: 如果你没有安装 Python 或需要更新版本,请从官方 Python 网站(python.org)下载,或使用包管理器,如 Homebrew(macOS)、apt(Debian/Ubuntu)或 Chocolatey(Windows)。
  • • Pip: 确保你已安装 pip,即 Python 包管理器。它通常与 Python 一起捆绑提供。你可以通过 pip --version 或 pip3 --version 来检查。

安装和设置 Ollama

你需要在计划运行 LiteLLM Python 代码的同一台机器上安装并运行 Ollama(如果在不同的机器上运行,则需要通过网络访问)。

  • • 下载并安装: 访问 Ollama 网站(ollama.com)并下载适合你操作系统的安装程序(macOS、Linux、Windows)。按照安装说明进行操作。
  • • 验证安装: 安装完成后,打开一个  终端窗口并运行:
ollama --version

这应该会显示已安装的 Ollama 版本。

拉取 Ollama 模型

Ollama 需要至少下载一个模型才能处理请求。让我们拉取一个流行的模型,比如 Llama 3(8B 指令变体)。

  • • 拉取命令: 在你的终端中运行:
ollama pull llama3

这将下载 Llama 3 模型文件。根据你的互联网连接和模型大小,这可能需要一些时间。你可以用 Ollama 库中其他可用的模型替换 llama3(例如,mistralphi3gemma:2b)。请查看 Ollama 网站以获取完整列表。

安装 LiteLLM

在准备好 Python 和 Ollama 后,使用 pip 安装 LiteLLM。

  • • 安装命令: 打开终端或命令提示符并运行:
pip install litellm
# or if you use pip3
# pip3 install litellm
  • • 验证(可选): 你可以通过在 Python 解释器中导入 LiteLLM 来验证安装:
python # or python3
>>> import litellm
>>> litellm.__version__
# This should print the installed version without errors.
>>> exit()

在本地运行 Ollama

LiteLLM 需要连接到 Ollama API 服务器。你需要确保 Ollama 正在运行。

验证 Ollama 是否正在运行

  • • macOS/Windows 桌面应用程序: 如果你安装了桌面应用程序,Ollama 通常会在安装后自动在后台运行。你应该在菜单栏(macOS)或系统托盘(Windows)中看到 Ollama 图标。
  • • Linux / 手动启动: 在 Linux 上,或者如果你更喜欢手动控制,你可能需要显式启动 Ollama 服务器。打开终端并运行:
ollama serve

此命令将启动服务器,通常会在该终端窗口中持续运行,直到你停止它(Ctrl+C)。你可能希望将其在后台运行或作为系统服务以便长期使用。

  • • 检查状态: 你可以通过尝试使用 curl(如果可用)或网页浏览器访问其默认端点来检查服务器是否响应:
curl http://localhost:11434

你应该会收到类似 Ollama is running 的响应。如果你收到“连接被拒绝”的错误,Ollama 可能未运行或配置在不同的端口/地址上。

默认情况下,Ollama 在以下地址公开其 API:

  • • URL: http://localhost:11434

LiteLLM 已预配置为知道这个默认地址。

如果你的 Ollama 实例运行在不同的主机或端口上(例如,在具有端口映射的 Docker 容器内,或在远程服务器上)。

需要告诉 LiteLLM 在哪里可以找到它(在配置部分中介绍)。对于大多数标准本地设置,默认配置开箱即用。

首次使用 LiteLLM 调用 Ollama

现在,让我们编写一个简单的 Python 脚本,通过 LiteLLM 向运行在 Ollama 上的 llama3 模型发送请求。

基本 Python 脚本

创建一个新的 Python 文件(例如,ollama_test.py),并添加以下代码:

import litellm
import os

# Optional: Set verbose logging for LiteLLM to see what's happening
# litellm.set_verbose = True

# Define the model name - important: prefix with "ollama/"
# Ensure 'llama3' is the model you pulled with `ollama pull llama3`
model_name = "ollama/llama3"

# Define the messages for the chat completion
messages = [
    {"role""system""content""You are a helpful assistant."},
    {"role""user""content""Why is the sky blue?"}
]

try:
    print(f"--- Sending request to {model_name} ---")
    # Call the litellm.completion function
    response = litellm.completion(
        model=model_name,
        messages=messages
    )

    # Print the response
    print("--- Response ---")
    # The response object mirrors the OpenAI structure
    # Access the message content like this:
    message_content = response.choices[0].message.content
    print(message_content)

    # You can also print the entire response object for inspection
    # print("\n--- Full Response Object ---")
    # print(response)

except Exception as e:
    print(f"An error occurred: {e}")

让我们来分析一下这个函数:

  • • litellm.completion():这是 LiteLLM 中生成文本补全的核心功能(包括聊天风格的补全)。
  • • model:此参数指定要使用的模型/提供者。重要的是,对于 Ollama 模型,你必须在模型名称(Ollama 所知的名称)前加上 ollama/ 前缀。因此,llama3 变为 ollama/llama3mistral 变为 ollama/mistral,等等。这告诉 LiteLLM 将请求路由到与 Ollama 兼容的端点。
  • • messages:这遵循标准的 OpenAI 聊天补全格式——一个字典列表,每个字典都有一个 rolesystemuser 或 assistant)和 content
  • • 返回值: 由 litellm.completion 返回的 response 对象模仿 OpenAI API 响应对象的结构。这种一致性是 LiteLLM 的一个关键优势。你通常通过 response.choices[0].message.content 访问生成的文本。

考虑到这些要点,让我们运行这个函数:

确保 Ollama 正在运行(如第 4 步所验证)并且你已经拉取了 llama3 模型。然后,从你的终端运行脚本:

python ollama_test.py

你应该会看到类似于以下的输出(确切的文本会根据模型的响应而有所不同):

--- Sending request to ollama/llama3 ---
--- Response ---
The sky appears blue because of a phenomenon called Rayleigh scattering. Sunlight reaching Earth's atmosphere is composed of different colors of light, which have different wavelengths. Blue and violet light have shorter wavelengths, while red and orange light have longer wavelengths.

As sunlight travels through the atmosphere, it collides with tiny gas molecules (mostly nitrogen and oxygen). These molecules scatter the sunlight in all directions. Shorter wavelengths (blue and violet) are scattered more effectively than longer wavelengths (red and orange).

Our eyes are more sensitive to blue than violet, and some violet light is absorbed higher in the atmosphere, so we perceive the sky as primarily blue during the daytime when the sun is high.

Near sunrise and sunset, sunlight passes through more of the atmosphere to reach our eyes. Most of the blue light is scattered away, allowing more of the longer wavelength red and orange light to reach us, which is why sunrises and sunsets often appear reddish or orange.

恭喜!你已成功使用 LiteLLM 与本地 Ollama 模型进行通信。

生成流式响应

对于交互式应用程序(如聊天机器人)或生成长响应时,等待整个完成可能会导致用户体验不佳。

流式传输允许你在生成时逐个接收响应令牌。LiteLLM 使这变得简单。

为什么选择流式传输?

  • • 提升感知性能: 用户立即看到输出,使应用程序感觉更具响应性。
  • • 处理长响应: 在不等待整个响应的情况下处理部分响应,适用于非常长的文本生成。
  • • 实时交互: 支持构建实时对话界面。

使用 LiteLLM 实现流式传输

修改之前的脚本 (ollama_test.py) 以启用流式传输:

import litellm
import os

# litellm.set_verbose = True # Optional for debugging

model_name = "ollama/llama3"
messages = [
    {"role""system""content""You are a concise poet."},
    {"role""user""content""Write a short haiku about a cat."}
]

try:
    print(f"--- Sending streaming request to {model_name} ---")
    # Set stream=True
    response_stream = litellm.completion(
        model=model_name,
        messages=messages,
        stream=True# Enable streaming
    )

    print("--- Streaming Response ---")
    full_response = ""
    # Iterate through the stream chunks
    for chunk in response_stream:
        # Each chunk mimics the OpenAI streaming chunk structure
        # Access the content delta like this:
        content_delta = chunk.choices[0].delta.content

        if content_delta:  # Check if there's new content in this chunk
            print(content_delta, end="", flush=True# Print immediately without newline
            full_response += content_delta

    print("\n--- End of Stream ---")
    # print(f"\nFull reconstructed response:\n{full_response}") # Optional: show full response at the end

except Exception as e:
    print(f"\nAn error occurred: {e}")

更改:

  1. 1. stream=True:将此参数添加到 litellm.completion 调用中。
  2. 2. 迭代: 该函数现在返回一个迭代器(response_stream)。我们遍历这个迭代器。
  3. 3. 块处理: 循环中的每个 chunk 代表响应的一小部分。我们使用 chunk.choices[0].delta.content 访问新的文本片段。delta 属性包含与前一个块的差异 (通常是几个字符或一个单词)。
  4. 4. print(..., end="", flush=True) :立即打印块内容而不添加换行,刷新输出缓冲区以确保它立即出现在终端中。

运行这个更新的脚本:

python ollama_test.py

你会看到俳句在终端中逐字或逐字符地出现,展示流式行为。

配置 LiteLLM + Ollama 设置

虽然 LiteLLM 可以开箱即用地与默认的 Ollama 设置一起工作,但如果你的设置偏离标准 http://localhost:11434,你可能需要进行配置。

默认行为(本地主机)

如前所述,当你使用 ollama/ 前缀时,LiteLLM 会自动假设 Ollama 正在 http://localhost:11434 上运行。如果这是你的设置,则无需额外配置。

使用环境变量(可选)

如果 Ollama 在不同的主机或端口上运行,你可以通过使用环境变量告诉 LiteLLM 在哪里找到它。

LiteLLM 会检查特定的环境变量以配置 API 端点。对于特定的 Ollama 模型(或者如果你想要一般覆盖,可以针对所有 Ollama 模型),你可以设置其基础 URL。

例如,如果你的 Ollama 实例运行在 http://192.168.1.100:11434,你可以在运行 Python 脚本 之前 设置一个环境变量:

Linux/macOS:

export OLLAMA_API_BASE="http://192.168.1.100:11434"
python your_script.py

Windows(命令提示符):

set OLLAMA_API_BASE=http://192.168.1.100:11434
python your_script.py

Windows(PowerShell):

$env:OLLAMA_API_BASE = "http://192.168.1.100:11434"
python your_script.py

现在,当你的脚本调用 litellm.completion(model="ollama/llama3", ...) 时,LiteLLM 将查找 OLLAMA_API_BASE 环境变量,并使用该 URL 代替默认的 localhost

注意: 设置 OLLAMA_API_BASE 会覆盖以 ollama/ 开头的 所有 模型的基础 URL。如果需要更细粒度的环境变量控制,请查阅 LiteLLM 文档(例如,为特定模型别名设置基础 URL)。

使用配置文件(可选)

对于涉及多个模型、自定义设置或避免使用环境变量的更复杂配置,LiteLLM 支持配置文件(config.yaml 或指定路径)。

在与你的脚本相同的目录中创建一个 config.yaml 文件(或在其他位置,并指向 LiteLLM):

# config.yaml
model_list:
-model_name:ollama/llama3# The name you use in litellm.completion
    litellm_params:
      model:ollama/llama3# The actual model identifier for the provider
      api_base:"http://localhost:11434"# Default, change if needed

-model_name:ollama/mistral-remote# Example: Alias for a remote Ollama
    litellm_params:
      model:ollama/mistral# Ollama expects 'mistral'
      api_base:"http://192.168.1.100:11434"

-model_name:gpt-4o-mini# Example: Including a non-Ollama model
    litellm_params:
      model:gpt-4o-mini
      api_key:"os.environ/OPENAI_API_KEY"# Securely read from env var

general_settings:
# Optional: Set global settings like timeouts
# timeout: 300 # 5 minutes

# You can define custom environment variables within the config too
environment_variables:
OPENAI_API_KEY:"" # Define placeholders or actual keys (less secure)

要使用此配置文件,你需要告诉 LiteLLM 加载它,通常在应用程序启动时进行:

import litellm
import os

# Load configuration from config.yaml in the current directory
# You can also provide an absolute path: litellm.load_config("path/to/your/config.yaml")
try:
    litellm.load_config()
    print("LiteLLM configuration loaded successfully.")
except Exception as e:
    print(f"Warning: Could not load LiteLLM config. Using defaults. Error: {e}")


# Now you can use the model names defined in the config
try:
    # Using the standard ollama/llama3 which might pick up the api_base from the config
    response_local = litellm.completion(model="ollama/llama3", messages=[{"role""user""content""Test local"}])
    print("Local Llama3 Response:", response_local.choices[0].message.content[:50], "..."# Print snippet

    # Using the alias defined for the remote mistral model
    # response_remote = litellm.completion(model="ollama/mistral-remote", messages=[{"role": "user", "content": "Test remote"}])
    # print("Remote Mistral Response:", response_remote.choices[0].message.content[:50], "...")

except Exception as e:
    print(f"An error occurred during completion: {e}")

配置文件提供了一种结构化的方式来管理多个模型的设置,包括可能在不同机器上运行的 Ollama 实例。

除了基本的呼叫和流媒体功能,LiteLLM 还提供增强稳健性和可观察性的功能,这些功能与 Ollama 无缝协作。

模型别名

虽然配置文件允许定义别名,但你也可以通过编程方式注册它们。这对于简化模型名称或将通用名称映射到特定的 Ollama 模型非常有用。

import litellm

# Define an alias: map "my-local-llm" to "ollama/llama3"
litellm.register_model({
    "my-local-llm": {
        "model""ollama/llama3",
        # You could also specify api_base here if needed for this alias specifically
        # "api_base": "http://localhost:11434"
    }
})

# Now use the alias in your completion call
messages = [{"role""user""content""Tell me about model aliasing."}]
response = litellm.completion(model="my-local-llm", messages=messages)

print(response.choices[0].message.content)

错误处理和重试

网络故障或临时的 Ollama 问题可能会发生。LiteLLM 内置了重试逻辑。

import litellm
import time

# Example: Make Ollama temporarily unavailable (e.g., stop `ollama serve`)
print("Stopping Ollama for 10 seconds (if possible)... You might need to do this manually.")
# os.system("ollama stop") # This command might not exist; manual stop is safer
# time.sleep(10)
# print("Restarting Ollama... You might need to do this manually.")
# os.system("ollama serve &") # Start in background
# time.sleep(5) # Give it time to start

messages = [{"role""user""content""Does retry work?"}]

try:
    # LiteLLM will automatically retry on specific connection errors
    # You can configure the number of retries, backoff factor, etc.
    response = litellm.completion(
        model="ollama/llama3",
        messages=messages,
        num_retries=3,       # Attempt up to 3 retries
        timeout=10           # Set a timeout for each request attempt (seconds)
    )
    print("Success after retries (or on first try):")
    print(response.choices[0].message.content)

except Exception as e:
    # This will catch errors that persist after retries (e.g., model not found, config error)
    # Or if all retries fail for connection errors.
    print(f"An error occurred after retries: {e}")

LiteLLM 智能地重试常见的瞬态网络错误。你可以全局或按调用自定义重试行为。

日志记录和回调

LiteLLM 提供了钩子来记录请求/响应数据或在成功调用或发生错误时触发自定义函数(回调)。

这对于监控、调试和成本跟踪非常重要(尽管对于本地 Ollama,成本跟踪的相关性较低,除非你分配虚拟成本)。

import litellm
import logging

# Configure basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
logger = logging.getLogger(__name__)

# Define a simple success callback function
deflog_success(kwargs, completion_response, start_time, end_time):
    """Logs details about a successful LLM call."""
    model = kwargs.get("model""unknown_model")
    input_text = kwargs.get("messages", [])[-1]['content'if kwargs.get("messages"else"N/A"
    output_text = completion_response.choices[0].message.content[:50] + "..."# Snippet
    duration = (end_time - start_time).total_seconds()
    logger.info(f"Success! Model: {model}, Duration: {duration:.2f}s, Input: '{input_text[:30]}...', Output: '{output_text}'")

# Define a simple failure callback function
deflog_failure(kwargs, exception, start_time, end_time):
    """Logs details about a failed LLM call."""
    model = kwargs.get("model""unknown_model")
    duration = (end_time - start_time).total_seconds()
    logger.error(f"Failure! Model: {model}, Duration: {duration:.2f}s, Error: {exception}")


# Register the callbacks with LiteLLM
litellm.success_callback = [log_success]
litellm.failure_callback = [log_failure]

# Now make a call - callbacks will trigger automatically
messages = [{"role""user""content""How do callbacks work in LiteLLM?"}]
try:
    response = litellm.completion(model="ollama/llama3", messages=messages)
    # print(response.choices[0].message.content) # You can still use the response
except Exception as e:
    pass# Failure callback already handled the logging

# Example of a call that might fail (e.g., model not pulled)
# try:
#     response_fail = litellm.completion(model="ollama/nonexistent-model", messages=messages)
# except Exception as e:
#     pass # Failure callback will log

运行此脚本后,你将看到由回调函数记录的 INFO 或 ERROR 消息,从而提供对 LLM 交互的可见性。LiteLLM 还与 Langfuse、Helicone、PromptLayer 等平台集成,以实现更高级的可观察性。

管理 API 密钥

虽然 Ollama 本身通常不需要 API 密钥进行本地访问,但如果你的应用程序还通过 LiteLLM 使用云服务提供商(如 OpenAI、Anthropic 等),你需要管理这些密钥。

LiteLLM 会在标准环境变量中查找密钥(例如,OPENAI_API_KEYANTHROPIC_API_KEY),或者可以在 config.yaml 中设置,或直接传递给 completion 调用(出于安全原因不太推荐)。

使用 config.yaml 或环境变量是首选方法。

如何使用 LiteLLM 代理服务器(推荐用于稳健性)

虽然在你的 Python 代码中直接使用 litellm 库非常适合简单脚本或单个应用程序。

但 LiteLLM 代理提供了更稳健和可扩展的解决方案,特别是对于微服务或当多个应用程序需要访问 LLM(包括 Ollama)时。

什么是 LiteLLM 代理?

LiteLLM 代理是一个独立的服务器,你需要单独运行。你的应用程序随后向代理的端点发出标准的 OpenAI 兼容 API 请求。

代理根据你的模型详细信息(包括 Ollama 实例、云服务提供商的 API 密钥等)进行配置,处理请求路由到正确的底层 LLM,管理密钥,强制执行速率限制,记录日志,重试等。

使用 Ollama 设置代理

安装代理依赖项:

pip install 'litellm[proxy]'

创建代理配置文件(proxy_config.yaml):
此文件告知代理你可用的模型。

# proxy_config.yaml
model_list:
-model_name:local-llama3# How users will call this model via the proxy
    litellm_params:
      model:ollama/llama3# Tells proxy this uses ollama driver for 'llama3'
      api_base:"http://localhost:11434"# Ensure this points to your Ollama

-model_name:local-mistral
    litellm_params:
      model:ollama/mistral
      api_base:"http://localhost:11434"# Assuming same Ollama instance

# Example: Adding an OpenAI model alongside Ollama
-model_name:cloud-gpt4o
    litellm_params:
      model:gpt-4o-mini
      api_key:"os.environ/OPENAI_API_KEY"# Proxy reads env var

litellm_settings:
# Optional: Set proxy-level settings
# drop_params: True # Removes unsupported params before sending to model
# set_verbose: True # Enable detailed proxy logging
pass
# environment_variables: # Define env vars for the proxy if needed
#   OPENAI_API_KEY: "your_openai_key_here" # Less secure - prefer real env vars

运行代理服务器:
打开终端,确保你的 OPENAI_API_KEY 环境变量已设置(如果使用 OpenAI 模型),然后运行:

litellm --config /path/to/proxy_config.yaml --port 8000
# Replace /path/to/proxy_config.yaml with the actual path
# --port 8000 specifies the port the proxy listens on (default is 4000)

代理服务器将启动并记录信息,表明它已准备好接收请求。

通过代理进行调用

现在,你的应用程序代码(甚至可以使用不同的语言)不再直接使用 litellm.completion,而是向代理的端点(在本例中为 http://localhost:8000)发出标准的 OpenAI API 调用。

你可以使用 openai Python 库或简单的 requests

使用 openai 库:

首先,安装它:pip install openai

import openai
import os

# Point the OpenAI client to the LiteLLM Proxy endpoint
client = openai.OpenAI(
    base_url="http://localhost:8000"# URL of YOUR LiteLLM Proxy
    api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"# Required by OpenAI client, but LiteLLM Proxy ignores it by default
)

# Define messages
messages = [
    {"role""system""content""You are a proxy-powered assistant."},
    {"role""user""content""Explain the benefit of using a proxy for LLM calls."}
]

try:
    print("--- Sending request via LiteLLM Proxy ---")
    # Use the model name defined in proxy_config.yaml ('local-llama3')
    response = client.chat.completions.create(
        model="local-llama3"# Use the alias from proxy_config.yaml
        messages=messages,
        stream=False# Set to True for streaming via proxy
    )

    print("--- Response from Proxy ---")
    print(response.choices[0].message.content)

    # Example Streaming via Proxy
    print("\n--- Streaming via Proxy ---")
    stream_response = client.chat.completions.create(
        model="local-llama3",
        messages=messages,
        stream=True
    )
    for chunk in stream_response:
         if chunk.choices[0].delta.content isnotNone:
              print(chunk.choices[0].delta.content, end="", flush=True)
    print("\n--- End of Stream ---")


except openai.APIConnectionError as e:
    print(f"Connection Error: Could not connect to LiteLLM Proxy at {client.base_url}. Is it running?")
except openai.APIStatusError as e:
    print(f"API Error: Status={e.status_code}, Response={e.response}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

代理方法的好处

  • • 集中管理: 在一个地方管理所有模型配置(Ollama、OpenAI 等)和 API 密钥。
  • • 标准 OpenAI 接口: 所有应用程序使用熟悉的 OpenAI SDK/API 格式进行交互,无论后端模型如何。
  • • 语言无关: 任何可以发出 HTTP 请求的应用程序都可以使用该代理。
  • • 负载均衡/路由: 配置路由规则、回退和多个模型部署(包括多个 Ollama 实例)之间的负载均衡。
  • • 一致的日志记录/监控: 对所有 LLM 调用进行集中日志记录和可观察性。
  • • 安全性: 云服务提供商的 API 密钥安全地存储在代理服务器上,而不是分发到客户端应用程序中。

对于简单脚本以外的任何内容,强烈建议在将 Ollama 集成到更大生态系统时使用 LiteLLM 代理。

常见问题

以下是你可能遇到的一些常见问题及其解决方法:

连接错误( 连接被拒绝 , 超时 )

  • • Ollama 正在运行吗? 验证 Ollama 服务器是否处于活动状态(第 4 步)。检查 Ollama 日志以查找错误。
  • • API 正确么? 你确定 Ollama 位于 http://localhost:11434 吗?如果不是,请使用环境变量(OLLAMA_API_BASE)或配置文件(第 7 步)或代理配置(第 9 步)来配置 LiteLLM。
  • • 防火墙问题? 如果 Ollama 在不同的机器上运行或在 Docker 内部运行,请确保防火墙规则允许从运行 LiteLLM 代码/代理的地方连接到 Ollama 端口(默认 11434)。
  • • LiteLLM 代理是否正在运行? 如果使用代理,请确保 litellm --config ... 命令正在运行并且可以在指定的主机/端口上访问。

模型未找到错误( litellm.exceptions.NotFounderror ,404 模型未找到 )

  • • 模型名称正确吗? 在你的 litellm.completion 调用或代理配置中,你是否使用了 ollama/ 前缀(例如,ollama/llama3)?
  • • 在 Ollama 中拉取模型? 你是否实际运行了 ollama pull <model_name>(例如,ollama pull llama3)?请使用 ollama list 验证。
  • • 拼写错误? 请仔细检查模型名称的拼写是否与 ollama list 的输出一致。
  • • 代理别名: 如果使用代理,请确保你客户端调用中的模型名称(例如,local-llama3)与 proxy_config.yaml 中定义的 model_name 完全匹配。

超时问题 (litellm.exceptions.Timeout)

  • • 模型过载/硬件缓慢: 你的机器可能处理请求的时间过长。尝试使用更小的模型(例如,ollama pull phi3)或在 LiteLLM 中增加超时时间:
# Direct call
response = litellm.completion(model="ollama/llama3", messages=messages, timeout=300# 300 seconds

# Or set globally in config.yaml or proxy_config.yaml
# general_settings:
#   timeout: 300
  • • 复杂提示: 非常长或复杂的提示可能需要更长时间。

依赖冲突:

  • • 确保你使用兼容版本的 Python、LiteLLM,以及在使用代理时可能需要的 openai 库。考虑使用 Python 虚拟环境 (venv) 来隔离项目依赖:
python -m venv myenv
source myenv/bin/activate # Linux/macOS
# myenv\Scripts\activate # Windows
pip install litellm 'litellm[proxy]' openai # Install within the venv

详细日志记录:为了更深入的调试,请在 LiteLLM 中启用详细日志记录:

# For direct library use
litellm.set_verbose = True

# For proxy (in proxy_config.yaml)
# litellm_settings:
#   set_verbose: True

这将打印关于所发请求、头部、响应和潜在错误的详细信息。

结论和下一步

你现在已经学会了如何有效地弥合使用 Ollama 运行本地模型的便利性与 LiteLLM 的标准化、功能丰富的界面之间的差距。

通过Ollama 模型名称前加上 ollama/,你可以利用 LiteLLM 的 completion 功能、流式传输能力、配置选项、错误处理和可观察性特性与你的本地 LLM 结合使用。

使用 LiteLLM 代理提供了一种更强大的解决方案,可以通过统一的、兼容 OpenAI 的 API 端点来管理 Ollama 实例以及可能的许多其他云或本地 LLM 提供商。

接下来该去哪里?

  • • 探索更多 Ollama 模型: 尝试 Ollama 库中的不同模型(ollama pull <model>),并通过 LiteLLM 访问它们(ollama/<model>)。
  • • 深入了解 LiteLLM 代理: 探索高级代理功能,如路由策略、预算管理和 UI 仪表板(LiteLLM UI)。
  • • 与框架集成: 将 LiteLLM 与 LangChain 或 LlamaIndex 等框架一起使用,在配置 LLM 组件时指定 ollama/<model> 作为模型名称。
  • • 实验回调: 将 LiteLLM 的回调与监控工具(Langfuse、Helicone 等)集成,以更好地跟踪你的本地模型使用情况。
  • • 贡献: LiteLLM (github.com/BerriAI/litellm) 和 Ollama (github.com/ollama/ollama) 都是开源项目。

通过结合 LiteLLM 和 Ollama你可以获得显著的灵活性和控制权,以便将大型语言模型集成到你的应用程序中,从而实现强大的本地优先 AI 解决方案。


 


53AI,企业落地大模型首选服务商

产品:场景落地咨询+大模型应用平台+行业解决方案

承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

添加专属顾问

回到顶部

加载中...

扫码咨询