使用DeepSeek Function Calling构建智能测试助手

引言:当AI遇见测试自动化

随着大语言模型(LLM)技术的突破性进展,特别是其中函数调用(Function Calling)能力的出现,软件测试这一传统而关键的软件开发环节,正逐步迎来AI化的变革与挑战。本文将探讨如何有效利用大语言模型的函数调用能力,构建智能化、高效能的测试助手。

function_calling技术解析

什么是function_calling

function_calliing是大语言模型根据用户请求智能选择并调用预定义函数的能力。模型通过理解自然语言指令,自动匹配对应的函数模板并生成结构化参数。

# 传统测试参数定义示例
test_case = {
    "api": "/user/login",
    "method": "POST",
    "params": {"username": "test", "password": "123456"}
}

# 函数调用参数定义示例
tools = [
    {
        "type": "function",
        "function": {
            "name": "execute_api_job",
            "description": "执行接口测试任务",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "任务名称,例如:用户中心测试任务",
                    }
                },
                "required": ["job"]
            },
        }
    }
]

技术优势对比

传统方式函数调用方式
人工维护测试用例自动生成测试逻辑
固定参数组合动态参数生成
单一断言策略智能断言机制
线性执行流程自适应测试路径

实现方式

定义函数

我们需要将我们要通过大模型调用的函数定义好:

tools = [
    {
        "type": "function",
        "function": {
            "name": "execute_api_job",
            "description": "执行接口测试任务",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "任务名称,例如:用户中心测试任务",
                    }
                },
                "required": ["job"]
            },
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_report",
            "description": "查询测试报告",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "任务名称:例如:消息中心测试任务",
                    }
                },
                "required": ["job"]
            },
        }
    },
{
        "type": "function",
        "function": {
            "name": "analysis_report",
            "description": "分析测试报告数据",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "任务名称,例如:订单中心任务",
                    }
                },
                "required": ["job"]
            },
        }
    }
]

实现函数

具体实现内容,根据自己项目来定义,这里提供简单的demo

def execute_api_job(job):
    """模拟执行测试任务"""
    return f"已经开始执行测试任务:{job}"


def get_report(job):
    """模拟获取测试报告"""
    return f"查看{job}的测试报告,请点击https://www.baidu.com"


def analysis_report(job):
    """模拟分析测试数据"""
    # 获取报告数据
    report = get_data(job)
    # 将测试数据发送给AI大模型进行分析
    response = send_messages(f"分析测试任务数据:{report}")
    return f'测试结果分析:\n {response}'

调用大模型

import json
from openai import OpenAI


def send_messages(messages):
    msg = [{"role": "user", "content": messages}]
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=msg,
        tools=tools
    )
    mess = response.choices[0].message
    if mess.tool_calls:
        tool = mess.tool_calls[0]
        function_name = tool.function.name
        arguments = json.loads(tool.function.arguments)

        # 调用函数
        if function_name == 'execute_api_job':
            function_response = execute_api_job(arguments.get("location"))
        elif function_name == 'get_report':
            function_response = get_report(arguments.get("location"))
        elif function_name == 'analysis_report':
            function_response = analysis_report(arguments.get('location'))
        else:
            return response.choices[0].message
        return function_response
    else:
        return response.choices[0].message


client = OpenAI(
    api_key="your_api_key",
    base_url="https://api.deepseek.com",
)

执行

# 测试示例
if __name__ == "__main__":

    while True:
        user_input = input("用户输入:")
        if user_input.lower() == 'exit':
            break
        response = send_messages(user_input)
        print("助手回复:", response)
        print("\n" + "=" * 50 + "\n")

执行结果展示:
在这里插入图片描述

通过DeepSeek的Function Calling能力,我们成功构建了一个能理解自然语言、执行测试任务、智能分析结果的AI测试助手。当然,这只是简单的demo介绍,主要讲述function_calling的使用方法,具体在测试工具中的使用,还是需要结合自身项目。如:测试用例生成、测试数据生成等。

### 使用 DeepSeek 进行函数调用 为了实现基于 DeepSeek 的功能,特别是针对 deepseek 函数调用的操作,通常涉及以下几个方面: #### 安装必要的依赖库 在执行任何操作之前,确保已安装所需的 Python 库。这可以通过 pip 来完成[^1]。 ```bash pip install python-docx pandas requests ``` #### 调用 DeepSeek API 接口 对于 DeepSeek 函数的具体调用方式取决于所使用的编程环境以及 DeepSeek 提供的服务端点。假设有一个 RESTful 风格的 API 可用于交互,则可以采用如下方式进行 POST 请求来发送数据并接收响应: ```python import requests import json def call_deepseek_api(prompt): url = "http://localhost:8000/api/v1/generate" # 替换成实际API地址 headers = { 'Content-Type': 'application/json' } payload = { "prompt": prompt, "max_tokens": 500, "temperature": 0.7 } response = requests.post(url, data=json.dumps(payload), headers=headers) if response.status_code == 200: result = response.json() return result['text'] else: raise Exception(f"Error calling API: {response.text}") ``` 这段代码定义了一个 `call_deepseek_api` 方法,它接受提示字符串作为参数,并向指定 URL 发送 HTTP POST 请求以获取由 DeepSeek 模型生成的结果。注意这里的 URL 和其他配置项应根据实际情况调整。 #### 处理 WPS 中 JavaScript 宏 (JSA) 对 DeepSeek API 的调用 当涉及到从 WPS 办公软件内部通过 JSA 调用外部服务时,可能需要额外考虑跨域请求等问题。具体来说,在 Windows 平台上部署好 DeepSeek 后,可通过 XMLHttpRequest 或 Fetch API 实现异步通信[^2]: ```javascript async function generateWithDeepSeek(promptText){ const endpointUrl = "http://localhost:8000/api/v1/generate"; // 更改为您的服务器URL try{ let res = await fetch(endpointUrl,{ method:'POST', body:JSON.stringify({ prompt:promptText, max_tokens:500, temperature:0.7 }), headers:{ 'Accept':'application/json', 'Content-Type':'application/json' } }); if(!res.ok){ throw new Error('Network response was not ok'); } let jsonResponse = await res.json(); console.log(jsonResponse); return jsonResponse; }catch(error){ console.error('There has been a problem with your fetch operation:', error); } } ``` 上述 JavaScript 片段展示了如何利用现代浏览器支持的方法发起网络请求给本地运行的 DeepSeek 服务实例,并处理返回的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值