litellm.completion()。LiteLLM 处理将你的请求转换为目标模型提供者所需的特定格式的底层复杂性。
LiteLLM 的主要特性:
litellm.completion,litellm.embedding)。gpt-4o切换到ollama/llama3)。结合 Ollama 和 LiteLLM 提供了几个优势:
ollama/llama3与ollama/mistral),即可轻松尝试 Ollama 提供的不同本地模型。在我们开始之前,请确保已安装并设置好必要的工具。
LiteLLM 是一个 Python 库,因此你需要在系统上安装 Python。LiteLLM 要求 Python 3.8 或更高版本。
python --version
# or
python3 --versionpip,即 Python 包管理器。它通常与 Python 一起捆绑提供。你可以通过pip --version或pip3 --version来检查。安装和设置 Ollama
你需要在计划运行 LiteLLM Python 代码的同一台机器上安装并运行 Ollama(如果在不同的机器上运行,则需要通过网络访问)。
ollama--version
这应该会显示已安装的 Ollama 版本。
拉取 Ollama 模型
Ollama 需要至少下载一个模型才能处理请求。让我们拉取一个流行的模型,比如 Llama 3(8B 指令变体)。
ollamapullllama3
这将下载 Llama 3 模型文件。根据你的互联网连接和模型大小,这可能需要一些时间。你可以用 Ollama 库中其他可用的模型替换llama3(例如,mistral,phi3,gemma:2b)。请查看 Ollama 网站以获取完整列表。
安装 LiteLLM
在准备好 Python 和 Ollama 后,使用 pip 安装 LiteLLM。
pip install litellm
# or if you use pip3
# pip3 install litellmpython# or python3
>>> import litellm
>>> litellm.__version__
# This should print the installed version without errors.
>>>exit()LiteLLM 需要连接到 Ollama API 服务器。你需要确保 Ollama 正在运行。
验证 Ollama 是否正在运行
ollamaserve
此命令将启动服务器,通常会在该终端窗口中持续运行,直到你停止它(Ctrl+C)。你可能希望将其在后台运行或作为系统服务以便长期使用。
curl(如果可用)或网页浏览器访问其默认端点来检查服务器是否响应:curlhttp://localhost:11434
你应该会收到类似Ollama is running的响应。如果你收到“连接被拒绝”的错误,Ollama 可能未运行或配置在不同的端口/地址上。
默认情况下,Ollama 在以下地址公开其 API:
http://localhost:11434LiteLLM 已预配置为知道这个默认地址。
如果你的 Ollama 实例运行在不同的主机或端口上(例如,在具有端口映射的 Docker 容器内,或在远程服务器上)。
需要告诉 LiteLLM 在哪里可以找到它(在配置部分中介绍)。对于大多数标准本地设置,默认配置开箱即用。
现在,让我们编写一个简单的 Python 脚本,通过 LiteLLM 向运行在 Ollama 上的llama3模型发送请求。
创建一个新的 Python 文件(例如,ollama_test.py),并添加以下代码:
importlitellm
importos
# 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)
exceptExceptionase:
print(f"An error occurred:{e}")
让我们来分析一下这个函数:
litellm.completion():这是 LiteLLM 中生成文本补全的核心功能(包括聊天风格的补全)。model:此参数指定要使用的模型/提供者。重要的是,对于 Ollama 模型,你必须在模型名称(Ollama 所知的名称)前加上ollama/前缀。因此,llama3变为ollama/llama3,mistral变为ollama/mistral,等等。这告诉 LiteLLM 将请求路由到与 Ollama 兼容的端点。messages:这遵循标准的 OpenAI 聊天补全格式——一个字典列表,每个字典都有一个role(system、user或assistant)和content。litellm.completion返回的response对象模仿 OpenAI API 响应对象的结构。这种一致性是 LiteLLM 的一个关键优势。你通常通过response.choices[0].message.content访问生成的文本。考虑到这些要点,让我们运行这个函数:
确保 Ollama 正在运行(如第 4 步所验证)并且你已经拉取了llama3模型。然后,从你的终端运行脚本:
pythonollama_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 使这变得简单。
为什么选择流式传输?
修改之前的脚本 (ollama_test.py) 以启用流式传输:
importlitellm
importos
# 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
forchunkinresponse_stream:
# Each chunk mimics the OpenAI streaming chunk structure
# Access the content delta like this:
content_delta = chunk.choices[0].delta.content
ifcontent_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
exceptExceptionase:
print(f"\nAn error occurred:{e}")
更改:
stream=True:将此参数添加到litellm.completion调用中。response_stream)。我们遍历这个迭代器。chunk代表响应的一小部分。我们使用chunk.choices[0].delta.content访问新的文本片段。delta属性包含与前一个块的差异(通常是几个字符或一个单词)。print(..., end="", flush=True):立即打印块内容而不添加换行,刷新输出缓冲区以确保它立即出现在终端中。运行这个更新的脚本:
pythonollama_test.py
你会看到俳句在终端中逐字或逐字符地出现,展示流式行为。
虽然 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:
exportOLLAMA_API_BASE="http://192.168.1.100:11434"
python your_script.pyWindows(命令提示符):
set OLLAMA_API_BASE=http://192.168.1.100:11434
python your_script.pyWindows(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
llama/llama3# The name you use in litellm.completion
litellm_params:
model
llama/llama3# The actual model identifier for the provider
api_base:"http://localhost:11434"# Default, change if needed
-model_name
llama/mistral-remote# Example: Alias for a remote Ollama
litellm_params:
model
llama/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 加载它,通常在应用程序启动时进行:
importlitellm
importos
# 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.")
exceptExceptionase:
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], "...")
exceptExceptionase:
print(f"An error occurred during completion:{e}")
配置文件提供了一种结构化的方式来管理多个模型的设置,包括可能在不同机器上运行的 Ollama 实例。
除了基本的呼叫和流媒体功能,LiteLLM 还提供增强稳健性和可观察性的功能,这些功能与 Ollama 无缝协作。
虽然配置文件允许定义别名,但你也可以通过编程方式注册它们。这对于简化模型名称或将通用名称映射到特定的 Ollama 模型非常有用。
importlitellm
# 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 内置了重试逻辑。
importlitellm
importtime
# 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)
exceptExceptionase:
# 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,成本跟踪的相关性较低,除非你分配虚拟成本)。
importlitellm
importlogging
# 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']ifkwargs.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
exceptExceptionase:
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 等平台集成,以实现更高级的可观察性。
虽然 Ollama 本身通常不需要 API 密钥进行本地访问,但如果你的应用程序还通过 LiteLLM 使用云服务提供商(如 OpenAI、Anthropic 等),你需要管理这些密钥。
LiteLLM 会在标准环境变量中查找密钥(例如,OPENAI_API_KEY、ANTHROPIC_API_KEY),或者可以在config.yaml中设置,或直接传递给completion调用(出于安全原因不太推荐)。
使用config.yaml或环境变量是首选方法。
虽然在你的 Python 代码中直接使用litellm库非常适合简单脚本或单个应用程序。
但 LiteLLM 代理提供了更稳健和可扩展的解决方案,特别是对于微服务或当多个应用程序需要访问 LLM(包括 Ollama)时。
LiteLLM 代理是一个独立的服务器,你需要单独运行。你的应用程序随后向代理的端点发出标准的 OpenAI 兼容 API 请求。
代理根据你的模型详细信息(包括 Ollama 实例、云服务提供商的 API 密钥等)进行配置,处理请求路由到正确的底层 LLM,管理密钥,强制执行速率限制,记录日志,重试等。
安装代理依赖项:
pipinstall'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
llama/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
llama/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 调用。
你可以使用openaiPython 库或简单的requests。
使用openai库:
首先,安装它:pip install openai
importopenai
importos
# 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
)
forchunkinstream_response:
ifchunk.choices[0].delta.contentisnotNone:
print(chunk.choices[0].delta.content, end="", flush=True)
print("\n--- End of Stream ---")
exceptopenai.APIConnectionErrorase:
print(f"Connection Error: Could not connect to LiteLLM Proxy at{client.base_url}. Is it running?")
exceptopenai.APIStatusErrorase:
print(f"API Error: Status={e.status_code}, Response={e.response}")
exceptExceptionase:
print(f"An unexpected error occurred:{e}")
对于简单脚本以外的任何内容,强烈建议在将 Ollama 集成到更大生态系统时使用 LiteLLM 代理。
以下是你可能遇到的一些常见问题及其解决方法:
连接错误(连接被拒绝,超时)
http://localhost:11434吗?如果不是,请使用环境变量(OLLAMA_API_BASE)或配置文件(第 7 步)或代理配置(第 9 步)来配置 LiteLLM。litellm --config ...命令正在运行并且可以在指定的主机/端口上访问。模型未找到错误(litellm.exceptions.NotFounderror,404 模型未找到)
litellm.completion调用或代理配置中,你是否使用了ollama/前缀(例如,ollama/llama3)?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依赖冲突:
openai库。考虑使用 Python 虚拟环境 (venv) 来隔离项目依赖:python -m venv myenv
sourcemyenv/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 pull <model>),并通过 LiteLLM 访问它们(ollama/<model>)。ollama/<model>作为模型名称。通过结合 LiteLLM 和 Ollama你可以获得显著的灵活性和控制权,以便将大型语言模型集成到你的应用程序中,从而实现强大的本地优先 AI 解决方案。
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |