跳转到内容

在LlamaIndex抽象层中自定义LLM

您可以将这些LLM抽象插件集成到LlamaIndex的其他模块中(索引器、检索器、查询引擎、智能体),从而在您的数据上构建高级工作流。

默认情况下,我们使用 OpenAI 的 gpt-3.5-turbo 模型。但您可以选择自定义所使用的底层 LLM。

以下展示了一个自定义所使用大语言模型的示例代码片段。

在此示例中,我们使用 gpt-4o-mini 而非 gpt-3.5-turbo。可用模型包括 gpt-4o-minigpt-4oo3-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 类(或使用更简单接口的 CustomLLM) 您需要负责将文本传递给模型并返回新生成的标记。

该实现可以是某些本地模型,甚至是您自己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调用的回调函数提供可观测性。

请注意,您可能需要调整内部提示以获得良好性能。即便如此,您应该使用足够大的LLM以确保它能够处理LlamaIndex内部使用的复杂查询,因此实际效果可能有所不同。

所有默认内部提示的列表可在此处查看,聊天专用提示在此处列出。您还可以实现自定义提示