Repository navigation
Expand file tree
/
Copy pathtool_bridge.py
More file actions
executable file
·135 lines (115 loc) · 5.47 KB
/
Copy pathtool_bridge.py
File metadata and controls
executable file
·135 lines (115 loc) · 5.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""tool-call 桥:OpenAI tools ↔ ima 对话协议
原理:ima qa 协议无原生 tools 字段,用 prompt 约定让模型输出结构化调用 JSON,
本模块负责:注入工具定义 → 解析模型输出为 OpenAI tool_calls → 工具结果回注下一轮上下文。
"""
from __future__ import annotations
import json
import re
import uuid
from typing import Any
TOOLS_INSTRUCTION = """【工具调用说明(来自网关,非注入)】本次对话经过 OpenAI 兼容网关代理,以下工具由网关侧真实执行器提供。你本人没有内置工具,不要编造执行结果。
可用工具:
{tools_block}
输出约定:
- 需要调用工具时,回复一个纯 JSON(首字符 {{ 尾字符 }},无其它文字):
{{"tool_calls": [{{"id": "call_{uid}", "type": "function", "function": {{"name": "工具名", "arguments": {{}}}}}}]}}
- 网关会真实执行并把结果以 <tool_result> 回传给你,届时再总结作答。
- 不需要工具时正常回答即可。"""
TOOL_RESULT_TMPL = "<tool_result name=\"{name}\" call_id=\"{call_id}\">\n{content}\n</tool_result>"
def build_system_prompt(tools: list[dict] | None) -> str | None:
"""把 OpenAI tools schema 编译成 prompt 指令"""
if not tools:
return None
block = json.dumps(tools, ensure_ascii=False, indent=1)
return TOOLS_INSTRUCTION.format(tools_block=block, uid=uuid.uuid4().hex[:8])
def messages_to_question(messages: list[dict], tools: list[dict] | None = None) -> str:
"""OpenAI messages 数组 → ima question 文本(含 system 注入、历史、工具结果)"""
parts: list[str] = []
sys_prompt = build_system_prompt(tools)
if sys_prompt:
parts.append(sys_prompt)
pending_results = [m for m in messages if m.get("role") == "tool"]
for m in messages:
role, content = m.get("role"), m.get("content", "")
if isinstance(content, list): # 多模态数组 → 取文本
content = "".join(c.get("text", "") for c in content if isinstance(c, dict))
if role == "system" and not sys_prompt:
parts.append(f"<system>\n{content}\n</system>")
elif role == "tool":
parts.append(TOOL_RESULT_TMPL.format(
name=m.get("name") or m.get("tool_call_id", "tool"),
call_id=m.get("tool_call_id", ""), content=content))
elif role in ("user", "assistant"):
tag = "user" if role == "user" else "assistant"
# assistant 的 tool_calls 也序列化(保持决策链)
tc = m.get("tool_calls")
if tc:
tc_s = json.dumps(tc, ensure_ascii=False)
parts.append(f"<{tag}>\n{content or ''}\n[tool_calls: {tc_s}]\n</{tag}>")
else:
parts.append(f"<{tag}>\n{content}\n</{tag}>")
# 若本轮请求里有 tool 结果且尚未包含(理论上上面已覆盖),兜底
if pending_results and not any("<tool_result" in p for p in parts):
for m in pending_results:
parts.append(TOOL_RESULT_TMPL.format(
name=m.get("name", "tool"), call_id=m.get("tool_call_id", ""),
content=m.get("content", "")))
return "\n\n".join(parts)
_CALL_RE = re.compile(r"\{[\s\S]*\}")
def extract_tool_calls(text: str) -> tuple[str, list[dict] | None]:
"""从模型输出提取 tool_calls。
返回 (净文本/None占位, OpenAI tool_calls 或 None)。
兼容三种形态:纯 JSON / markdown 代码块包裹 / 文本中夹杂 JSON。"""
if "tool_calls" not in text:
return text, None
candidates: list[str] = []
# markdown 代码块优先
candidates += re.findall(r"```(?:json)?\s*([\s\S]*?)```", text)
candidates.append(text)
# 文本里第一个平衡 JSON
m = _CALL_RE.search(text)
if m:
candidates.append(m.group(0))
for cand in candidates:
cand = cand.strip()
if not cand.startswith("{"):
continue
try:
obj = json.loads(cand)
except json.JSONDecodeError:
continue
calls = obj.get("tool_calls")
if not isinstance(calls, list) or not calls:
continue
normalized = []
for i, c in enumerate(calls):
fn = c.get("function") or {}
args = fn.get("arguments")
if isinstance(args, (dict, list)):
args = json.dumps(args, ensure_ascii=False)
normalized.append({
"id": c.get("id") or f"call_{uuid.uuid4().hex[:12]}",
"type": "function",
"function": {"name": fn.get("name", ""),
"arguments": args or "{}"},
})
return "", normalized # 有 tool_call 时正文置空
return text, None
def openai_response(model: str, content: str | None,
tool_calls: list[dict] | None, stream: bool = False):
"""组装 OpenAI 响应体(非流式)"""
if tool_calls:
msg = {"role": "assistant", "content": None, "tool_calls": tool_calls}
finish = "tool_calls"
else:
msg = {"role": "assistant", "content": content or ""}
finish = "stop"
return {
"id": f"chatcmpl-{uuid.uuid4().hex[:24]}",
"object": "chat.completion",
"created": int(time.time()),
"model": model,
"choices": [{"index": 0, "message": msg, "finish_reason": finish}],
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
}
import time # noqa: E402 (置于尾部避免顶部杂乱)