惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Cloudflare Blog
A
About on SuperTechFans
腾讯CDC
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Google Online Security Blog
Google Online Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
小众软件
小众软件
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Heimdal Security Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Security @ Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Jina AI
Jina AI
爱范儿
爱范儿
D
DataBreaches.Net
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Proofpoint News Feed
P
Privacy International News Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Palo Alto Networks Blog
S
SegmentFault 最新的问题
U
Unit 42
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
美团技术团队
T
Tenable Blog
V
V2EX
M
MIT News - Artificial intelligence
Recorded Future
Recorded Future
A
Arctic Wolf
Hacker News - Newest:
Hacker News - Newest: "LLM"
Last Week in AI
Last Week in AI
P
Proofpoint News Feed
Stack Overflow Blog
Stack Overflow Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
GRAHAM CLULEY
P
Privacy & Cybersecurity Law Blog
Martin Fowler
Martin Fowler
人人都是产品经理
人人都是产品经理
Google DeepMind News
Google DeepMind News
L
LINUX DO - 热门话题
博客园 - 【当耐特】
博客园 - 叶小钗
S
Securelist
T
Tor Project blog
Forbes - Security
Forbes - Security
O
OpenAI News
IT之家
IT之家
博客园 - Franky

博客园 - VipSoft

Python 项目简单部署(Linux) MinerU - 将非结构化文档(PDF、图片、Office 文件等)转换为机器可读的 Markdown 和 JSON LangChain 入门 服务端部署-FastAPI LangChain 入门 LangSmith LangChain 入门 实战 - 食谱推荐 LangChain 入门 Memory 会话记忆 LangChain 入门 Tools 工具 LangChain 入门 Tools 工具 LangChain 入门 Prompts 提示词 LangChain 入门 Message 消息 LangChain 入门 Model 的初始化和调用 AI 0基础学习,名词解析 LangChain 和 LangGraph AI大模型知识体系 Dify — Workflow - 数据可视化 Dify — 连接MySQL配置 Dify — Chatflow - 数据库智能查询 Dify — Chatflow - 文档知识库 Dify — Agent 智能体 高安全券码、注册码生成 Dify — 文本生成应用 Dify — 聊天助手 -- 知识库 Windows 下 Docker 安装 Dify Ollama — 命令 Ollama — 为什么能够运行不同的模型 Ollama — 接口 Qwen — 自定义模型文件 Ollama Qwen — 安装测试 Ollama Windows 安装 & 指定安装目录 跟着AI学AI - 诊断结论信息抽取 - 批量处理脚本 跟着AI学AI - 诊断结论信息抽取 - 模型压缩与部署 跟着AI学AI - 诊断结论信息抽取 - 模型评估与调试 跟着AI学AI - 诊断结论信息抽取 - 模型训练 轻型民用无人驾驶航空器安全操控理论考试培训材料 FreeRedis Helper Windbg w3wp.DMP 内存分析 跟着AI学AI - 诊断结论信息抽取 - 数据增强 QQ 录屏软件 Java - 加权随机算法 - 示例 Java - 加权随机算法--Demo Java LoadBalanceUtil 负载均衡、轮询加权 SpringBoot 集成 IP2Region 获取IP地域信息 Windows 服务器和虚拟主机,创建.开头的文件夹 .well-known 跟着AI学AI - 诊断结论信息抽取 - 数据格式转换BERT训练格式 跟着AI学AI - 诊断结论信息抽取 - LabelStudio 标注 -- 结论标注 跟着AI学AI - 诊断结论信息抽取 - 学习路径 跟着AI学AI - UV 安装 数据标注工具 Label-Studio `VIRTUAL_ENV=venv` does not match the project environment 跟着AI学AI - 学习路径 - 命名实体识别(NER)和信息抽取(IE) 跟着AI学AI - 需要购买显卡吗? C# 无BOM的UTF-8编码 Vue ref reactive Vue - el-table 嵌套表 Spring `@Scheduled` 中这些参数的区别、组合和应用场景 Python 找出同步日志中的重复数据 Python - UV PyCharm 不能识别 .venv 的环境
LangChain 入门 Agent 的基本运行机制
VipSoft · 2026-06-03 · via 博客园 - VipSoft

Python - UV 为每个项目创建独立、干净的Python工作空间
UV 中文文档:https://uv.doczh.com/

安装依赖

cd D:\OpenSource\Python\VipLangChain

# 初始化 uv 项目(可选)
uv init

# 1. 创建虚拟环境
uv venv

# 2. 激活虚拟环境(Windows)
.venv\Scripts\activate

# 3. 安装环境变量
uv add python-dotenv --default-index https://pypi.tuna.tsinghua.edu.cn/simple

# LangChain 支持各种不同的模型,而且提供了对应的兼容SDK,不过也都需要安装对应依赖,
# 4. 安装 LangChain 依赖
# -v 可以显示 debug 日志
uv add langchain -v --default-index https://pypi.tuna.tsinghua.edu.cn/simple

# 5. 集成 DeepSeek
# 前面加了 --default-index 后面执行可以不用加了,因为它会在 pyproject.toml 中记录了
uv add langchain-deepseek --default-index https://pypi.tuna.tsinghua.edu.cn/simple

# 如果需要集成 OpenAI
uv add langchain-openai --default-index https://pypi.tuna.tsinghua.edu.cn/simple

# 如果需要集成 Anthropic
uv add langchain-anthropic --default-index https://pypi.tuna.tsinghua.edu.cn/simple

为了测试环境,创建一个 notebook (jupyter)

uv add notebook

pyproject.toml

[project]
name = "vip-langchain"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
    "langchain>=1.3.4",
    "langchain-deepseek>=1.0.1",
    "notebook>=7.5.6",
    "python-dotenv>=1.2.2",
]

[[tool.uv.index]]
url = "https://pypi.tuna.tsinghua.edu.cn/simple"
default = true

print("Hello LangChain")

Hello LangChain

添加环境变量

创建 .env 文件

DEEPSEEK_API_KEY=sk-7c0asdffasd.........

加载环境变量

# 1. 加载环境变更
from dotenv import load_dotenv

load_dotenv()

定义工具

Agent 的核心能力之一是 Tool Calling(工具调用) 。

# 2. 定义工具
from langchain.tools import tool

# 定义一个工具,其实就是定义一个方法通过 @tool 进行修饰
@tool
def getWeather(city: str) -> str:
    """通过调用第三方接口,将天气进行返回"""
    print(f"正在查询{city}天气...")
    return f"{city}今天是晴天,气温25度"

创建 Agent

LangChain 入门 Model 的初始化和调用

接下来创建一个 Agent,并指定使用 deepseek 模型。
LangChain 会自动加载.env 文件中的 DEEPSEEK_API_KEY ,并根据指定的模型,去访问对应的接口地睛,无需要指定接口地址
模型不能调工具,但它可以返回的内容里包含想要调的工具名 tool_calls,这时候 LangChain 会自动去调工具

# 3. 创建 Agent
from langchain.agents import create_agent

agent = create_agent(
    # 前面加上 "openai:qwen-plus" 前缀,指定模型
    "deepseek-chat",
    tools=[getWeather]
)

发起调用

LangChain 会自动调用 get_weather 方法,并返回结果。

# 调用 Agent
print("正在调用大模型...")
response = agent.invoke({
    "messages": [
        {"role": "user", "content": "苏州今天的天气如何?"}
    ]
})
print(response)

# 格式化打印
for message in response["messages"]:
    print(message.model_dump_json(indent=2))

完成代码如下

from langchain.agents import create_agent
from langchain.tools import tool
from  dotenv import load_dotenv

load_dotenv()

@tool
def getWeather(city: str) -> str:
    """通过调用第三方接口,将天气进行返回"""
    print(f"正在查询{city}天气...")
    return f"{city}今天是晴天,气温25度"

# 创建 agent
agent = create_agent(
    model="deepseek-chat",  # 不需要加前缀 如:"ollama:qwen3.5:4b"
    tools=[getWeather],  #定义回调的工具(函数)
    system_prompt="You are a helpful assistant"
)

# 注意不要写成 message,也不报错,就是不返回你想要的结果,问AI,还一本正经的胡说八道,给我越改越复杂
response = agent.invoke({
    "messages": [
        {"role": "user", "content": "苏州今天的天气如何?"}
    ]
})

for message in response["messages"]:
    print(message.model_dump_json(indent=2))

invoke 的调用记录

正在调用大模型...
正在查询苏州天气...
# 请求模型
{
  "content": "苏州今天的天气如何?",
  "additional_kwargs": {},
  "response_metadata": {},
  "type": "human",
  "name": null,
  "id": "f011a5ea-85d4-435e-b09b-fdac67409924"
}
# 模型返回内容
{
  "content": "好的,我来帮您查询苏州今天的天气情况。",
  "additional_kwargs": {
    "refusal": null
  },
  "response_metadata": {
    "token_usage": {
      "completion_tokens": 54,
      "prompt_tokens": 286,
      "total_tokens": 340,
      "completion_tokens_details": null,
      "prompt_tokens_details": {
        "audio_tokens": null,
        "cached_tokens": 256
      },
      "prompt_cache_hit_tokens": 256,
      "prompt_cache_miss_tokens": 30
    },
    "model_provider": "deepseek",
    "model_name": "deepseek-v4-flash",
    "system_fingerprint": "fp_8b330d02d0_prod0820_fp8_kvcache_20260402",
    "id": "e093d135-db43-4207-ab51-8ec767899395",
    "finish_reason": "tool_calls",
    "logprobs": null
  },
  "type": "ai",
  "name": null,
  "id": "lc_run--019e901c-4b44-78d0-a6fa-344e52bcf90b-0",
  "tool_calls": [
    {
      "name": "getWeather",  # 模型不会调工具,但他会告诉你,接下来需要调什么工具(工具就是函数)
      "args": {
        "city": "苏州"
      },
      "id": "call_00_BYkQIEyR1XEU7Q02dJTK9591",
      "type": "tool_call"
    }
  ],
  "invalid_tool_calls": [],
  "usage_metadata": {
    "input_tokens": 286,
    "output_tokens": 54,
    "total_tokens": 340,
    "input_token_details": {
      "cache_read": 256
    },
    "output_token_details": {}
  }
}
# 工具的结果,发给模型分析
{
  "content": "苏州今天是晴天,气温25度",
  "additional_kwargs": {},
  "response_metadata": {},
  "type": "tool",
  "name": "getWeather",
  "id": "1b3937e0-b767-47f0-9a26-a513357d2598",
  "tool_call_id": "call_00_BYkQIEyR1XEU7Q02dJTK9591",
  "artifact": null,
  "status": "success"
}

# 最终模型反出结果
{
  "content": "苏州今天天气不错,具体情况如下:\n\n🌤 **苏州今日天气**\n- **天气状况**:晴天\n- **气温**:25℃\n\n是个适合出门的好天气!如果需要了解更多信息,随时可以问我哦~",
  "additional_kwargs": {
    "refusal": null
  },
  "response_metadata": {
    "token_usage": {
      "completion_tokens": 46,
      "prompt_tokens": 358,
      "total_tokens": 404,
      "completion_tokens_details": null,
      "prompt_tokens_details": {
        "audio_tokens": null,
        "cached_tokens": 256
      },
      "prompt_cache_hit_tokens": 256,
      "prompt_cache_miss_tokens": 102
    },
    "model_provider": "deepseek",
    "model_name": "deepseek-v4-flash",
    "system_fingerprint": "fp_8b330d02d0_prod0820_fp8_kvcache_20260402",
    "id": "e7239d5d-f12a-4894-830e-0c4e2cf79f83",
    "finish_reason": "stop",
    "logprobs": null
  },
  "type": "ai",
  "name": null,
  "id": "lc_run--019e901c-5024-7e63-a841-a8da6e7bc375-0",
  "tool_calls": [],
  "invalid_tool_calls": [],
  "usage_metadata": {
    "input_tokens": 358,
    "output_tokens": 46,
    "total_tokens": 404,
    "input_token_details": {
      "cache_read": 256
    },
    "output_token_details": {}
  }
}

此时 Agent 会:

  • 解析用户问题
  • 判断是否需要调用工具
  • 自动调用 get_weather
  • 返回最终答案

image
image

如果跑不起来,看下 PyCharm 的运行环境是否正确
image