1.langchain 入门到放弃(一) mode I&O
部署
pip install langchain
LLMS(Large Language Model)
python.langchain.com/v0.1/docs/m…
-
支持多种模型接口,比如 OpenAI、Hugging Face、AzureOpenAI ...
-
缓存的支持,比如 in-mem(内存)、SQLite、Redis、SQL
-
支持流模式(就是一个字一个字的返回,类似打字效果)
model = ChatOpenAI(temperature=0, api_key="sk-nrKGd0JGzis7dMo95aF09642Be354fE3BdD7C61d2sss",
base_url="https://api.chatgpt-3.vip/v1", max_tokens=1000)
PromptTemplate
python.langchain.com/v0.1/docs/m…
提示词模版
每条聊天消息都与内容以及称为角色的附加参数相关联。例如,在 OpenAI Chat Completions API 中,聊天消息可以与 AI 助手、人类或系统角色相关联。
system_template = """你是个资深{domain}专家,在此行业有独到见解."""
human_template = "{input}"
# 创建系统消息和人类消息的PromptTemplate实例
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 使用这两个模板创建ChatPromptTemplate实例
prompt_template = ChatPromptTemplate.from_messages([
system_message_prompt,
human_message_prompt,
])
Output Parsers
输出解析器负责获取 LLM 的输出并将其转换为更合适的格式
python.langchain.com/v0.1/docs/m…
# 格式化输出
parser = StrOutputParser()
Chains
python.langchain.com/v0.1/docs/m…
暂时理解其为任务
- LLMChain
- 各种工具Chain
chain = prompt_template | model | parser
示例
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain_openai import ChatOpenAI
system_template = """你是个资深{domain}专家,在此行业有独到见解."""
human_template = "{input}"
# 创建系统消息和人类消息的PromptTemplate实例
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 使用这两个模板创建ChatPromptTemplate实例
prompt_template = ChatPromptTemplate.from_messages([
system_message_prompt,
human_message_prompt,
])
model = ChatOpenAI(temperature=0, api_key="sk-nrKGd0JGzis7dMo95aF09642Be354fE3BdD7C61d767as123",
base_url="https://api.chatgpt-3.vip/v1", max_tokens=1000)
# 格式化输出
parser = StrOutputParser()
chain = prompt_template | model | parser
print(chain.invoke({'domain':'游戏','input': '2000年发生了什么大事'}))