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
是否已设置,若未设置则会提示输入。
%%capture --no-stderr
%pip install --quiet -U langchain_openai langchain_core langchain_community tavily-python
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)则适合创意性任务或需要多样化输出的场景。
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_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)
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
类型,然后传递给底层模型。
gpt4o_chat.invoke("hello world")
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})
gpt35_chat.invoke("hello world")
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})
所有聊天模型的接口保持一致,模型通常在每个笔记本启动时初始化一次。
因此,如果您对其他提供商有强烈偏好,可以轻松切换模型而无需更改下游代码。
_set_env("TAVILY_API_KEY")
from langchain_community.tools.tavily_search import TavilySearchResults
tavily_search = TavilySearchResults(max_results=3)
search_docs = tavily_search.invoke("What is LangGraph?")
search_docs
[{'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...'}]