国产最强 DeepSeek-V3.2 Agent 开发实战系列(一)

DeepSeek-V3.2 Agent 开发入门

本篇将依次从 DeepSeek-V3.2 模型简介、快速上手使用方法以及与 LangChain 集成三个方面展开介绍,并包含可运行示例供大家学习实验。

一、DeepSeek-V3.2 模型简介

DeepSeek-V3.2 作为目前 国内最强模型,通过引入可拓展的 GRPO 训练框架搭配大规模合成 Agent 任务数据集,借助海量强化学习后训练,让模型一举突破性能极限。在数学、编程、Agent 性能方面全面领先,整体追平全球性能最强大模型 Gemini 3.0 Pro。

image-20251203190049436

DeepSeek-V3.2 模型价格也是非常香:

image-20251203190122421

DeepSeek-V3.2 模型的 API 已全面上线,模型权重也已全面开源。

  • 模型权重:https://huggingface.co/deepseek-ai/DeepSeek-V3.2
image-20251203190201357
  • 模型详解视频地址:https://www.bilibili.com/video/BV13rSHBBEoG/

  • LangChain 1.0 快速入门指南:https://www.bilibili.com/video/BV1uV1yBHE2o/

二、DeepSeek V3.2 快速上手使用

加入👉赋范空间 免费领取 完整项目代码及示例,还有更多Agent 开发实战内容等你来拿

1. 基础配置

首先注册 DeepSeek 账号并获取 API Key( https://platform.deepseek.com/usage )。

在项目根目录创建 .env 文件存储 API Key:

image-20251203191005554
2. 基础调用示例

加入👉赋范空间 免费领取 完整项目代码及示例,还有更多Agent 开发实战内容等你来拿

"""
DeepSeek API 基础调用示例
该脚本展示了如何配置环境并调用 DeepSeek 对话接口。
"""
import os
from dotenv import load_dotenv
from openai import OpenAI

# 加载环境变量
load_dotenv(override=True)
DeepSeek_API_KEY = os.getenv("DEEPSEEK_API_KEY")

def basic_chat_demo():
    """
    演示基础对话功能
    """
    # 初始化 DeepSeek 的 API 客户端
    # 参数注释:
    # api_key: 从环境变量获取的 DeepSeek API 密钥
    # base_url: DeepSeek 官方 API 地址
    client = OpenAI(api_key=DeepSeek_API_KEY, base_url="https://api.deepseek.com")

    # 调用 DeepSeek 的 API,生成回答
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "你是乐于助人的助手,请根据用户的问题给出回答"},
            {"role": "user", "content": "你好,请你介绍一下你自己。"},
        ],
    )

    # 打印模型最终的响应结果
    print(response.choices[0].message.content)

if __name__ == "__main__":
    basic_chat_demo()

三、DeepSeek-V3.2 Function Calling 调用流程

Function Calling 是大模型调用外部工具的关键技术。

image-20250318202029130
202412191720637
1. 定义外部函数与工具描述
import json
import requests
import os

def get_weather(loc):
    """
    查询即时天气函数
    
    :param loc: 必要参数,字符串类型,用于表示查询天气的具体城市名称。
                注意:中国的城市需要用对应城市的英文名称代替,例如查询北京市天气,loc 输入 'Beijing'。
    :return: OpenWeather API 查询即时天气的结果(JSON 字符串)。
    :raises Exception: 当网络请求失败或 API Key 错误时可能抛出异常。
    """
    api_key = os.getenv("OPENWEATHER_API_KEY") # 请确保已设置此环境变量
    url = "https://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": loc,               
        "appid": api_key,
        "units": "metric",            # 使用摄氏度
        "lang": "zh_cn"               # 输出语言为简体中文
    }
    response = requests.get(url, params=params)
    return json.dumps(response.json())

# 定义工具描述,供模型理解
tools = [
    {
        "type": "function",
        "function": {
            'name': 'get_weather',
            'description': '查询即时天气函数,根据输入的城市名称,查询对应城市的实时天气',
            'parameters': {
                'type': 'object',
                'properties': {
                    'loc': {
                        'description': "城市名称(英文),如 'Beijing'",
                        'type': 'string'
                    }
                },
                'required': ['loc']
            }
        }
    }
]
2. 执行 Function Calling 完整流程

以下代码展示了如何处理模型返回的工具调用请求,执行函数,并生成最终回答。

def run_function_calling_demo():
    """
    演示 DeepSeek Function Calling 完整流程
    """
    client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
    
    messages = [{"role": "user", "content": "请问北京今天天气如何?"}]
    
    # 第一次调用:模型判断是否需要调用工具
    response = client.chat.completions.create(
        model="deepseek-reasoner",  # 使用 reasoner 模型体验思考过程
        messages=messages,
        tools=tools,
    )
    
    # 获取工具调用信息
    tool_calls = response.choices[0].message.tool_calls
    
    if tool_calls:
        # 将模型的响应(包含工具调用意图)加入历史消息
        messages.append(response.choices[0].message.model_dump())
        
        # 遍历所有工具调用请求
        available_functions = {"get_weather": get_weather}
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_args = json.loads(tool_call.function.arguments)
            
            # 执行函数
            function_to_call = available_functions[function_name]
            function_response = function_to_call(**function_args)
            
            # 将函数执行结果加入历史消息
            messages.append({
                "role": "tool",
                "content": function_response,
                "tool_call_id": tool_call.id,
            })
            
        # 第二次调用:模型根据函数执行结果生成最终回答
        final_response = client.chat.completions.create(
            model="deepseek-reasoner",
            messages=messages,
            tools=tools,
        )
        
        print("最终回答:", final_response.choices[0].message.content)
        if hasattr(final_response.choices[0].message, 'reasoning_content'):
            print("思考过程:", final_response.choices[0].message.reasoning_content)

if __name__ == "__main__":
    run_function_calling_demo()
image-20251202151950194

四、LangChain 集成与 DeepSeek Reasoner 兼容性解决方案

这里就不过多展开讲解LangChain集成了,详情可以参考 LangChain1.0实战教学 只需将其中模型API替换即可。

这里主要讲解目前 LangChain 1.1 版本与 DeepSeek-V3.2 Reasoner 推理模型的兼容性解决方案。

LangChain 提供了便捷的 Agent 开发接口,但 LangChain 1.1 目前与 DeepSeek-V3.2 Reasoner 模型的兼容性存在一定问题(主要在于推理内容的流式处理和工具调用的解析)。

image-20251028154837987
image-20251028171815049
自定义 DeepSeekReasonerChatModel

通过继承 BaseChatModel 创建自定义的 DeepSeekReasonerChatModel,实现:

  1. 与 LangChain 1.0 的 create_agent 完全兼容
  2. 正确处理 reasoning_content 字段
  3. 支持完整的工具调用流程
  4. 可以查看模型的推理过程
image-20251202163004568
  • 创建核心类:DeepSeekReasonerChatModel
from typing import Optional, List, Dict, Any
from langchain_core.language_models.chat_models import BaseChatModel

class DeepSeekReasonerChatModel(BaseChatModel):
    """
    自定义 DeepSeek Reasoner 模型

    关键特性:
    1. 保留 reasoning_content 在 additional_kwargs 中
    2. 消息转换时恢复 reasoning_content
    3. 完整支持工具绑定和调用
    """

    api_key: str
    base_url: str = "https://api.deepseek.com"
    model_name: str = "deepseek-reasoner"
    temperature: float = 0.7
    bound_tools: Optional[List[Dict]] = None
  • 创建关键方法:_convert_messages_to_openai_format
def _convert_messages_to_openai_format(self, messages):
    """LangChain 消息 → OpenAI 格式"""
    openai_messages = []

    for msg in messages:
        if isinstance(msg, AIMessage):
            msg_dict = {
                "role": "assistant",
                "content": msg.content or "",
            }

            # 添加 tool_calls
            if msg.tool_calls:
                msg_dict["tool_calls"] = [...]

            # 【关键】恢复 reasoning_content
            if 'reasoning_content' in msg.additional_kwargs:
                msg_dict["reasoning_content"] = msg.additional_kwargs['reasoning_content']

            openai_messages.append(msg_dict)

    return openai_messages
  • 优化响应处理:_create_ai_message_from_response
def _create_ai_message_from_response(self, response):
    """OpenAI 响应 → LangChain AIMessage"""
    message = response.choices[0].message

    # 处理 tool_calls
    tool_calls = [...]

    # 【关键】保存 reasoning_content 到 additional_kwargs
    additional_kwargs = {}
    if hasattr(message, 'reasoning_content'):
        additional_kwargs['reasoning_content'] = message.reasoning_content

    return AIMessage(
        content=message.content or "",
        tool_calls=tool_calls if tool_calls else None,  # 不能是 None
        additional_kwargs=additional_kwargs
    )
  • 进行工具绑定:bind_tools
from langchain_core.tools import BaseTool
def bind_tools(self, tools: List[BaseTool], **kwargs):
    """绑定 LangChain 工具"""
    # 转换为 OpenAI 格式
    openai_tools = []
    for tool in tools:
        openai_tools.append({
            "type": "function",
            "function": {
                "name": tool.name,
                "description": tool.description,
                "parameters": tool.args_schema.model_json_schema()
            }
        })

    # 返回新实例
    return self.__class__(
        api_key=self.api_key,
        base_url=self.base_url,
        model_name=self.model_name,
        temperature=self.temperature,
        bound_tools=openai_tools,  # 保存绑定的工具
        **kwargs
    )
  • 优化生成响应格式:_generate
def _generate(self, messages, stop=None, run_manager=None, **kwargs):
    """核心生成方法"""
    # 转换消息
    openai_messages = self._convert_messages_to_openai_format(messages)

    # 准备请求
    request_params = {
        "model": self.model_name,
        "messages": openai_messages,
        "temperature": self.temperature,
    }

    # 添加工具
    if self.bound_tools:
        request_params["tools"] = self.bound_tools

    # 调用 API
    response = self._client.chat.completions.create(**request_params)

    # 创建响应
    ai_message = self._create_ai_message_from_response(response)

    return ChatResult(generations=[ChatGeneration(message=ai_message)])
  • 创建自定义模型
import os
from dotenv import load_dotenv
from langchain_core.tools import tool
from langchain.agents import create_agent

load_dotenv()
# 导入自定义模型
from deepseek_reasoner_chat_model import DeepSeekReasonerChatModel
# 创建自定义模型
model = DeepSeekReasonerChatModel(
    api_key=os.environ.get("DEEPSEEK_API_KEY"),
    model_name="deepseek-reasoner",
    temperature=0.7
)
tools = [get_weather, write_file]
agent = create_agent(
    model=model,
    tools=tools,
    system_prompt="你是一个有用的助手,可以使用工具来回答问题。"
)
result = agent.invoke(
    {"messages": [{"role": "user", "content": "请帮我查询北京天气信息。"}]}
)
result['messages'][-1].content

五、结语

本篇我们从 0 到 1 走完了 DeepSeek-V3.2 Agent 开发的基础路径:先整体认识模型能力与价格优势,再完成 API Key 配置与基础调用示例,接着通过 Function Calling 打通「模型 ↔ 外部工具」的完整闭环,最后给出了一套 LangChain 对推理模型 的兼容性解决方案。

欢迎加入👉赋范空间 免费领取 完整项目教程及源码,还有更多Agent 开发实战内容等你来拿

MATLAB代码实现了个基于多种智能优化算法优化RBF神经网络的回归预测模型,其核心是通过智能优化算法自动寻找最优的RBF扩展参数(spread),以提升预测精度。 1.主要功能 多算法优化RBF网络:使用多种智能优化算法优化RBF神经网络的核心参数spread。 回归预测:对输入特征进行回归预测,适用于连续值输出问题。 性能对比:对比不同优化算法在训练集和测试集上的预测性能,绘制适应度曲线、预测对比图、误差指标柱状图等。 2.算法步骤 数据准备:导入数据,随机打乱,划分训练集和测试集(默认7:3)。 数据归化:使用mapminmax将输入和输出归化到[0,1]区间。 标准RBF建模:使用固定spread=100建立基准RBF模型。 智能优化循环: 调用优化算法(从指定文件夹中读取算法文件)优化spread参数。 使用优化后的spread重新训练RBF网络。 评估预测结果,保存性能指标。 结果可视化: 绘制适应度曲线、训练集/测试集预测对比图。 绘制误差指标(MAE、RMSE、MAPE、MBE)柱状图。 十种智能优化算法分别是: GWO:灰狼算法 HBA:蜜獾算法 IAO:改进天鹰优化算法,改进①:Tent混沌映射种群初始化,改进②:自适应权重 MFO:飞蛾扑火算法 MPA:海洋捕食者算法 NGO:北方苍鹰算法 OOA:鱼鹰优化算法 RTH:红尾鹰算法 WOA:鲸鱼算法 ZOA:斑马算法
### 使用 DeepSeek-R1 作为 Agent 的配置与操作 #### 配置环境 为了使 DeepSeek-R1 能够作为个有效的代理(agent),首先需要确保其运行环境已经按照指定的方式进行了设置。由于 DeepSeek-R1 是基于 DeepSeek-V3-Base 训练而来,因此 R1 的部署流程可参照 V3 版本的相关指南[^1]。 对于本地环境中启动 DeepSeek-R1 模型而言,可以通过特定命令来实现模型的快速调用和执行。具体来说,当希望再次激活本地已有的 DeepSeek 实例时,应当利用如下指令完成这过程:`ollama run deepseek-r1:1.5b`[^2]。 #### 编写交互逻辑 为了让 DeepSeek-R1 成功扮演代理角色并处理来自用户的请求或任务,编写合理的交互逻辑至关重要。这通常涉及到定义输入输出格式、设定对话管理机制以及集成必要的业务功能模块等方面的工作。下面是个简单的 Python 函数示例,用于展示如何向 DeepSeek-R1 发送查询并获取响应: ```python import requests def query_deepseek_r1(prompt): url = "http://localhost:8000/api/v1/query" headers = {"Content-Type": "application/json"} data = { 'model': 'deepseek-r1', 'prompt': prompt, 'max_tokens': 150 } response = requests.post(url, json=data, headers=headers) result = response.json() return result['choices'][0]['text'] ``` 此函数接受个字符串类型的 `prompt` 参数作为用户提问的内容,并将其发送给位于 localhost 上监听端口 8000 的 API 接口;随后解析返回的数据结构以提取最终的回答文本。 #### 测试与验证 最后,在完成了上述准备工作之后,应该进行全面的功能测试以确认整个系统的稳定性和准确性。可以尝试构建些实际场景下的案例来进行模拟演练,观察 DeepSeek-R1 是否能够正确理解意图并给出恰当回应。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值