跳到主要内容

文档索引

在以下地址获取完整的文档索引:https://docs.langchain.org.cn/llms.txt

在进一步探索之前,请使用此文件发现所有可用页面。

本快速入门指南将向您展示如何在几分钟内创建一个功能齐全的 AI 智能体。
正在使用 AI 编程助手?

安装依赖项

安装以下软件包以跟随操作
uv init
uv add langchain deepagents
uv sync

设置 API 密钥

任何支持的模型提供商(例如 Google Gemini 或 OpenAI)处获取 API 密钥。 设置 API 密钥,例如:
export OPENAI_API_KEY="your-api-key"

构建一个基础智能体

首先创建一个简单的智能体,它能够回答问题并调用工具。此示例中的智能体使用了所选的语言模型、一个基础天气函数作为工具,以及一个简单的提示词来引导其行为。
from langchain.agents import create_agent

def get_weather(city: str) -> str:
    """Get weather for a given city."""
    return f"It's always sunny in {city}!"

agent = create_agent(
    model="openai:gpt-5.4",
    tools=[get_weather],
    system_prompt="You are a helpful assistant",
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)
当您运行代码并提示智能体告知您旧金山的天气时,智能体会利用该输入及其可用的上下文。智能体能够理解您是在询问旧金山的天气,因此会使用提供的城市名称调用天气工具。
通过更改代码中的模型名称并设置相应的 API 密钥,您可以使用任何支持的模型

构建一个实际应用场景的智能体

在接下来的示例中,您将构建一个研究型智能体,它可以回答有关文本文件的问题。在此过程中,您将探索以下概念:
  1. 详细的系统提示词:用于获得更好的智能体行为
  2. 创建工具:与外部数据进行集成
  3. 模型配置:获得一致的响应
  4. 对话记忆:实现类似聊天的交互
  5. Deep Agents:内置的功能特性
  6. 测试:您的智能体
1

定义系统提示词

系统提示词定义了智能体的角色和行为。请保持其具体且可执行。
SYSTEM_PROMPT = """You are a literary data assistant.

## Capabilities

- `fetch_text_from_url`: loads document text from a URL into the conversation.
Do not guess line counts or positions—ground them in tool results from the saved file."""
2

创建工具

工具允许模型通过调用您定义的函数与外部系统进行交互。工具可以依赖运行时上下文,也可以与智能体记忆进行交互。此示例使用一个工具从给定的 URL 加载文档:
import urllib.error
import urllib.request

from langchain.tools import tool


@tool
def fetch_text_from_url(url: str) -> str:
    """Fetch the document from a URL.
    """
    req = urllib.request.Request(
        url,
        headers={"User-Agent": "Mozilla/5.0 (compatible; quickstart-research/1.0)"},
    )
    try:
        with urllib.request.urlopen(req, timeout=120) as resp:
            raw = resp.read()
    except urllib.error.URLError as e:
        return f"Fetch failed: {e}"
    text = raw.decode("utf-8", errors="replace")
    return text
工具应具备良好的文档说明:其名称、描述和参数名称将成为模型提示词的一部分。LangChain 的 @tool 装饰器会添加元数据,并支持使用 ToolRuntime 参数进行运行时注入。在工具指南中了解更多信息。
3

配置您的模型

使用适合您用例的参数来设置您的语言模型。例如:
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "openai:gpt-5.4",
    temperature=0.5,
    timeout=300,
    max_tokens=25000,
)
根据所选的模型和提供商,初始化参数可能会有所不同;请参阅其参考页面了解详情。
4

添加记忆

为您的智能体添加记忆功能,以便在交互过程中保持状态。这允许智能体记住之前的对话和上下文。
from langgraph.checkpoint.memory import InMemorySaver

checkpointer = InMemorySaver()
在生产环境中,请使用将消息历史记录保存到数据库的持久检查点(checkpointer)。有关详细信息,请参阅添加和管理记忆
5

创建并运行智能体

现在将所有组件组装起来并运行您的智能体。有两种不同的框架用于创建智能体:LangChain 智能体和 Deep Agents。LangChain 和 Deep Agents 都为您提供了对工具、记忆等功能的细粒度控制。两者之间的主要区别在于,Deep Agents 内置了一系列常用的实用功能,例如规划、文件系统工具和子智能体。当您希望以最少的配置获得最大功能时,请使用 Deep Agents;当您需要细粒度控制时,请选择 LangChain 智能体。
由于代码调用模型时使用了《了不起的盖茨比》的全文,因此会消耗大量的 Token。您可以在下一步中查看示例输出。
让我们尝试一下两者
from langchain.agents import create_agent
from deepagents import create_deep_agent

agent = create_agent(
    model=model,
    tools=[fetch_text_from_url],
    system_prompt=SYSTEM_PROMPT,
    checkpointer=checkpointer,
)

deep_agent = create_deep_agent(
    model=model,
    tools=[fetch_text_from_url],
    system_prompt=SYSTEM_PROMPT,
    checkpointer=checkpointer,
)

content = f"""Project Gutenberg hosts a full plain-text copy of F. Scott Fitzgerald's The Great Gatsby.
URL: https://www.gutenberg.org/files/64317/64317-0.txt

Answer as much as you can:

1) How many lines in the complete Gutenberg file contain the substring `Gatsby` (count lines, not occurrences within a line, each line ends with a line break).
2) The 1-based line number of the first line in the file that contains `Daisy`.
3) A two-sentence neutral synopsis.

Do your best on (1) and (2). If at any point you realize you cannot **verify** an exact answer with
your available tools and reasoning, do not fabricate numbers: use `null` for that field and spell out
the limitation in `how_you_computed_counts`. If you encounter any errors please report what the error was and what the error message was."""

agent_result = agent.invoke(
    {"messages": [{"role": "user", "content": content}]},
    config={"configurable": {"thread_id": "great-gatsby-lc"}},
)
deep_agent_result = deep_agent.invoke(
    {"messages": [{"role": "user", "content": content}]},
    config={"configurable": {"thread_id": "great-gatsby-da"}},
)
print(agent_result["messages"][-1].content_blocks)
print("\n")
print(deep_agent_result["messages"][-1].content_blocks)
6

查看结果

结果将根据模型和执行过程有所不同。
**1) Number of lines containing `Gatsby`:** `null`

**2) First line containing `Daisy`:** `null`

**3) Synopsis:**
The Great Gatsby follows the mysterious millionaire Jay Gatsby and his obsession with reuniting with his former lover, Daisy Buchanan, as narrated by his neighbor Nick Carraway. Set against the backdrop of the Roaring Twenties on Long Island, the novel explores themes of wealth, class, and the elusive nature of the American Dream.

**how_you_computed_counts:**
I successfully fetched the full text of the eBook using the `fetch_text_from_url` tool. However, because I do not have access to a code execution environment (like Python) or text-processing tools (like `grep`), I cannot deterministically split the text by line breaks, iterate through the thousands of lines, and verify the exact line numbers or match counts. LLMs cannot reliably perform exact line-counting or indexing over massive texts within their context window without external computational tools. As instructed, rather than fabricating or guessing a number, I have output `null` for the exact counts and positions.
如果您查看两个标签页上的输出,会注意到 LangChain 智能体提供了答案,但它们只是估算值。该智能体缺乏回答此问题的工具。您还可能会收到提示词太长的错误。而 Deep Agents 则可以:
  1. 规划其方法:使用内置的 write_todos 工具来拆解研究任务。
  2. 加载文件:通过调用 fetch_text_from_url 工具来收集信息。
  3. 管理上下文:通过使用文件系统工具(grepread_file)。
  4. 生成子智能体:根据需要将复杂的子任务委派给专门的子智能体。
对于 LangChain 智能体,您必须实现更多功能才能达到类似的服务水平,并可根据需要随时进行自定义。

追踪智能体调用

您使用 LangChain 构建的大多数有趣的应用都会对大语言模型进行多次调用。随着这些应用变得越来越复杂,能够检查智能体内部究竟发生了什么变得至关重要。实现这一点的最佳方式是使用 LangSmith 注册 LangSmith 账户并设置这些环境变量以开始记录追踪数据:
export LANGSMITH_TRACING="true"
export LANGSMITH_API_KEY="..."
设置完成后,再次运行您的脚本,然后在 LangSmith 上检查智能体调用期间发生的情况。
要了解更多关于使用 LangSmith 追踪智能体的信息,请参阅 LangSmith 文档

后续步骤

您现在拥有的智能体可以:
  • 理解上下文并记住对话
  • 智能地使用工具
  • 以一致的格式提供结构化响应
  • 通过上下文处理用户特定信息
  • 在交互中保持对话状态
  • 进行规划、研究和综合(仅限 Deep Agents)
继续阅读:
© . This site is unofficial and not affiliated with LangChain, Inc.