模型
控制台
文档
试验场
模型
控制台
文档
试验场
  • 概览

    • 简介
    • 快速开始
    • 更新日志
    • 费用与价格
  • API使用

    • API使用
  • 最佳实践

    • 智能体
    • function call
    • MCP使用案例
  • 项目管理

    • 创建或加入组织
    • 创建项目
    • 选择服务
    • 设置API Key
  • 试验场

    • 如何进入试验场
    • Chat
  • 热门工具接入

    • ARGO
    • Dify
    • Bob翻译
    • ChatGPT Box
    • 沉浸式导读
    • 沉浸式翻译
    • 馆长
    • 划词翻译
    • 流畅阅读
    • Cursor
    • Chatbox
    • ChatGPT-Next-Web
    • Cherry Studio
    • Easydict
    • Enconvo
    • Pal - AI Chat Client
    • RSS翻译器
    • 思源笔记
    • ToMemo
    • Cline
    • AI-commit

function call

函数调用为模型提供了一种强大且灵活的方式,用于与您的代码或外部服务进行交互。这里给出一段示例代码,示例如何调用外部函数获取天气。

# 支持兼容OpenAI Python SDK  终端运行:pip install OpenAI
from openai import OpenAI
import json

## 函数调用接口,这里作为示意函数直接给出返回值
def get_weather(latitude,longtitude):
    return 20

## 初始化客户端
client = OpenAI(
    api_key= "API_KEY",
    base_url= "https://www.sophnet.com/api/open-apis/v1"
)
## 创建tools
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current temperature for provided coordinates in celsius.",
        "parameters": {
            "type": "object",
            "properties": {
                "latitude": {"type": "number"},
                "longitude": {"type": "number"}
            },
            "required": ["latitude", "longitude"],
            "additionalProperties": False
        },
        "strict": True
    }
}]

## 创建Messages
messages = [{"role": "user", "content": "今日上海天气如何?"}]

## 第一次调用接口
completion = client.chat.completions.create(
    model="DeepSeek-R1",
    messages=messages,
    tools=tools,
)

## 从第一次的结果中获取函数参数
tool_call = completion.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)

## 调用函数获取结果
result = get_weather(args["latitude"], args["longitude"])

## 将第一次的回复以及函数返回值加入到messages中
messages.append(completion.choices[0].message)  # append model's function call message
messages.append({                               # append result message
    "role": "tool",
    "tool_call_id": tool_call.id,
    "content": str(result)
})

## 第二次调用接口
completion_2 = client.chat.completions.create(
    model="DeepSeek-R1",
    messages=messages,
    tools=tools,
)

# 打印结果
print(completion_2.choices[0].message.content)
Prev
智能体
Next
MCP使用案例