在LlamaIndex抽象层中自定义LLM
您可以将这些LLM抽象插件集成到LlamaIndex的其他模块中(索引器、检索器、查询引擎、智能体),从而在您的数据上构建高级工作流。
默认情况下,我们使用 OpenAI 的 gpt-3.5-turbo 模型。但您可以选择自定义所使用的底层 LLM。
以下展示了一个自定义所使用大语言模型的示例代码片段。
在此示例中,我们使用 gpt-4o-mini 而非 gpt-3.5-turbo。可用模型包括 gpt-4o-mini、gpt-4o、o3-mini 等。
from llama_index.core import Settings, VectorStoreIndex, SimpleDirectoryReaderfrom llama_index.llms.openai import OpenAI
# define LLMllm = OpenAI(temperature=0.1, model="gpt-4o-mini")
# change the global default LLMSettings.llm = llm
documents = SimpleDirectoryReader("data").load_data()
# build indexindex = VectorStoreIndex.from_documents(documents)
# locally override the LLMquery_engine = index.as_query_engine(llm=llm)response = query_engine.query( "What did the author do after his time at Y Combinator?")示例:使用自定义LLM模型 - 高级
Section titled “Example: Using a Custom LLM Model - Advanced”要使用自定义LLM模型,您只需实现 LLM 类(或使用更简单接口的 CustomLLM)
您需要负责将文本传递给模型并返回新生成的标记。
该实现可以是某些本地模型,甚至是您自己API的封装。
请注意,为了获得完全私密的体验,还需设置一个本地嵌入模型。
以下是一个小型模板示例:
from typing import Optional, List, Mapping, Any
from llama_index.core import SimpleDirectoryReader, SummaryIndexfrom llama_index.core.callbacks import CallbackManagerfrom llama_index.core.llms import ( CustomLLM, CompletionResponse, CompletionResponseGen, LLMMetadata,)from llama_index.core.llms.callbacks import llm_completion_callbackfrom 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 LLMSettings.llm = OurLLM()
# define embed modelSettings.embed_model = "local:BAAI/bge-base-en-v1.5"
# Load the your datadocuments = SimpleDirectoryReader("./data").load_data()index = SummaryIndex.from_documents(documents)
# Query and print responsequery_engine = index.as_query_engine()response = query_engine.query("<query_text>")print(response)使用此方法,您可以使用任何大型语言模型。也许您有在本地运行的模型,或在您自己的服务器上运行的模型。只要类已实现且返回生成的令牌,它就应该能正常工作。请注意,我们需要使用提示助手来自定义提示大小,因为每个模型的上下文长度略有不同。
装饰器是可选的,但通过LLM调用的回调函数提供可观测性。
请注意,您可能需要调整内部提示以获得良好性能。即便如此,您应该使用足够大的LLM以确保它能够处理LlamaIndex内部使用的复杂查询,因此实际效果可能有所不同。