5. 底层接口
# 5.1 提示词模板(PromptTemplate)
from llama_index.core import PromptTemplate
prompt = PromptTemplate("写一个关于{topic}的笑话")
msg = prompt.format(topic="小明")
print(msg)
# out:写一个关于小明的笑话
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 5.2 多轮消息模板(ChatPromptTemplate)
from llama_index.core.llms import ChatMessage, MessageRole
from llama_index.core import ChatPromptTemplate
chat_text_qa_msgs = [
ChatMessage(
role=MessageRole.SYSTEM,
content="你叫{name},你必须根据用户提供的上下文回答问题。",
),
ChatMessage(
role=MessageRole.USER,
content=(
"已知上下文:\n"
"{context}\n\n"
"问题:{question}"
)
),
]
text_qa_template = ChatPromptTemplate(chat_text_qa_msgs)
print(
text_qa_template.format(
name="圆球",
context="这是一个测试",
question="这是什么"
)
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 5.3 OpenAI 参数指定
from llama_index.core import PromptTemplate
from llama_index.llms.openai import OpenAI
prompt = PromptTemplate("写一个关于{topic}的笑话")
llm = OpenAI(temperature=0, model="gpt-4o")
response = llm.complete(prompt.format(topic="小明"))
print(response.text)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 5.4 设置全局使用的语言模型
from llama_index.core import Settings
Settings.llm = OpenAI(temperature=0, model="gpt-4o")
1
2
3
2
3
除 OpenAI 外,LlamaIndex 已集成多个大语言模型,包括云服务 API 和本地部署 API,详见官方文档:Available LLM integrations (opens new window)。比较遗憾的是,除了零一万物以外没有国内的模型集成。
# 5.5 Embedding 模型
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core import Settings
# 全局设定
Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small", dimensions=512)
1
2
3
4
5
2
3
4
5
编辑 (opens new window)
上次更新: 2025/12/19, 15:17:48