使用大型语言模型
构建基于LLM的应用程序时,初始步骤之一是选择使用哪种LLM;它们具有不同的优势和价格点,您可能希望使用多个LLM。
LlamaIndex 为众多不同的大型语言模型提供了统一接口。使用大型语言模型可以像安装相应的集成一样简单:
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集成提供不止一个模型。您可以通过将model参数传递给LLM构造函数来指定模型:
llm = OpenAI(model="gpt-4o-mini")response = llm.complete("Who is Laurie Voss?")print(response)一些大型语言模型支持多模态聊天消息。这意味着您可以传入文本与其他模态(图像、音频、视频等)的混合内容,而大型语言模型将能够处理这些信息。
目前,LlamaIndex支持在ChatMessages中使用内容块来处理文本、图像和音频。
from llama_index.core.llms import ChatMessage, TextBlock, ImageBlockfrom 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 FunctionToolfrom 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等)。
您可以在工具指南中了解更多关于工具和智能体的信息。
可用的大语言模型
Section titled “Available LLMs”我们支持与 OpenAI、Anthropic、Mistral、DeepSeek、Hugging Face 等数十家厂商的集成。查看我们的大语言模型模块指南获取完整列表,包括如何运行本地模型。
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模型的详细信息。