Langchain Academy translated
  • module-0
    • LangChain 学院
  • module-1
    • 智能体记忆
    • 智能体
    • 链式结构
    • 部署
    • 路由器
    • 最简单的图结构
  • module-2
    • 支持消息摘要与外部数据库记忆的聊天机器人
    • 支持消息摘要的聊天机器人
    • 多模式架构
    • 状态归约器
    • 状态模式
    • 消息过滤与修剪
  • module-3
    • 断点
    • 动态断点
    • 编辑图状态
    • 流式处理
    • 时间回溯
  • module-4
    • 映射-归约
    • 并行节点执行
    • 研究助手
    • 子图
  • module-5
    • 记忆代理
    • 具备记忆功能的聊天机器人
    • 基于集合架构的聊天机器人
    • 支持个人资料架构的聊天机器人
  • module-6
    • 助手
    • 连接 LangGraph 平台部署
    • 创建部署
    • 双重消息处理
  • Search
  • Previous
  • Next
  • LangChain 学院
    • 背景
    • 课程结构
    • 环境配置
    • 聊天模型
    • 搜索工具

在 Colab 中打开 在 LangChain Academy 中打开

LangChain 学院¶

欢迎来到 LangChain 学院!

背景¶

在 LangChain,我们的目标是让构建大语言模型(LLM)应用变得简单。其中一种可构建的 LLM 应用就是智能体(agent)。构建智能体令人兴奋,因为它们能自动化执行许多过去无法完成的任务。

然而在实践中,要构建能可靠执行这些任务的系统极其困难。通过帮助用户将智能体投入生产的经验,我们发现往往需要更多控制。例如,可能需要智能体总是优先调用特定工具,或根据其状态使用不同的提示词。

为解决这个问题,我们开发了 LangGraph —— 一个用于构建智能体和多智能体应用的框架。作为独立于 LangChain 的包,LangGraph 的核心设计理念是帮助开发者在智能体工作流中实现更精确的控制,以应对现实世界系统的复杂性。

课程结构¶

本课程由多个模块组成,每个模块聚焦 LangGraph 的特定主题。每个模块对应一个文件夹,其中包含系列笔记文档。每个笔记文档配有讲解视频,但这些文档本身也是自包含的——它们包含完整解释,可不依赖视频独立阅读。每个模块文件夹还包含一个 studio 子文件夹,内含可加载到 LangGraph Studio(我们的 LangGraph 应用开发 IDE)中的图表集合。

环境配置¶

开始前,请按照 README 文件的说明创建环境并安装依赖项。

聊天模型¶

本课程将使用 聊天模型,这类模型以消息序列作为输入并返回聊天消息作为输出。LangChain 不托管任何聊天模型,而是依赖第三方集成。此处 是 LangChain 支持的第三方聊天模型集成列表!默认情况下,课程将使用 ChatOpenAI,因其兼具流行性和高性能。请注意确保您已配置 OPENAI_API_KEY。

下面将检查您的 OPENAI_API_KEY 是否已设置,若未设置则会提示输入。

In [ ]:
Copied!
%%capture --no-stderr
%pip install --quiet -U langchain_openai langchain_core langchain_community tavily-python
%%capture --no-stderr %pip install --quiet -U langchain_openai langchain_core langchain_community tavily-python
In [1]:
Copied!
import os, getpass

def _set_env(var: str):
    if not os.environ.get(var):
        os.environ[var] = getpass.getpass(f"{var}: ")

_set_env("OPENAI_API_KEY")
import os, getpass def _set_env(var: str): if not os.environ.get(var): os.environ[var] = getpass.getpass(f"{var}: ") _set_env("OPENAI_API_KEY")

这里提供了关于聊天模型所有功能的实用指南,但我们将在下方展示几个重点内容。若您已按照README说明执行了pip install -r requirements.txt命令,则已安装langchain-openai包。通过该包,我们可以实例化ChatOpenAI模型对象。首次注册API时,您将获得可应用于任何模型的免费额度。各模型定价详情可在此查看。本笔记本默认使用gpt-4o模型,因其在质量、价格和速度间取得了良好平衡(更多说明),但您也可选择价格更低的gpt-3.5系列模型。

聊天模型有若干标准参数可供设置,其中两个最常用的是:

  • model:模型名称
  • temperature:采样温度

Temperature参数控制模型输出的随机性或创造性:较低温度值(接近0)会产生更确定性和聚焦的输出,适用于需要准确性或事实性回答的任务;较高温度值(接近1)则适合创意性任务或需要多样化输出的场景。

In [2]:
Copied!
from langchain_openai import ChatOpenAI
gpt4o_chat = ChatOpenAI(model="gpt-4o", temperature=0)
gpt35_chat = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
from langchain_openai import ChatOpenAI gpt4o_chat = ChatOpenAI(model="gpt-4o", temperature=0) gpt35_chat = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)

LangChain 中的聊天模型具有一系列默认方法。大多数情况下,我们会使用:

  • stream:以数据块流式返回响应
  • invoke:在输入上调用链

如前所述,聊天模型接收消息作为输入。消息包含角色(描述消息发送者)和内容属性。后续我们会深入讨论这一点,这里先展示基础概念。

In [3]:
Copied!
from langchain_core.messages import HumanMessage

# Create a message
msg = HumanMessage(content="Hello world", name="Lance")

# Message list
messages = [msg]

# Invoke the model with a list of messages 
gpt4o_chat.invoke(messages)
from langchain_core.messages import HumanMessage # Create a message msg = HumanMessage(content="Hello world", name="Lance") # Message list messages = [msg] # Invoke the model with a list of messages gpt4o_chat.invoke(messages)
Out[3]:
AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 11, 'total_tokens': 20}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_157b3831f5', 'finish_reason': 'stop', 'logprobs': None}, id='run-d3c4bc85-ef14-49f6-ba7e-91bf455cffee-0', usage_metadata={'input_tokens': 11, 'output_tokens': 9, 'total_tokens': 20})

我们得到一个 AIMessage 类型的响应。同时需要注意,我们可以直接用字符串调用聊天模型。当输入是字符串时,它会被转换为 HumanMessage 类型,然后传递给底层模型。

In [4]:
Copied!
gpt4o_chat.invoke("hello world")
gpt4o_chat.invoke("hello world")
Out[4]:
AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 9, 'total_tokens': 18}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_157b3831f5', 'finish_reason': 'stop', 'logprobs': None}, id='run-d6f6b682-e29a-44de-b45e-79fad1e405e5-0', usage_metadata={'input_tokens': 9, 'output_tokens': 9, 'total_tokens': 18})
In [5]:
Copied!
gpt35_chat.invoke("hello world")
gpt35_chat.invoke("hello world")
Out[5]:
AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 9, 'total_tokens': 18}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-c75d3f0f-2d71-47be-b14c-42b8dd2b4b08-0', usage_metadata={'input_tokens': 9, 'output_tokens': 9, 'total_tokens': 18})

所有聊天模型的接口保持一致,模型通常在每个笔记本启动时初始化一次。

因此,如果您对其他提供商有强烈偏好,可以轻松切换模型而无需更改下游代码。

搜索工具¶

在 README 文件中你还会看到 Tavily,这是一个专为 LLM 和 RAG 优化的搜索引擎,旨在提供高效、快速且持久的搜索结果。如前所述,它注册简便且提供慷慨的免费套餐。部分课程(在模块4中)会默认使用 Tavily,当然如果你想自行修改代码,也可以使用其他搜索工具。

In [10]:
Copied!
_set_env("TAVILY_API_KEY")
_set_env("TAVILY_API_KEY")
In [6]:
Copied!
from langchain_community.tools.tavily_search import TavilySearchResults
tavily_search = TavilySearchResults(max_results=3)
search_docs = tavily_search.invoke("What is LangGraph?")
from langchain_community.tools.tavily_search import TavilySearchResults tavily_search = TavilySearchResults(max_results=3) search_docs = tavily_search.invoke("What is LangGraph?")
In [7]:
Copied!
search_docs
search_docs
Out[7]:
[{'url': 'https://www.datacamp.com/tutorial/langgraph-tutorial',
  'content': 'LangGraph is a library within the LangChain ecosystem designed to tackle these challenges head-on. LangGraph provides a framework for defining, coordinating, and executing multiple LLM agents (or chains) in a structured manner.'},
 {'url': 'https://langchain-ai.github.io/langgraph/',
  'content': 'Overview LangGraph is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows. Compared to other LLM frameworks, it offers these core benefits: cycles, controllability, and persistence. LangGraph allows you to define flows that involve cycles, essential for most agentic architectures, differentiating it from DAG-based solutions. As a ...'},
 {'url': 'https://www.youtube.com/watch?v=nmDFSVRnr4Q',
  'content': 'LangGraph is an extension of LangChain enabling Multi-Agent conversation and cyclic chains. This video explains the basics of LangGraph and codesLangChain in...'}]
In [ ]:
Copied!


Documentation built with MkDocs.

Search

From here you can search these documents. Enter your search terms below.

Keyboard Shortcuts

Keys Action
? Open this help
n Next page
p Previous page
s Search