9 月 20 日学习报告:LangChain Agent 的 Tool、Memory 与 Streaming

9 月 20 日学习报告:LangChain Agent 的 Tool、Memory 与 Streaming 仅整理 2026-09-20 修改的 4 个文件。文件按最后修改时间排列;各文件内部保持原文标题顺序与层级,只压缩重复表述和示例,不省略知识点。 ...

FrameworksLangChain
14 分钟6680 字chenghaoning51

Event Streaming

LangChain agents are built on LangGraph, so they support the same streaming stack with agent-focused projections for messages, tool calls, state, and custom updates. For most situation,use Event Streaming throughstream_event(...,version="v3") Event Streaming returns a run object with typed projections, so each projection can be consumed independently instead of parsing stream-mode tuples 1 2 3 4 5 6 7 8 9 stream = agent.stream_events({ "messages": [{"role": "user", "content": "What is the weather in SF?"}], }, version="v3") for message in stream.messages: for delta in message.text: print(delta, end="", flush=True) final_state = stream.output What you can stream Projection Use for event in stream Raw protocol events with full envelope and access to every channel. stream.messages Model message streams, one per LLM call. message.text Text deltas and final text for a message. message.reasoning Reasoning deltas for models that expose reasoning content. message.tool_calls Tool-call argument chunks and finalized tool calls. message.output Final message object after the model call completes. stream.values Agent state snapshots. stream.output Final agent state. stream.subgraphs Nested graph runs (sub-agents and plain subgraphs). stream.extensions Custom transformer projections. stream.tool_calls Tool execution lifecycle, inputs, output deltas, final output, and errors. stream.messages 会生成 ChatModelStream 对象。每个消息流都暴露了 .text、.reasoning、.tool_calls 和 .output。同步投影可迭代以获取实时增量,也可排空以获取最终值:使用 str(message.text) 获取最终文本,使用 message.tool_calls.get() 获取已完成的工具调用 ...

FrameworksLangChain
4 分钟1674 字chenghaoning51

LangChain A Quick Start

一个简单的示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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="claude-sonnet-4-6", 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) Build a real-world agent: Detailed System Prompt Create Tools Model Configuration Conversational memory Deep agents Testing 1.Define the system prompt defines your agent’s role and behavior. Keep it specific and actionable. ...

FrameworksLangChain
1 分钟449 字chenghaoning51

LangChain Philosophy

LangChain is driven by a few core beliefs: Large Language Models (LLMs) are great, powerful new technology. LLMs are even better when you combine them with external sources of data. LLMs will transform what the applications of the future look like. Specifically, the applications of the future will look more and more agentic. It is still very early on in that transformation. While it’s easy to build a prototype of those agentic applications, it’s still really hard to build agents that are reliable enough to put into production.

FrameworksLangChain
1 分钟94 字chenghaoning51

Message

Message Carrying both the content and metadata which represent the state Messages contain: Role: identifies the message type(system,user) Content: the actual content Metadata: optional fields: such as information,message IDs,and token usage This is the standard message type Basic usage The easiest way to use message is to create message objects and pass them to a model when invoking Text prompts String Ideal for generation tasks where you don’t need to retain. ...

FrameworksLangChain
2 分钟886 字chenghaoning51

Models

In addition to text generation,many LLMs provide :tool calling,Structured output,Multimodality,Reasoning different model excel at different tasks LangChain has Standard model interface,which allow you to experiment with and switch models Basic usage 1.with agents 2.Standalone(outside the agent loop) Initialize a model the easiest way: use init_chat_model 1 2 3 4 5 6 import os from langchain.chat_models import init_chat_model os.environ["OPENAI_API_KEY"] = "sk-..." model = init_chat_model("gpt-5.5") key method: invoke,streaming.patch(批量处理) ...

FrameworksLangChain
4 分钟1543 字chenghaoning51

Short-term Memory

Conversation history is the most common form of short-term memory Fact1: message includes instructions and inpus Usage To add short-term memory to an agent ,you need to specify a checkpointer when creating an agent note: short-term memory is part of your agent’s state. State is persisted in a database using a checkpointer so thread can resume it an any time. Short-term memory updates when the agent is invoked or a step (like a tool call) is completed, and the state is read at the start of each step. ...

FrameworksLangChain
3 分钟1481 字chenghaoning51

Streaming

Overview 实现的功能: Stream agent progress Stream LLM tokens Streaming thinking/reasoning tokens Stream custom updates Stream multiple modes:从updates,messages,custom中进行选择 Supported stream modes 将下列的一个或者多个流式传输模式作为列表传输给stream或者astream方法 ...

FrameworksLangChain
5 分钟2472 字chenghaoning51

Structured Output

返回的形式: JSON objects, Pydantic models,or dataclasses that your application can use directly LangChain’s create_agent 会自动处理结构化输出 用户设置desired 结构化输出的schema 返回在 in the key strucured_responese key of the agent’s state Field函数的作用: 结构化输出时,是创建元数据的重要途径,且其内部的description可以作为Prompt的一部分指导LLM的工作 ...

FrameworksLangChain
4 分钟1930 字chenghaoning51

Tools

Tools Extend what agents can do! Create tools Basic tool definition The easiest way to create a tool is to use the @tool decorator In this way the docstring will become the description of the tool 1 2 3 4 5 6 7 8 9 10 11 from langchain.tools import tool @tool def search_database(query: str, limit: int = 10) -> str: """Search the customer database for records matching the query. Args: query: Search terms to look for limit: Maximum number of results to return """ return f"Found {limit} results for '{query}'" docstring:’’' ada ’’' 的部分 docstring应该内容丰富且简明扼要 参数的type hints是必须的,因为他们定义了工具的输入参数 ...

FrameworksLangChain
8 分钟3539 字chenghaoning51