【GPT入门】第19课 Langchain IO模型
【GPT入门】第19课 Langchain IO模型
- 概述
- 1. 四行代码调用OPENAI
- 2.三种角色
- 3. IO模型
- 3.1 PromptTemplate 可以在模板中自定义变量
- 3.2 ChatPromptTemplate用模板表示的对话上下文
- 3.3 从文件中加载prompt
- 3.4 从json_schema定义输出格式
- 3.5 json输出的第二种方法
- 3.6 OutputFixingParser做格式自动修正
概述
本文讲 LangChain 的核心组件
模型 I/O 封装
LLMs:大语言模型
Chat Models:一般基于 LLMs,但按对话结构重新封装
PromptTemple:提示词模板
OutputParser:解析输出
1. 四行代码调用OPENAI
from langchain_openai import ChatOpenAI
llm = ChatOpenAI()
response = llm.invoke("你是谁")
print(response.content)
2.三种角色
from langchain.schema import (
AIMessage, # 相当于OpenAI的ChatCompletion的role="assistant"
HumanMessage, # 相当于OpenAI的ChatCompletion的role="user"
SystemMessage # 相当于OpenAI的ChatCompletion的role="system"
)
from langchain_openai import ChatOpenAI
messages = [
SystemMessage(content="你是一个专业的翻译员"),
HumanMessage(content="你好,我想翻译一段英文,你能帮我吗?"),
AIMessage(content="当然可以,你可以告诉我你要翻译的英文是什么?"),
HumanMessage(content="how are you?")
]
llm = ChatOpenAI()
ret = llm.invoke(messages)
print(ret)
3. IO模型
3.1 PromptTemplate 可以在模板中自定义变量
from langchain.prompts import PromptTemplate
template = PromptTemplate.from_template("给我讲一个关于{subject}的笑话")
print(template)
print(template.format(subject="猫"))
template = PromptTemplate.from_template("给我讲主角是{name},主题是{subject}的笑话")
print(template)
print(template.format(name="小明", subject="猫"))
from langchain_openai import ChatOpenAI
llm = ChatOpenAI()
ret = llm.invoke(template.format(name="小明", subject="猫"))
print(ret)
3.2 ChatPromptTemplate用模板表示的对话上下文
from langchain.prompts import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
template = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template(
"你是{product}到客服助手,你的名字叫{name}"),
HumanMessagePromptTemplate.from_template("{query}")
])
llm = ChatOpenAI()
prompt = template.format_messages(
product="小米",
name="小爱同学",
query="你是谁"
)
ret = llm.invoke(prompt)
print(ret.content)
#我是小米客服助手,你可以叫我小爱同学。有什么问题我可以帮你解决呢?
3.3 从文件中加载prompt
from langchain.prompts import PromptTemplate
template = PromptTemplate.from_file("myPrompt.txt", encoding='utf-8')
print(template)
print(template.format(boyName="小明", girlName="小红"))
3.4 从json_schema定义输出格式
json_schema = {
"title": "Date",
"description": "Formated date expression",
"type": "object",
"properties": {
"year": {
"type": "integer",
"description": "year, YYYY",
},
"month": {
"type": "integer",
"description": "month, MM",
},
"day": {
"type": "integer",
"description": "day, DD",
},
"era": {
"type": "string",
"description": "BC or AD",
},
},
}
structure_llm = llm.with_structured_output(json_schema)
print(structure_llm.invoke(input_prompt))
3.5 json输出的第二种方法
from langchain_core.output_parsers import JsonOutputParser
parser = JsonOutputParser(pydantic_object=Date)
prompt = PromptTemplate(
template="提取用户输入中的日期。\n用户输入:{query}\n{format_instructions}",
input_variables=["query"],
partial_variables={"format_instructions": parser.get_format_instructions()},
)
query = "2025年三月6日天气晴..."
input_prompt = prompt.format_prompt(query=query)
output = llm.invoke(input_prompt)
print("原始输出:\n"+output.content)
print("\n解析后:")
print(parser.invoke(output))
3.6 OutputFixingParser做格式自动修正
from langchain.output_parsers import OutputFixingParser
new_parser = OutputFixingParser.from_llm(parser=parser, llm=ChatOpenAI())
bad_output = output.content.replace("3","四")
print("PydanticOutputParser:")
try:
print(parser.invoke(bad_output))
except Exception as e:
print(e)
print("OutputFixingParser:")
print(new_parser.invoke(bad_output))