[langchain教程]langchain01——用langchain调用大模型

什么是LangChain

LangChain 是一个开源框架,旨在简化基于大型语言模型(LLMs)的应用程序开发。通过模块化组件和链式结构将语言模型与外部数据源、工具和任务流程集成,构建复杂且功能强大的应用程序。

核心概念

组件(Components) :LangChain 提供了多种模块化的构建块,如提示模板、索引、代理等,用于处理不同任务。这些组件可以动态组合,以适应不同的应用场景。
链(Chains) :LangChain 的核心思想是通过“链”将多个组件串联起来,形成一个自动化的工作流。开发者可以通过定义链来实现复杂的任务,例如数据连接、文本生成或问答系统。
代理(Agents) :代理机制允许开发者将任务分解为更小的步骤,并利用语言模型和其他工具完成这些步骤。
提示与模板(Prompts and Templates) :LangChain 提供了预设的提示模板和自定义模板,帮助开发者优化语言模型的输入和输出。
记忆与索引(Memory and Indexes) :LangChain 支持上下文感知和数据持久化,使模型能够记住历史交互并从外部数据源中检索信息

如何用langchain调用大模型

1. 创建提示模板

提示词模板将用户输入和参数转换为语言模型,用于指导模型的响应,帮助其理解上下文并生成相关且连贯的基于语言的输出。

from langchain_core.prompts import ChatPromptTemplate


system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages([
    ('system', system_template),
    ('user', '{text}')
])

result = prompt_template.invoke({"language": "italian", "text": "hi"})
print(result)
result1 = result.to_messages()
print(result1)

提示词模板的输入是一个字典,其中每个键表示要填充的提示词模板中的变量。
例如,上述代码提示词模板的输入是{"language": "italian", "text": "hi"}

输出一个 PromptValue,方便在字符串和消息之间切换,可以传递给 LLM 或 ChatModel,也可以转换为字符串或消息列表。

ChatPromptValue(messages=[SystemMessage(content='Translate the following into italian:'), HumanMessage(content='hi')])

如果想访问消息,可以用result.to_messages()

[SystemMessage(content='Translate the following into italian:'), HumanMessage(content='hi')]

2. 大模型接口

模型接收字符串作为输入,并输出字符串。
LangChain不托管任何大型语言模型,而是依赖于第三方集成。

from langchain_community.llms import Ollama

model = Ollama(model="deepseek-r1:8b")

模型输出如下:

'\nOkay, so I need to translate "hi" from English to Italian. Hmm, let\'s see... I know that in many languages, "hello" is a common greeting, but "hi" is more informal and might be used between friends or people who are closer.\n\nFirst, I should think about the different ways to say "hi." In Italian, I believe the most direct translation is "Ciao." Yeah, that sounds familiar. But wait, isn\'t "ciao" also used for goodbye? So maybe it\'s a bit of both. Like when someone says "Ciao" to a friend, it can mean both hello and bye.\n\nI\'ve heard people use "Ciao" in greetings, especially with friends or family. It feels more casual than saying "Hello." I don\'t think "Buongiorno" is as informal. So "Ciao" seems right for translating "hi."\n\nBut just to make sure, let me consider other possibilities. There\'s also "Salve," which is a formal greeting, like "Hello." But that might be too stiff. For something more casual and direct like "hi," "Ciao" makes sense.\n\nAnother thought: in some regions of Italy, people might use different greetings. But generally, across Italy, "Ciao" is widely used for informal greetings. So I think that\'s the best choice here.\n\n\nThe translation of "hi" from English to Italian is "Ciao." This greeting is commonly used informally between friends or acquaintances and carries a casual tone suitable for such interactions.'

3. 结果解析器

结果解析器负责获取模型的输出并将其转换为更适合下游任务的格式,例如json格式、xml格式等。 在使用大型语言模型生成结构化数据或规范化聊天模型和大型语言模型的输出时非常有用。

from langchain_core.output_parsers import StrOutputParser

parser = StrOutputParser()

结果解析器输出如下:

'\nOkay, so I need to translate "hi" from English to Italian. Hmm, let\'s see... I know that in many languages, "hello" is a common greeting, but "hi" is more informal and might be used between friends or people who are closer.\n\nFirst, I should think about the different ways to say "hi." In Italian, I believe the most direct translation is "Ciao." Yeah, that sounds familiar. But wait, isn\'t "ciao" also used for goodbye? So maybe it\'s a bit of both. Like when someone says "Ciao" to a friend, it can mean both hello and bye.\n\nI\'ve heard people use "Ciao" in greetings, especially with friends or family. It feels more casual than saying "Hello." I don\'t think "Buongiorno" is as informal. So "Ciao" seems right for translating "hi."\n\nBut just to make sure, let me consider other possibilities. There\'s also "Salve," which is a formal greeting, like "Hello." But that might be too stiff. For something more casual and direct like "hi," "Ciao" makes sense.\n\nAnother thought: in some regions of Italy, people might use different greetings. But generally, across Italy, "Ciao" is widely used for informal greetings. So I think that\'s the best choice here.\n\n\nThe translation of "hi" from English to Italian is "Ciao." This greeting is commonly used informally between friends or acquaintances and carries a casual tone suitable for such interactions.'

这段代码中加不加StrOutputParser()输出的内容一样,是因为在这段代码中,StrOutputParser并没有对输出结果产生明显的影响。StrOutputParser的作用是将模型的输出解析为一个字符串,但在这个例子中,模型的输出已经是符合预期的字符串格式,所以即使不使用StrOutputParser,输出结果看起来也是一样的。

4. 创建链连接组件

LangChain表达式语言(LangChain Expression Language,简称LCEL)是LangChain框架中用于构建复杂处理链条的一种声明式方法。它允许开发者以一种简洁、声明式的方式组合多个可运行的组件(Runnables),从而构建出复杂的处理流程

在 LangChain 中,| 符号用于将多个组件或步骤组合成一个链(Chain),这是 LangChain 表达式语言(LCEL)的一部分。| 符号类似于 unix 管道操作符,它以声明式的方式将提示模板、语言模型、输出解析器等组件按顺序连接起来,将一个组件的输出作为下一个组件的输入。

chain = prompt_template | model | parser

在这个链条中,用户输入被传递给提示模板,然后提示模板的输出被传递给模型,然后模型的输出被传递给输出解析器。

5. 调用链条

invoke: 在输入上调用链

chain.invoke({"language": "italian", "text": "hi"})

完整代码示例

from langchain_core.prompts import ChatPromptTemplate


system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages([
    ('system', system_template),
    ('user', '{text}')
])

result = prompt_template.invoke({"language": "italian", "text": "hi"})

from langchain_community.llms import Ollama

model = Ollama(model="deepseek-r1:8b")

from langchain_core.output_parsers import StrOutputParser

parser = StrOutputParser()

chain = prompt_template | model | parser

chain.invoke({"language": "italian", "text": "hi"})

你可能感兴趣的:(LangChain,langchain,python,人工智能,语言模型,chatgpt)