AI创想

标题: LangChain学习——核心组件 [打印本页]

作者: 林克link02    时间: 2025-9-7 23:39
标题: LangChain学习——核心组件
LangChain是一个用于大语言模型(LLM)应用开发的框架,它简化了LLM应用的开发难度,帮助开发者快速构建复杂的LLM应用。
一、LangChain 库简介

LangChain 包的主要价值主张是:
现成的链使得开始变得容易。组件使得定制现有链和构建新链变得容易。
LangChain 库本身由几个不同的包组成。
二、LangChain的核心组件

        1、模型输入输出(Model I/O)

        这是与各种大语言模型进行交互的基本组件。它允许开发者管理提示(prompt),通过通用接口调用语言模型,并从模型输出中提取信息。简单来说,这个组件负责与大语言模型“对话”,将我们的请求传递给模型,并接收模型的回复。


  1. from langchain.prompts import PromptTemplate
  2. template = PromptTemplate.from_template("给我讲个关于{subject}的故事")
  3. print(template.format(subject='星座'))
复制代码
  1. from langchain.prompts import (
  2.     ChatPromptTemplate,
  3.     HumanMessagePromptTemplate,
  4.     SystemMessagePromptTemplate,
  5. )
  6. from langchain_openai import ChatOpenAI
  7. template = ChatPromptTemplate.from_messages(
  8.     [
  9.         SystemMessagePromptTemplate.from_template(
  10.             "你是{product}的客服助手。你的名字叫{name}"),
  11.         HumanMessagePromptTemplate.from_template("{query}"),
  12.     ]
  13. )
  14. llm = ChatOpenAI()
  15. prompt = template.format_messages(
  16.     product="手机客服",
  17.     name="小花",
  18.     query="你是谁"
  19. )
  20. ret = llm.invoke(prompt)
  21. print(ret.content)
复制代码
  1. from langchain.prompts import (
  2.     ChatPromptTemplate,
  3.     HumanMessagePromptTemplate,
  4.     MessagesPlaceholder,
  5. )
  6. from langchain_core.messages import AIMessage, HumanMessage
  7. human_prompt = "Translate your answer to {language}."
  8. human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)
  9. chat_prompt = ChatPromptTemplate.from_messages(
  10.     [MessagesPlaceholder(variable_name="conversation"), human_message_template]
  11. )
  12. human_message = HumanMessage(content="Who is Elon Musk?")
  13. ai_message = AIMessage(
  14.     content="Elon Musk is a billionaire entrepreneur, inventor, and industrial designer"
  15. )
  16. messages = chat_prompt.format_prompt(
  17.     # 对 "conversation" 和 "language" 赋值
  18.     conversation=[human_message, ai_message], language="中文"
  19. )
  20. result = llm.invoke(messages)
  21. print(result.content)
复制代码





欢迎光临 AI创想 (http://llms-ai.com/) Powered by Discuz! X3.4