使用LLMs#
提示
如需查看我们支持的LLM列表及其功能对比,请参阅我们的LLM模块指南。
构建基于LLM的应用时,首要步骤之一是选择使用哪种LLM;它们各有不同的优势和价格点,您可能希望使用多个LLM。
LlamaIndex为大量不同的LLM提供了统一的接口。使用LLM可以像安装适当的集成一样简单:
pip install llama-index-llms-openai
然后通过一行代码调用它:
from llama_index.llms.openai import OpenAI
response = OpenAI().complete("William Shakespeare is ")
print(response)
请注意,这需要在您的环境中设置一个名为OPENAI_API_KEY
的API密钥;更多详情请参阅入门教程。
complete
也可以作为异步方法使用,即 acomplete
。
你也可以通过调用stream_complete
获取流式响应,该函数会返回一个生成器,在生成令牌时实时产出:
handle = OpenAI().stream_complete("William Shakespeare is ")
for token in handle:
print(token.delta, end="", flush=True)
stream_complete
也可作为异步方法使用,即 astream_complete
。
聊天界面#
LLM类还实现了一个chat
方法,允许您进行更复杂的交互:
messages = [
ChatMessage(role="system", content="You are a helpful assistant."),
ChatMessage(role="user", content="Tell me a joke."),
]
chat_response = llm.chat(messages)
stream_chat
和 astream_chat
也可用。
指定模型#
许多LLM集成提供了不止一个模型。您可以通过向LLM构造函数传递model
参数来指定模型:
llm = OpenAI(model="gpt-4o-mini")
response = llm.complete("Who is Laurie Voss?")
print(response)
多模态LLMs#
部分LLM支持多模态聊天消息。这意味着您可以传入文本与其他模态(图像、音频、视频等)的混合内容,LLM将能够处理这些信息。
目前,LlamaIndex支持在ChatMessages中使用内容块来包含文本、图像和音频。
from llama_index.core.llms import ChatMessage, TextBlock, ImageBlock
from llama_index.llms.openai import OpenAI
llm = OpenAI(model="gpt-4o")
messages = [
ChatMessage(
role="user",
blocks=[
ImageBlock(path="image.png"),
TextBlock(text="Describe the image in a few sentences."),
],
)
]
resp = llm.chat(messages)
print(resp.message.content)
工具调用#
部分大型语言模型(如OpenAI、Anthropic、Gemini、Ollama等)支持通过API直接调用工具功能——这意味着无需特定提示词和解析机制即可调用工具和函数。
from llama_index.core.tools import FunctionTool
from llama_index.llms.openai import OpenAI
def generate_song(name: str, artist: str) -> Song:
"""Generates a song with provided name and artist."""
return {"name": name, "artist": artist}
tool = FunctionTool.from_defaults(fn=generate_song)
llm = OpenAI(model="gpt-4o")
response = llm.predict_and_call(
[tool],
"Pick a random song for me",
)
print(str(response))
如需了解更多关于更高级工具调用的详细信息,请参阅使用OpenAI的深度指南。同样的方法适用于任何支持工具/函数的LLM(例如Anthropic、Gemini、Ollama等)。
您可以在工具指南中了解更多关于工具和智能体的信息。
可用的LLMs#
我们支持与OpenAI、Anthropic、Mistral、DeepSeek、Hugging Face等数十家平台的集成。查看我们的大语言模型模块指南获取完整列表,包括如何运行本地模型。
提示
关于隐私和LLM使用的一般说明可以在隐私页面找到。
使用本地LLM#
LlamaIndex不仅支持托管的LLM API;您还可以在本地运行诸如Meta的Llama 3这样的本地模型。例如,如果您已安装并运行Ollama:
from llama_index.llms.ollama import Ollama
llm = Ollama(
model="llama3.3",
request_timeout=60.0,
# Manually set the context window to limit memory usage
context_window=8000,
)
查看自定义LLM指南了解更多关于使用和配置LLM模型的详细信息。