llama_index 如何为模型设置默认提示模板?

klh5stk1  于 2个月前  发布在  其他
关注(0)|答案(2)|浏览(41)

问题验证

  • 我已经在文档和discord上搜索过答案。

问题

我设置了使用远程llama-3模型:

import os

from llama_index.core import PromptTemplate
from llama_index.llms.openai_like import OpenAILike

SERVER_LLAMACPP = os.getenv("SERVER_LLAMACPP", "http://localhost:8181")
os.environ["OPENAI_API_KEY"] = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
os.environ["OPENAI_API_BASE"] = f"{SERVER_LLAMACPP}/v1"
os.environ["OPENAI_API_HOST"] = f"{SERVER_LLAMACPP}"
model = OpenAILike()

p = """<|begin_of_text|><|start_header_id|>system<|end_header_id|>

{system_prompt}<|eot_id|><|start_header_id|>user<|end_header_id|>

{prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
print(
    model.complete(
        prompt=p.format(
            system_prompt="You reply accurately to the user",
            prompt="What is the capital of France?",
        )
    )
)

OpenAILike中,我可以分配一个query_wrapper_prompt参数,但这似乎没有任何区别,如果我稍后调用这个(输出是乱码):

model.complete(prompt="What is the capital of France?")

一种可能的方法是子类化OpenAILike,然后用llama-3提示模板格式化我的内容,但这似乎有点过分。我在文档或问题中找不到关于默认提示模板的信息,我的问题是:

  • 如何将PromptTemplate设置为模型的默认 Package 器?
  • 这是与llama-index正确合作的方式吗?
ztmd8pv5

ztmd8pv51#

要将 PromptTemplate 设置为与 llama-index 一起使用的模型的默认 Package 器,您可以使用 SelectorPromptTemplate 类来定义您的默认提示和任何条件。以下是如何执行此操作的示例:

from llama_index.core.prompts.base import SelectorPromptTemplate, PromptTemplate
from llama_index.core.prompts.utils import is_chat_model

# Define your custom PromptTemplate
custom_prompt_template = PromptTemplate(template="Your custom prompt template here")

# Define conditionals if any (e.g., for chat models)
custom_conditionals = [(is_chat_model, custom_prompt_template)]

# Create a SelectorPromptTemplate with your custom prompt and conditionals
CUSTOM_PROMPT_SEL = SelectorPromptTemplate(
    default_template=custom_prompt_template,
    conditionals=custom_conditionals,
)

# Now, `CUSTOM_PROMPT_SEL` is set as the default wrapper for the model

此代码片段演示了如何创建一个 SelectorPromptTemplate,定义自定义提示和条件,并将其设置为模型的默认 Package 器。 SelectorPromptTemplate 类允许您指定默认模板和条件,类似于在 llama-index 库中定义默认提示选择器的方式。
关于您的第二个问题,当您需要为您的模型设置默认提示模板时,这种方法确实是一种合适的处理方式。它避免了需要继承 OpenAILike 并提供了一种灵活的管理提示模板的方法。

  • 要继续与 Dosu 交谈,请提及 @dosu。*
c0vxltue

c0vxltue2#

@egeres,您可以在OpenAILike中设置一些函数钩子,例如completion_to_prompt()messages_to_prompt()

相关问题