一、文档地址
二、Tutorials
快速上手案例
1. 基础
1.1 使用LCEL构建简单的LLM应用程序
案例说明
将把文本从英语翻译成另一种语言。案例中会用到language models语言模型、PromptTemplates模板、 OutputParsers输出解析器、LangChain Expression Language (LCEL)langchain表达语言、LangSmith调速器、LangServe服务器
其他说明
(1)文档中的案例采用了openai模型,作者学习时采用的是本地部署的qwen。详细部署参考win10部署本地大模型langchain+ollama_win10如何运行大模型-优快云博客
(2)文档中采用的是chatModel(聊天模型,交互式的对话)作为案例,与之对应的是LLM(大语言模型,文本生成和补全)。接下来会展示二者输出的差异。
from langchain_community.llms import Ollama
from langchain_community.chat_models import ChatOllama
from langchain_core.messages import HumanMessage,SystemMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
# 使用llm
llm = Ollama(model="qwen:7b")
# 使用chatmodel
model = ChatOllama(model="qwen:7b")
# 使用格式化+链式
parser=StrOutputParser()
chain=model|parser
# 固定messages
messages=[
SystemMessage(content="Translate the following from English into Chinese"),
HumanMessage(content="hi")
]
# 使用模板
system_template = "Translate the following into {language}:"
human_template = "{text}"
prompt_template = ChatPromptTemplate.from_messages(
[("system", system_template),("user", human_template)]
)
# langchain表达式;也就是采用“|”连接上下的component
chain1=prompt_template|chain
# 输出
print(llm.invoke(messages))
#你好!
print(model.invoke(messages))
# content = '你好!有什么我可以帮助你的吗?'
# response_metadata = {'model': 'qwen:7b', 'created_at': '2024-07-13T03:32:15.601267Z',
# 'message': {'role': 'assistant', 'content': ''}, 'done': True, 'total_duration': 6628953700,
# 'load_duration': 12998500, 'prompt_eval_count': 19, 'prompt_eval_duration': 3899168000,
# 'eval_count': 9, 'eval_duration': 2712232000}
# id = 'run-5aa393a8-a19b-42bf-9021-3ad8a1512484-0'
print(chain.invoke(messages))
# 你好!有什么我可以帮助你的吗?
print(chain1.invoke({"language":"中文","text":"hi"}))
#你好!有什么我能帮助你的吗?