1. Langchain环境搭建-本地模型应用
1.1 Ollama LangChain第三方库安装
使用以下命令安装集成包:
python
pip install langchain-ollama
使用:
python
# 大语言模型
# 大语言模型
from langchain_ollama import ChatOllama
llm = ChatOllama(
model="gemma3:1b",
temperature=0,
# other params...
)
messages = [
(
"system",
"你是一个助手,请用中文回复",
),
("human","夏天适合穿什么小裙子"),
]
ai_msg = llm.invoke(messages)
print(ai_msg)
print(ai_msg.content)
2. langchain的关键对象-提示词模板
它的作用是将用户的输入或动态的数据结构嵌入到预定义的模板中 ,从而生成适合模型处理的提示词 ,提升模型输出的准确性和一致性
python
from langchain_core.prompts import PromptTemplate
template = '你是一个{role}, 请问一个{style}的风格回答问题,回答的问题是什么{question}'
prompt = PromptTemplate.from_template(template=template)
filed_prompt = prompt.format(role ='历史老师', style='幽默风趣', question='三国是从什么时候开始的?')
ai_msg = chat.invoke(filed_prompt)
print(ai_msg.content)
python
from langchain_core.prompts import ChatPromptTemplate
sys_template = '你是一个{role}, 请问一个{style}的风格回答问题,回答的问题是什么{question}'
user_template = '请问简单易懂的方式回答{question}'
prompt = ChatPromptTemplate.from_messages([('system', sys_template), ('human', user_template)])
sys_filed_prompt = prompt.format(role ='历史老师', style='幽默风趣', question='三国是从什么时候开始的?')
ai_msg = chat.invoke(sys_filed_prompt)
print(ai_msg.content)