人工智能-function calling(函数调用)

文章目录

function calling(函数调用)是至关重要的一项能力。

示例

先设置环境变量MODELSCOPE_API_KEY,值为魔搭社区的token。

代码:

python 复制代码
import requests
import json
import os
import re

# ====================== 核心配置 ======================
API_KEY = os.getenv("MODELSCOPE_API_KEY", "YOUR_MODELSCOPE_TOKEN_HERE")
URL = "https://api-inference.modelscope.cn/v1/chat/completions"
MODEL_NAME = "Qwen/Qwen3.5-35B-A3B"

# ====================== 函数定义 ======================
functions = [
    {
        "name": "get_weather",
        "description": "查询指定城市的实时天气信息",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名称,如北京、上海"},
                "date": {"type": "string", "description": "日期,格式YYYY-MM-DD"}
            },
            "required": ["city"]
        }
    }
]

# ====================== 真实函数 ======================
def get_weather(city: str, date: str = "2026-03-23") -> str:
    weather = {
        "北京": "多云转晴 5~19℃,轻度污染",
        "上海": "小雨 10~15℃",
        "广州": "晴 18~28℃"
    }
    return f"{date} {city}天气:{weather.get(city, '暂无数据')}"

# ====================== 调用模型 ======================
def run(question):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    data = {
        "model": MODEL_NAME,
        "messages": [{"role": "user", "content": question}],
        "functions": functions,
        "function_call": "auto",
        "temperature": 0.0
    }

    resp = requests.post(URL, headers=headers, json=data, timeout=60)
    resp_data = resp.json()

    print("📌 模型返回:")
    print(json.dumps(resp_data, ensure_ascii=False, indent=2))

    # 读取 reasoning_content(Qwen3.5 把调用决策写在这里)
    message = resp_data["choices"][0]["message"]
    reasoning = message.get("reasoning_content", "")
    content = message.get("content", "")

    print("\n🧠 模型思考内容:", reasoning)

    # ====================== 关键:从自然语言 reasoning 里提取函数调用 ======================
    func_name = None
    city = None
    date = None

    if "get_weather" in reasoning:
        func_name = "get_weather"

        # 正则提取 city
        city_match = re.search(r'city[="\s]+([^"\s]+)', reasoning)
        if city_match:
            city = city_match.group(1).strip('"')

        # 正则提取 date
        date_match = re.search(r'\d{4}-\d{1,2}-\d{1,2}', reasoning)
        if date_match:
            date = date_match.group(0)

    # 如果识别到要调用天气函数
    if func_name == "get_weather" and city:
        print(f"\n✅ 成功识别函数调用:get_weather(city={city}, date={date})")
        result = get_weather(city=city, date=date or "2026-03-23")
        print("🌤 天气结果:", result)
        return

    # 否则直接输出回答
    print("\n💬 模型直接回答:", content)

# ====================== 测试 ======================
if __name__ == "__main__":
    print("===== 测试1:天气查询 =====")
    run("北京2026-03-23的天气怎么样")

    print("\n===== 测试2:纯聊天 =====")
    run("介绍一下Qwen3.5-35B-A3B")
示例-流程解读

1、用户提问 "北京的天气怎么样?"

2、代码调魔搭Qwen(传functions)

3、模型思考并写调用意图到reasoning

4、代码解析思考内容(可以用文本匹配来做,例如是否包含get_weather函数、包含必填参数city等)

5、执行本地函数

6、返回结果

相关推荐
码农胖大海17 分钟前
AI 响应慢自查清单
agent·ai编程
梓䈑29 分钟前
【用 Vibe Coding 实现的 C++17 在线判题系统】前端开发 + Web 自动化测试
前端·c++·ai编程
BullSmall1 小时前
Another Redis Desktop Manager(ARDM)下载指南
数据库·redis·缓存
SelectDB1 小时前
Apache Doris 倒排索引工作原理:全文检索提速 59 倍,点查提速 14 倍
数据库
码农颜1 小时前
5.1.1 原⼦性
数据库·mysql
机建狂魔1 小时前
Codex 接入第三方模型 API 实战:以 Mimo 为例
java·服务器·数据库·ai·ai编程·codex
山峰哥2 小时前
数据库工程与SQL调优:从慢查询到秒级响应的实战之路
java·开发语言·数据库·sql·深度优先·启发式算法
moMo2 小时前
# 向量数据库入门:从"关键词匹配"到"语义理解"
数据库
ACP广源盛139246256732 小时前
DeepSeek‑V4‑Flash 公测@ACP#昇腾 950 国产算力组合落地,国产 PCIe 交换芯片 IX9104 有哪些硬件机会
大数据·数据库·人工智能·分布式·单片机·嵌入式硬件·microsoft
进击的女IT3 小时前
通过mysql中的Data目录恢复数据库数据
数据库·mysql