LangChain和LangGraph

LangChain和LangGraph 特性 LangChain LangGraph 诞生背景 解决LLM应用开发的零散、重复问题 解决LangChain复杂智能体自定义难、扩展难、生产部署难的问题 核心理念 模块化、可组合的链 “图即工作流”,低抽象、强控制的状态机 核心组件 Components, Chains, LCEL Nodes, Edges, StateGraph, Checkpointer 执行模式 线性串联为主,LLM自主决策为辅 有向图驱动,支持循环、分支与并行处理 生态系统 丰富的社区集成,庞大的工具库 原生LangChain集成,可独立运行 设计目标 快速开发、快速原型 生产可靠、可观测、易扩展 Deep Agents是一个基于LangGraph的代理工具:规划、子代理、文件系统工具和上下文管理。 LangChain是代理框架:模型、工具和代理循环的抽象和集成。 LangGraph是编排运行时:持久执行、流、人在循环和持久性。 LangSmith是用于跨框架跟踪、评估、提示和部署的平台。 Function Calling(函数调用/工具调用) 是大语言模型(LLM)的一项核心能力——它允许模型在生成回复时,不直接输出文本,而是输出一个 结构化的函数调用请求(通常是 JSON),由开发者实际执行该函数,然后将执行结果返回给模型,模型再据此生成最终回复。 注:本文根据吴恩达AI Agent课程学习整理,模型限制未使用chatgpt,用Deekseek替换。 基于react模式的智能代理 代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 import openai import re import httpx import os from dotenv import load_dotenv _ = load_dotenv() from openai import OpenAI # ================= 改动开始 ================= # 使用 DeepSeek 的 API 地址和你的 API Key # 建议在 .env 文件中设置 DEEPSEEK_API_KEY DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY") # 如果没有设置,会读取 OPENAI_API_KEY 兼容 if not DEEPSEEK_API_KEY: raise ValueError("请在环境变量中设置 DEEPSEEK_API_KEY") client = OpenAI( api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com/v1" # DeepSeek 官方 API 地址 ) # ================= 改动结束 ================= # 测试调用(可选) chat_completion = client.chat.completions.create( model="deepseek-chat", # 使用 DeepSeek 模型 messages=[{"role": "user", "content": "Hello world"}] ) print(chat_completion.choices[0].message.content) class Agent: def __init__(self, system=""): self.system = system self.messages = [] if self.system: self.messages.append({"role": "system", "content": system}) def __call__(self, message): self.messages.append({"role": "user", "content": message}) result = self.execute() self.messages.append({"role": "assistant", "content": result}) return result def execute(self): completion = client.chat.completions.create( model="deepseek-chat", # 统一使用 DeepSeek 模型 temperature=0, messages=self.messages ) return completion.choices[0].message.content prompt = """ You run in a loop of Thought, Action, PAUSE, Observation. At the end of the loop you output an Answer Use Thought to describe your thoughts about the question you have been asked. Use Action to run one of the actions available to you - then return PAUSE. Observation will be the result of running those actions. Your available actions are: calculate: e.g. calculate: 4 * 7 / 3 Runs a calculation and returns the number - uses Python so be sure to use floating point syntax if necessary average_dog_weight: e.g. average_dog_weight: Collie returns average weight of a dog when given the breed Example session: Question: How much does a Bulldog weigh? Thought: I should look the dogs weight using average_dog_weight Action: average_dog_weight: Bulldog PAUSE You will be called again with this: Observation: A Bulldog weights 51 lbs You then output: Answer: A bulldog weights 51 lbs """.strip() def calculate(what): return eval(what) def average_dog_weight(name): if name in "Scottish Terrier": return("Scottish Terriers average 20 lbs") elif name in "Border Collie": return("a Border Collies average weight is 37 lbs") elif name in "Toy Poodle": return("a toy poodles average weight is 7 lbs") else: return("An average dog weights 50 lbs") known_actions = { "calculate": calculate, "average_dog_weight": average_dog_weight } abot = Agent(prompt) result = abot("How much does a toy poodle weigh?") print(result) result = average_dog_weight("Toy Poodle") result next_prompt = "Observation: {}".format(result) abot(next_prompt) abot.messages abot = Agent(prompt) question = """I have 2 dogs, a border collie and a scottish terrier. \ What is their combined weight""" abot(question) next_prompt = "Observation: {}".format(average_dog_weight("Border Collie")) print(next_prompt) abot(next_prompt) next_prompt = "Observation: {}".format(average_dog_weight("Scottish Terrier")) print(next_prompt) abot(next_prompt) next_prompt = "Observation: {}".format(eval("37 + 20")) print(next_prompt) next_prompt = "Observation: {}".format(eval("37 + 20")) print(next_prompt) abot(next_prompt) action_re = re.compile('^Action: (\w+): (.*)$') # python regular expression to selection action def query(question, max_turns=5): i = 0 bot = Agent(prompt) next_prompt = question while i < max_turns: i += 1 result = bot(next_prompt) print(result) actions = [ action_re.match(a) for a in result.split('\n') if action_re.match(a) ] if actions: # There is an action to run action, action_input = actions[0].groups() if action not in known_actions: raise Exception("Unknown action: {}: {}".format(action, action_input)) print(" -- running {} {}".format(action, action_input)) observation = known_actions[action](action_input) print("Observation:", observation) next_prompt = "Observation: {}".format(observation) else: return question = """I have 2 dogs, a border collie and a scottish terrier. \ What is their combined weight""" query(question) 这段代码实现了一个基于大语言模型的 ReAct 风格智能代理,能够通过“思考-行动-观察”循环来解决需要多步推理或工具调用的问题。它使用了 DeepSeek 模型(兼容 OpenAI API),并内置了两个简单工具:数学计算和查询狗的平均体重。 ...

July 1, 2026 · 21 min · 4447 words · Taigong