Python implementationPython 实现
Force the tool when freshness is non-negotiable新鲜度不可妥协时,强制调用工具
DeepSeek’s official API exposes function tools. The model
returns function arguments; your code executes the function and
sends its result back. DeepSeek’s documentation explicitly notes
that the model does not execute the function itself.DeepSeek 官方 API
支持函数工具。模型返回函数参数,由你的代码执行函数并把结果送回;官方文档明确指出,具体函数并不是由模型自行执行。
import json
from openai import OpenAI
client = OpenAI(api_key=DEEPSEEK_API_KEY,
base_url="https://api.deepseek.com")
tools = [{
"type": "function",
"function": {
"name": "get_current_stock_quote",
"description": "Get a current, read-only stock quote.",
"parameters": {
"type": "object",
"properties": {
"symbol": {"type": "string"},
"exchange": {"type": "string"}
},
"required": ["symbol"],
"additionalProperties": False
}
}
}]
messages = [
{"role": "system", "content":
"For current market facts, use the quote tool. Never substitute memory. "
"State source, provider timestamp, session, and delay status."},
{"role": "user", "content": user_question}
]
first = client.chat.completions.create(
model="deepseek-v4-pro",
messages=messages, tools=tools,
tool_choice="required"
).choices[0].message
args = json.loads(first.tool_calls[0].function.arguments)
quote = execute_validated_quote(args) # your server-side code
messages += [first, {
"role": "tool",
"tool_call_id": first.tool_calls[0].id,
"content": json.dumps(quote)
}]
answer = client.chat.completions.create(
model="deepseek-v4-pro", messages=messages, tools=tools
).choices[0].message.content
Validate generated arguments校验模型生成的参数
Treat arguments as untrusted input. Parse JSON, reject
unexpected keys, normalize case, cap list lengths, resolve
venue ambiguity, and apply authorization before contacting a
provider. The API reference warns that generated arguments may
be invalid or contain hallucinated parameters.把参数视为不可信输入:解析
JSON、拒绝未知字段、统一大小写、限制列表长度、处理交易所歧义,并在访问服务商前执行授权。官方
API 参考也提醒,生成参数可能无效或包含虚构字段。
Use auto selectively有选择地使用 auto
Use auto when the same assistant handles stable
educational questions and current-data questions. At the
application layer, classify hard freshness intent and require
the tool for those requests.同一助手同时处理稳定知识和当前数据时,可以使用
auto。但应用层应识别强实时意图并强制调用工具。
+
Replace the placeholder替换占位函数
A provider adapter with validation and freshness checks带参数校验与新鲜度检查的行情适配器
The endpoint and response fields below are intentionally
generic. Map them to the official documentation and entitlement
of the provider you actually select; do not copy field names
blindly.下面的端点和返回字段刻意保持通用。请按实际选择的数据源官方文档与授权范围完成映射,不要直接照抄字段名。
import os, re
from datetime import datetime, timezone
import httpx
SYMBOL = re.compile(r"^[A-Z][A-Z0-9.-]{0,14}$")
def execute_validated_quote(arguments):
symbol = str(arguments.get("symbol", "")).strip().upper()
exchange = str(arguments.get("exchange", "")).strip().upper() or None
if not SYMBOL.fullmatch(symbol):
return {"status": "error", "code": "invalid_symbol"}
response = httpx.get(
os.environ["MARKET_DATA_URL"],
params={"symbol": symbol, "exchange": exchange},
headers={"Authorization": "Bearer " + os.environ["MARKET_DATA_API_KEY"]},
timeout=4.0
)
response.raise_for_status()
raw = response.json()
provider_time = datetime.fromisoformat(
raw["timestamp"].replace("Z", "+00:00")
)
retrieved_at = datetime.now(timezone.utc)
age_seconds = (retrieved_at - provider_time).total_seconds()
if age_seconds < 0 or age_seconds > MAX_QUOTE_AGE_SECONDS:
return {"status": "error", "code": "stale_quote",
"provider_time": provider_time.isoformat()}
return {
"status": "ok",
"instrument": {"symbol": raw["symbol"],
"exchange": raw["exchange"]},
"quote": {"value": raw["price"],
"field": raw["price_type"],
"currency": raw["currency"]},
"freshness": {"provider_time": provider_time.isoformat(),
"retrieved_at": retrieved_at.isoformat(),
"session": raw["session"],
"delay": raw["delay_label"]},
"source": {"provider": raw["provider"],
"feed": raw["feed"]}
}
Example: successful grounded answer示例:有数据依据的成功回答
User asks for the current quote. DeepSeek requests the
function. The backend returns an ok envelope. The
final answer states the resolved symbol and exchange, price
meaning, currency, provider time, session, source, and delay
label.用户询问当前行情,DeepSeek 请求函数,后端返回
ok
封装。最终回答展示已解析代码与交易所、价格含义、币种、数据源时间、交易时段、来源和延迟标签。
Example: honest failure示例:诚实失败
If the adapter returns stale_quote,
not_entitled, or timeout, DeepSeek
says that a current price could not be verified and retains
any available timestamp. It does not output a remembered
price.如果适配器返回 stale_quote、not_entitled
或 timeout,DeepSeek
应说明当前价格无法验证,并保留可用时间信息,不能输出记忆中的价格。
Read DeepSeek’s official Tool Calls guide阅读 DeepSeek 官方 Tool Calls 指南
·
Check the current Chat Completion schema查看当前 Chat Completion Schema