主题
你可以把这些 LLM 抽象插入 LlamaIndex 的其他模块(索引、检索器、查询引擎、agent),从而在你的数据之上构建更复杂的流程。
默认使用 OpenAI 的 gpt-3.5-turbo 模型。但你可以自行指定底层要用的 LLM。
示例:更换底层 LLM
下面这段示例代码演示如何定制所用的 LLM。
这个例子里我们用 gpt-4o-mini 取代 gpt-3.5-turbo。可选模型包括 gpt-4o-mini、gpt-4o、o3-mini 等。
from llama_index.core import Settings, VectorStoreIndex, SimpleDirectoryReader
from llama_index.llms.openai import OpenAI
# define LLM
llm = OpenAI(temperature=0.1, model="gpt-4o-mini")
# change the global default LLM
Settings.llm = llm
documents = SimpleDirectoryReader("data").load_data()
# build index
index = VectorStoreIndex.from_documents(documents)
# locally override the LLM
query_engine = index.as_query_engine(llm=llm)
response = query_engine.query(
"What did the author do after his time at Y Combinator?"
)示例:使用自定义 LLM 模型 —— 进阶
要使用自定义 LLM 模型,你只需实现 LLM 类(或接口更简化的 CustomLLM)。你需要自己负责把文本传给模型,并返回新生成的 token。
这个实现可以是某个本地模型,甚至可以是你自己 API 的一层包装。
请注意,想要完全私密的体验,还要配上本地嵌入模型。
这里给一个精简的样板示例:
from typing import Optional, List, Mapping, Any
from llama_index.core import SimpleDirectoryReader, SummaryIndex
from llama_index.core.callbacks import CallbackManager
from llama_index.core.llms import (
CustomLLM,
CompletionResponse,
CompletionResponseGen,
LLMMetadata,
)
from llama_index.core.llms.callbacks import llm_completion_callback
from llama_index.core import Settings
class OurLLM(CustomLLM):
context_window: int = 3900
num_output: int = 256
model_name: str = "custom"
dummy_response: str = "My response"
@property
def metadata(self) -> LLMMetadata:
"""Get LLM metadata."""
return LLMMetadata(
context_window=self.context_window,
num_output=self.num_output,
model_name=self.model_name,
)
@llm_completion_callback()
def complete(self, prompt: str, **kwargs: Any) -> CompletionResponse:
return CompletionResponse(text=self.dummy_response)
@llm_completion_callback()
def stream_complete(
self, prompt: str, **kwargs: Any
) -> CompletionResponseGen:
response = ""
for token in self.dummy_response:
response += token
yield CompletionResponse(text=response, delta=token)
# define our LLM
Settings.llm = OurLLM()
# define embed model
Settings.embed_model = "local:BAAI/bge-base-en-v1.5"
# Load the your data
documents = SimpleDirectoryReader("./data").load_data()
index = SummaryIndex.from_documents(documents)
# Query and print response
query_engine = index.as_query_engine()
response = query_engine.query("<query_text>")
print(response)用这种方式你可以接任何 LLM——无论是跑在本机上,还是跑在你自己的服务器上。只要实现好这个类并把生成的 token 返回来,就能工作。注意我们需要用 prompt helper 来调整提示词尺寸,因为每个模型的上下文长度都略有不同。
那个装饰器是可选的,它会在 LLM 调用时通过回调提供可观测性。
你可能需要调整内部提示词才能得到理想表现。即便如此,也建议使用足够大的 LLM,才有能力承接 LlamaIndex 内部那些复杂查询,所以实际效果因人而异。