返回提交历史
Added
etc/unittest/test_tool_support_enhanced.py
+179
-0
Modified
g4f/Provider/__init__.py
+5
-0
Added
g4f/Provider/needs_auth/ChatGPTLightweight.py
+428
-0
Added
g4f/Provider/openai/turnstile_vm.py
+454
-0
Modified
g4f/providers/tool_support.py
+107
-220
Modified
g4f/tools/run_tools.py
+16
-0
Added
g4f/tools/tool_support.py
+468
-0
XFEstudio/gpt4free
Add new ChatGPT provider
45e562f8
代码差异
7 个文件
+1657
-220
@@ -0,0 +1,179 @@
1
import asyncio
2
import unittest
3
from typing import List, Optional
4
5
from g4f.providers.base_provider import AsyncGeneratorProvider
6
from g4f.providers.response import FinishReason, ToolCalls
7
from g4f.providers.tool_support import ToolSupportProvider, _preprocess_tool_messages
8
from g4f.tools.tool_support import (
9
function_to_tool_def,
10
normalize_tool_defs,
11
normalize_tool_calls,
12
parse_tool_calls_from_text,
13
)
14
15
16
def sample_get_weather(location: str, unit: str = "celsius") -> str:
17
"""Get the current weather for a location."""
18
return f"Weather in {location}: 20 degrees {unit}"
19
20
21
class DummyToolObj:
22
name = "dummy_func"
23
description = "Dummy tool description"
24
parameters = {
25
"type": "object",
26
"properties": {"val": {"type": "integer"}},
27
"required": ["val"],
28
}
29
30
31
class XMLToolProviderMock(AsyncGeneratorProvider):
32
working = True
33
34
@staticmethod
35
async def create_async_generator(model, messages, stream=True, **kwargs):
36
yield "<tool_call>{\"name\":\"sample_get_weather\",\"arguments\":{\"location\":\"Tokyo\"}}</tool_call>"
37
yield FinishReason("stop")
38
39
40
class TestToolSupportEnhanced(unittest.TestCase):
41
def test_function_to_tool_def(self):
42
tool = function_to_tool_def(sample_get_weather)
43
self.assertEqual(tool["type"], "function")
44
fn = tool["function"]
45
self.assertEqual(fn["name"], "sample_get_weather")
46
self.assertIn("Get the current weather", fn["description"])
47
props = fn["parameters"]["properties"]
48
self.assertIn("location", props)
49
self.assertIn("unit", props)
50
self.assertEqual(props["location"]["type"], "string")
51
self.assertEqual(fn["parameters"]["required"], ["location"])
52
53
def test_normalize_tool_defs_diverse_formats(self):
54
# 1. Python Callable
55
# 2. Anthropic input_schema
56
# 3. Flat dict
57
# 4. Object attributes
58
anthropic_tool = {
59
"name": "search_db",
60
"description": "Search database",
61
"input_schema": {"type": "object", "properties": {"q": {"type": "string"}}},
62
}
63
flat_tool = {
64
"name": "calc",
65
"description": "Calculate expression",
66
"parameters": {"type": "object", "properties": {"expr": {"type": "string"}}},
67
}
68
obj_tool = DummyToolObj()
69
70
defs = normalize_tool_defs([sample_get_weather, anthropic_tool, flat_tool, obj_tool])
71
self.assertEqual(len(defs), 4)
72
names = [d["function"]["name"] for d in defs]
73
self.assertEqual(names, ["sample_get_weather", "search_db", "calc", "dummy_func"])
74
75
def test_normalize_tool_calls_diverse_formats(self):
76
# 1. OpenAI standard
77
openai_call = {
78
"id": "call_1",
79
"type": "function",
80
"function": {"name": "calc", "arguments": '{"expr": "1+1"}'},
81
}
82
# 2. Anthropic tool_use
83
anthropic_call = {
84
"type": "tool_use",
85
"id": "toolu_99",
86
"name": "search_db",
87
"input": {"q": "query"},
88
}
89
# 3. Gemini functionCall
90
gemini_call = {
91
"functionCall": {"name": "sample_get_weather", "args": {"location": "London"}}
92
}
93
# 4. Flat call
94
flat_call = {"name": "calc", "arguments": {"expr": "2+2"}}
95
96
normalized = normalize_tool_calls([openai_call, anthropic_call, gemini_call, flat_call])
97
self.assertEqual(len(normalized), 4)
98
99
self.assertEqual(normalized[0]["function"]["name"], "calc")
100
self.assertEqual(normalized[1]["function"]["name"], "search_db")
101
self.assertEqual(normalized[1]["id"], "toolu_99")
102
self.assertEqual(normalized[2]["function"]["name"], "sample_get_weather")
103
self.assertEqual(normalized[3]["function"]["name"], "calc")
104
105
def test_parse_tool_calls_from_text_formats(self):
106
# XML tag
107
xml_text = "<tool_call>{\"name\": \"calc\", \"arguments\": {\"expr\": \"3*3\"}}</tool_call>"
108
res_xml = parse_tool_calls_from_text(xml_text)
109
self.assertEqual(len(res_xml), 1)
110
self.assertEqual(res_xml[0]["name"], "calc")
111
112
# ReAct style
113
react_text = "Action: sample_get_weather\nAction Input: {\"location\": \"Berlin\"}"
114
res_react = parse_tool_calls_from_text(react_text)
115
self.assertEqual(len(res_react), 1)
116
self.assertEqual(res_react[0]["name"], "sample_get_weather")
117
118
# Stringified format
119
stringified = "[Tool call: search_db] (id=call_abc)\nArguments: {\"q\": \"test\"}"
120
res_str = parse_tool_calls_from_text(stringified)
121
self.assertEqual(len(res_str), 1)
122
self.assertEqual(res_str[0]["name"], "search_db")
123
124
# JSON block in code fences
125
code_fence = "```json\n{\"tool_calls\": [{\"name\": \"calc\", \"arguments\": {\"expr\": \"5+5\"}}]}\n```"
126
res_code = parse_tool_calls_from_text(code_fence)
127
self.assertEqual(len(res_code), 1)
128
self.assertEqual(res_code[0]["name"], "calc")
129
130
def test_preprocess_tool_messages_anthropic_and_legacy(self):
131
messages = [
132
{"role": "system", "content": "You are helpful."},
133
{
134
"role": "assistant",
135
"content": [
136
{"type": "text", "text": "Using tool..."},
137
{"type": "tool_use", "id": "t1", "name": "calc", "input": {"expr": "1+1"}},
138
],
139
},
140
{
141
"role": "user",
142
"content": [
143
{"type": "tool_result", "tool_use_id": "t1", "content": "Result: 2"}
144
],
145
},
146
]
147
processed = _preprocess_tool_messages(messages)
148
self.assertEqual(len(processed), 3)
149
self.assertEqual(processed[0]["role"], "user")
150
self.assertIn("[System]", processed[0]["content"])
151
self.assertEqual(processed[1]["role"], "assistant")
152
self.assertIn("[Tool call: calc]", processed[1]["content"])
153
self.assertEqual(processed[2]["role"], "user")
154
self.assertIn("[Tool response (id=t1)]", processed[2]["content"])
155
156
157
def test_tool_support_provider_with_xml_tool_call(self):
158
async def run():
159
out = []
160
async for chunk in ToolSupportProvider.create_async_generator(
161
model="test-model",
162
messages=[{"role": "user", "content": "Weather in Tokyo"}],
163
stream=True,
164
tools=[sample_get_weather],
165
provider=XMLToolProviderMock,
166
):
167
out.append(chunk)
168
return out
169
170
out = asyncio.run(run())
171
tool_chunks = [x for x in out if isinstance(x, ToolCalls)]
172
self.assertEqual(len(tool_chunks), 1)
173
calls = tool_chunks[0].get_list()
174
self.assertEqual(len(calls), 1)
175
self.assertEqual(calls[0]["function"]["name"], "sample_get_weather")
176
177
178
if __name__ == "__main__":
179
unittest.main()
@@ -68,6 +68,7 @@ class ProviderLoader:
68
68
"OpenaiAPI",
69
69
"OpenaiAccount",
70
70
"OpenaiChat",
71
"ChatGPTLightweight",
71
72
"OpenaiTemplate",
72
73
"OperaAria",
73
74
"Perplexity",
@@ -408,6 +409,10 @@ class ProviderLoader:
408
409
from g4f.Provider.needs_auth.OpenaiChat import OpenaiChat
409
410
410
411
return OpenaiChat
412
elif name == "ChatGPTLightweight":
413
from g4f.Provider.needs_auth.ChatGPTLightweight import ChatGPTLightweight
414
415
return ChatGPTLightweight
411
416
elif name == "OpenaiTemplate":
412
417
from g4f.Provider.template.OpenaiTemplate import OpenaiTemplate
413
418
@@ -0,0 +1,428 @@
1
from __future__ import annotations
2
3
import asyncio
4
import base64
5
import html
6
import json
7
import os
8
import random
9
import re
10
import time
11
import uuid
12
13
from ...typing import AsyncResult, Messages
14
from ...requests import StreamSession
15
from ...requests.raise_for_status import raise_for_status
16
from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
17
from ..helper import format_prompt
18
from ..openai.proofofwork import generate_proof_token
19
from ..openai.new import get_requirements_token, get_config
20
from ..openai.turnstile_vm import process_turnstile_new
21
from ...providers.response import JsonConversation, FinishReason
22
from ...cookies import get_cookies
23
from ...config import COOKIES_DIR, CUSTOM_COOKIES_DIR
24
from ... import debug
25
26
27
class Conversation(JsonConversation):
28
"""Tracks the anonymous (lightweight) chat session state."""
29
30
def __init__(self, model: str):
31
self.model = model
32
self.oai_did = str(uuid.uuid4())
33
self.conversation_id: str = None
34
self.message_id: str = None
35
36
37
_RE_CONVERSATION_ID = re.compile(r'data-conversation-id="([\w-]+)"')
38
_RE_MESSAGE_ID = re.compile(r'data-message-id="([\w-]+)"')
39
_RE_ASSISTANT_BLOCK = re.compile(
40
r'(<p\b[^>]*data-assistant-stream-block=""[^>]*>)(.*?)</p>',
41
re.DOTALL,
42
)
43
_RE_BLOCK_INDEX = re.compile(r'data-assistant-stream-block-index="(\d+)"')
44
_RE_FAILURE_STATUS = re.compile(r'data-failure-status="(\d+)"')
45
_RE_GATE_KIND = re.compile(r'data-gate-kind="(\w+)"')
46
_RE_XML_MARKER = re.compile(r"<\?[^>]*>")
47
48
DEFAULT_HEADERS = {
49
"accept": "*/*",
50
"accept-language": "en-US,en;q=0.8",
51
"referer": "https://chatgpt.com/",
52
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36",
53
}
54
55
56
class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
57
"""ChatGPT anonymous guest chat via the "web-mobile" (unauth-mweb) surface.
58
59
Implements the lightweight_authenticated=0 flow observed in the guest
60
web UI: requirements token -> prepare -> sentinel/req -> proof-of-work ->
61
finalize -> conversation/prepare -> conversation/updates. The reply is
62
returned as a DPU HTML partial document containing assistant stream blocks.
63
64
The upstream gate intermittently answers with a 403 "Chat verification
65
required" (rate limiting / IP reputation). Requests are therefore retried
66
with a fresh session a few times before giving up.
67
68
A "cf_clearance" cookie from a real browser session (HAR capture or the
69
local browser profile) marks the visitor as trusted and greatly improves
70
the pass rate; see `_load_auth_state`.
71
"""
72
73
label = "ChatGPT (Lightweight)"
74
url = "https://chatgpt.com"
75
working = True
76
needs_auth = False
77
supports_stream = True
78
supports_system_message = True
79
supports_message_history = True
80
81
default_model = "auto"
82
# The guest surface routes to ChatGPT's default model; it is advertised
83
# for the models it can serve so model/provider validation passes.
84
models = [default_model, "gpt-4o-mini", "gpt-4o", "gpt-4.1-mini", "gpt-5"]
85
86
user_agent = DEFAULT_HEADERS["user-agent"]
87
max_retries = 4
88
89
# Cached (cookies, headers) harvested from HAR files / browser profile.
90
_auth_state = None
91
_auth_state_loaded_at = 0.0
92
_AUTH_STATE_TTL = 600.0
93
94
# Static app-version headers worth copying from a captured session.
95
# Note: the worker-version headers ("cloudflare-workers-version-overrides",
96
# "x-web-mobile-document-worker-version") are deliberately NOT copied:
97
# they are validated against the signed
98
# "x-web-mobile-conversation-document-affinity" token, which is minted
99
# client-side per session and cannot be reused. Sending the version
100
# headers without a matching affinity fails with a hard 403 "Invalid
101
# conversation document affinity"; sending neither reaches the app gate.
102
_AUTH_HEADERS_WHITELIST = (
103
"x-web-mobile-document-renderer",
104
"x-web-mobile-connectivity-effective-type",
105
"sec-ch-ua",
106
"sec-ch-ua-arch",
107
"sec-ch-ua-bitness",
108
"sec-ch-ua-full-version",
109
"sec-ch-ua-full-version-list",
110
"sec-ch-ua-mobile",
111
"sec-ch-ua-model",
112
"sec-ch-ua-platform",
113
"sec-ch-ua-platform-version",
114
)
115
116
# Endpoints of the unauth-mweb surface
117
requirements_prepare_url = "https://chatgpt.com/unauth-mweb/sentinel/chat-requirements/prepare"
118
requirements_finalize_url = "https://chatgpt.com/unauth-mweb/sentinel/chat-requirements/finalize"
119
sentinel_req_url = "https://chatgpt.com/backend-api/sentinel/req"
120
conversation_prepare_url = "https://chatgpt.com/unauth-mweb/conversation/prepare"
121
conversation_updates_url = "https://chatgpt.com/unauth-mweb/conversation/updates"
122
123
@classmethod
124
def get_client_context(cls) -> str:
125
# This exact shape is validated server-side; simplified versions are
126
# rejected with 400 "Invalid clientContextualInfo".
127
return json.dumps({
128
"app_name": "chatgpt.com",
129
"has_web_push_capabilities": True,
130
"is_dark_mode": False,
131
"web_push_notification_permission": "default",
132
"page_height": random.randint(600, 900),
133
"page_width": random.randint(600, 1400),
134
"pixel_ratio": 1,
135
"screen_height": random.choice([800, 900, 1080]),
136
"screen_width": random.choice([1280, 1600, 1920]),
137
"time_since_loaded": random.randint(1, 10),
138
})
139
140
@classmethod
141
async def create_async_generator(
142
cls,
143
model: str,
144
messages: Messages,
145
proxy: str = None,
146
timeout: int = 120,
147
conversation: Conversation = None,
148
return_conversation: bool = True,
149
**kwargs,
150
) -> AsyncResult:
151
model = cls.get_model(model)
152
prompt = format_prompt(messages)
153
if conversation is None:
154
conversation = Conversation(model)
155
156
last_error = None
157
for attempt in range(cls.max_retries):
158
try:
159
# A fresh visitor id per attempt: a flagged oai-did stays
160
# flagged, so reusing it would poison every retry.
161
if attempt > 0:
162
conversation.oai_did = str(uuid.uuid4())
163
reply = await cls._fetch_reply(prompt=prompt, conversation=conversation, proxy=proxy, timeout=timeout)
164
if reply is not None:
165
yield reply
166
if return_conversation:
167
yield conversation
168
yield FinishReason("stop")
169
return
170
except Exception as e:
171
last_error = e
172
debug.log(f"ChatGPTLightweight: attempt {attempt + 1} failed: {e}")
173
if attempt + 1 < cls.max_retries:
174
# The anonymous-chat gate is rate-limit based — back off
175
# before retrying with a fresh session.
176
await asyncio.sleep(3 * (attempt + 1) + random.uniform(0, 2))
177
if last_error is not None:
178
raise last_error
179
raise RuntimeError("ChatGPTLightweight: no reply received (verification gate)")
180
181
@classmethod
182
def _har_paths(cls) -> list:
183
paths = []
184
seen = set()
185
for dir_path in (CUSTOM_COOKIES_DIR, str(COOKIES_DIR), os.path.expanduser("~/.g4f/workspace")):
186
try:
187
if not os.path.isdir(dir_path):
188
continue
189
for name in os.listdir(dir_path):
190
if name.endswith(".har") and name not in seen:
191
seen.add(name)
192
paths.append(os.path.join(dir_path, name))
193
except OSError:
194
pass
195
return paths
196
197
@classmethod
198
def _load_auth_state(cls) -> tuple:
199
"""Collect chatgpt.com cookies and app headers from real sessions.
200
201
Sources, in order: the g4f cookie cache (populated from HAR files by
202
the API server) and browser_cookie3, then a direct scan of *.har
203
files in the cookie directories. The "cf_clearance" cookie is the
204
important one: without it the anonymous-chat gate rejects most
205
requests with 403 "Chat verification required".
206
"""
207
now = time.time()
208
if cls._auth_state is not None and now - cls._auth_state_loaded_at < cls._AUTH_STATE_TTL:
209
return cls._auth_state
210
211
cookies = {}
212
headers = {}
213
try:
214
cookies.update(get_cookies("chatgpt.com", raise_requirements_error=False))
215
except Exception:
216
pass
217
218
for path in cls._har_paths():
219
try:
220
with open(path, "rb") as file:
221
har = json.load(file)
222
except Exception:
223
continue
224
for entry in har.get("log", {}).get("entries", []):
225
request = entry.get("request", {})
226
entry_headers = {
227
h["name"].lower(): h["value"] for h in request.get("headers", [])
228
}
229
host = entry_headers.get(":authority") or entry_headers.get("host", "")
230
if "chatgpt.com" not in host:
231
continue
232
for cookie in request.get("cookies", []):
233
cookies.setdefault(cookie["name"], cookie["value"])
234
for name in cls._AUTH_HEADERS_WHITELIST:
235
if name in entry_headers:
236
headers.setdefault(name, entry_headers[name])
237
238
if cookies:
239
debug.log(
240
f"ChatGPTLightweight: loaded {len(cookies)} chatgpt.com cookies"
241
f" (cf_clearance={'yes' if cookies.get('cf_clearance') else 'no'})"
242
)
243
cls._auth_state = (cookies, headers)
244
cls._auth_state_loaded_at = now
245
return cls._auth_state
246
247
@classmethod
248
async def _fetch_reply(
249
cls,
250
prompt: str,
251
conversation: Conversation,
252
proxy: str = None,
253
timeout: int = 120,
254
) -> str:
255
auth_cookies, auth_headers = cls._load_auth_state()
256
# Reuse the captured visitor id when available so the session stays
257
# consistent with the cf_clearance cookie it was issued with.
258
oai_did = conversation.oai_did = auth_cookies.get("oai-did") or str(uuid.uuid4())
259
session_id = str(uuid.uuid4())
260
headers = {
261
**DEFAULT_HEADERS,
262
"oai-did": oai_did,
263
"oai-session-id": session_id,
264
**auth_headers,
265
}
266
cookies = {**auth_cookies, "oai-did": oai_did}
267
config = get_config(cls.user_agent)
268
requirements_token = get_requirements_token(config)
269
270
async with StreamSession(
271
impersonate="chrome", timeout=timeout, proxy=proxy,
272
cookies=cookies,
273
) as session:
274
json_headers = {
275
**headers,
276
"accept": "application/json",
277
"content-type": "application/json",
278
}
279
# 1. Prepare: register the requirements attempt
280
async with session.post(
281
cls.requirements_prepare_url,
282
json={"p": requirements_token},
283
headers=json_headers,
284
) as response:
285
await raise_for_status(response)
286
prepare_token = (await response.json())["prepare_token"]
287
288
# 2. Ask for the proof-of-work challenge
289
async with session.post(
290
cls.sentinel_req_url,
291
json={"p": requirements_token, "id": oai_did, "flow": "conversation"},
292
headers=json_headers,
293
) as response:
294
await raise_for_status(response)
295
requirements = await response.json()
296
pow_config = requirements.get("proofofwork") or {}
297
298
# 3. Solve the hashcash challenge
299
proof_token = generate_proof_token(
300
True, pow_config.get("seed", ""), pow_config.get("difficulty", ""), cls.user_agent
301
)
302
303
# 3b. Solve the invisible turnstile challenge. The "dx" payload is
304
# a VM op list XOR-encoded with the requirements token ("p") that
305
# was sent to sentinel/req; the browser runs it through the
306
# sentinel script and submits the result.
307
turnstile_config = requirements.get("turnstile") or {}
308
turnstile_token = ""
309
if turnstile_config.get("required"):
310
turnstile_token = process_turnstile_new(
311
turnstile_config.get("dx", ""), requirements_token, cls.user_agent
312
)
313
debug.log(f"ChatGPTLightweight: turnstile token len {len(turnstile_token)}")
314
315
# 4. Finalize: exchange prepare token + proof for a chat requirements token
316
async with session.post(
317
cls.requirements_finalize_url,
318
json={"prepare_token": prepare_token, "proofofwork": proof_token},
319
headers=json_headers,
320
) as response:
321
await raise_for_status(response)
322
chat_requirements_token = (await response.json())["token"]
323
324
client_context = cls.get_client_context()
325
retry_owner = json.dumps({"mode": "anonymous", "sessionEpoch": None})
326
form_headers = dict(headers)
327
328
# 5. Register the conversation document worker
329
async with session.post(
330
f"{cls.conversation_prepare_url}?lightweight_authenticated=0",
331
data={
332
"conversationRetryOwner": retry_owner,
333
"conversationState": json.dumps({
334
"messages": [],
335
"parentMessageId": "client-created-root",
336
"userMessageCount": 0,
337
}),
338
"clientContextualInfo": client_context,
339
"timezone": "Europe/Berlin",
340
"timezoneOffsetMinutes": "-120",
341
},
342
headers=form_headers,
343
) as response:
344
await raise_for_status(response)
345
prepare_data = await response.json()
346
conduit_token = prepare_data.get("conduit_token")
347
348
# 6. Send the message and read the DPU partial document
349
operation_id = str(uuid.uuid4())
350
form = {
351
"conversationState": json.dumps({
352
"messages": [],
353
"parentMessageId": "client-created-root",
354
"safety": {"dismissedInterventionIds": []},
355
"userMessageCount": 1,
356
}),
357
"messageMetadata": "{}",
358
"oai-session-id": session_id,
359
"imageAttachments": "[]",
360
"pendingImageUploads": "[]",
361
"prompt": prompt,
362
"chatRequirementsToken": chat_requirements_token,
363
"proofToken": proof_token,
364
"turnstileToken": turnstile_token,
365
"telemetryToken": "",
366
# Real browsers send measured turn timings; "[1,null]" is a
367
# bot signal that feeds the "Chat verification required" gate.
368
"timingToken": "[1,%.1f,70,0,21,2,0,88]" % random.uniform(40.0, 150.0),
369
"clientContextualInfo": client_context,
370
"imageSaveData": "off",
371
"imageEffectiveType": "4g",
372
"timezone": "Europe/Berlin",
373
"timezoneOffsetMinutes": "-120",
374
"conversationRetryOwner": retry_owner,
375
"assistantMessageId": f"pending-{str(uuid.uuid4())}",
376
"userMessageId": str(uuid.uuid4()),
377
}
378
update_headers = {
379
**form_headers,
380
"accept": "text/vnd.openai.web-mobile-partial+html",
381
"x-conduit-token": conduit_token,
382
"x-oai-turn-trace-id": operation_id,
383
"x-web-mobile-conversation-renderer": "octane",
384
"x-web-mobile-conversation-stream-protocol": "1",
385
"x-web-mobile-prepare-state": "success",
386
}
387
async with session.post(
388
f"{cls.conversation_updates_url}?lightweight_authenticated=0&operationId={operation_id}",
389
data=form,
390
headers=update_headers,
391
) as response:
392
await raise_for_status(response)
393
text = await response.text()
394
395
return cls._parse_dpu(text, conversation)
396
397
@classmethod
398
def _parse_dpu(cls, text: str, conversation: Conversation) -> str:
399
"""Extract the assistant reply from the DPU partial document.
400
401
Returns None when the upstream verification gate rejected the chat
402
(403 "Chat verification required") so the caller can retry.
403
"""
404
failure = _RE_FAILURE_STATUS.search(text)
405
if failure is not None:
406
gate = _RE_GATE_KIND.search(text)
407
debug.log(
408
f"ChatGPTLightweight: gate rejected chat "
409
f"(status={failure.group(1)}, kind={gate.group(1) if gate else 'unknown'})"
410
)
411
return None
412
conversation_id = _RE_CONVERSATION_ID.search(text)
413
if conversation_id:
414
conversation.conversation_id = conversation_id.group(1)
415
message_id = _RE_MESSAGE_ID.search(text)
416
if message_id:
417
conversation.message_id = message_id.group(1)
418
# Later blocks with the same index are streaming updates that
419
# supersede earlier (partial) ones — keep only the last per index.
420
blocks = {}
421
for tag, block in _RE_ASSISTANT_BLOCK.findall(text):
422
index_match = _RE_BLOCK_INDEX.search(tag)
423
index = int(index_match.group(1)) if index_match else 0
424
blocks[index] = _RE_XML_MARKER.sub("", block)
425
if not blocks:
426
debug.log(f"ChatGPTLightweight: no assistant block in response: {text[:300]!r}")
427
return None
428
return html.unescape("".join(blocks[index] for index in sorted(blocks)))
@@ -2,7 +2,8 @@ from __future__ import annotations
2
2
3
3
import json
4
4
import re
5
from typing import Optional, Union
5
import inspect
6
from typing import Optional, Union, Any
6
7
7
8
from ..typing import AsyncResult, Messages, MediaListType
8
9
from ..client.service import get_model_and_provider
@@ -10,6 +11,11 @@ from ..client.helper import filter_json
10
11
from .types import ProviderType
11
12
from .base_provider import AsyncGeneratorProvider, get_async_provider_method
12
13
from .response import ToolCalls, FinishReason, Usage, Reasoning, JsonConversation
14
from ..tools.tool_support import (
15
normalize_tool_defs,
16
normalize_tool_calls,
17
parse_tool_calls_from_text,
18
)
13
19
14
20
15
21
def _strip_code_fences(text: str) -> str:
@@ -59,24 +65,12 @@ def _parse_json_maybe(s: str):
59
65
60
66
def _stringify_tool_calls(tool_calls: list) -> str:
61
67
"""Render an assistant ``tool_calls`` list as a human-readable text block."""
68
normalized = normalize_tool_calls(tool_calls)
62
69
parts = []
63
for tc in tool_calls:
64
if not isinstance(tc, dict):
65
continue
66
fn = tc.get("function") if tc.get("type") == "function" else tc
67
if not isinstance(fn, dict):
68
continue
69
name = fn.get("name") or tc.get("name") or "unknown"
70
args = fn.get("arguments")
71
if isinstance(args, str):
72
args_str = args
73
else:
74
try:
75
args_str = json.dumps(
76
args if isinstance(args, dict) else {}, ensure_ascii=True
77
)
78
except Exception:
79
args_str = "{}"
70
for tc in normalized:
71
fn = tc.get("function", {})
72
name = fn.get("name") or "unknown"
73
args_str = fn.get("arguments", "{}")
80
74
call_id = tc.get("id", "")
81
75
header = f"[Tool call: {name}]"
82
76
if call_id:
@@ -88,8 +82,6 @@ def _stringify_tool_calls(tool_calls: list) -> str:
88
82
# Matches the text format produced by ``_stringify_tool_calls``:
89
83
# [Tool call: NAME] (id=CALL_ID)
90
84
# Arguments: { ... JSON ... }
91
# The ``(id=...)`` part is optional. The JSON arguments may span multiple
92
# lines and contain nested braces, so we balance them manually.
93
85
_TOOL_CALL_HEADER_RE = re.compile(
94
86
r"\[\s*Tool\s*call\s*:\s*([^\]]+?)\s*\](?:\s*\(id=([^\)]*)\))?\s*\n\s*Arguments\s*:\s*",
95
87
re.IGNORECASE,
@@ -97,14 +89,11 @@ _TOOL_CALL_HEADER_RE = re.compile(
97
89
98
90
99
91
def _extract_balanced_json(s: str, start: int) -> tuple[str, int]:
100
"""Return the balanced JSON object/array starting at ``s[start]`` and the
101
index just past it. If ``s[start]`` is not ``{`` or ``[``, returns the
102
remainder of the line as a best-effort argument string."""
92
"""Return the balanced JSON object/array starting at ``s[start]``."""
103
93
if start >= len(s):
104
94
return "", start
105
95
open_ch = s[start]
106
96
if open_ch not in "{[":
107
# Take until end of line as the argument text.
108
97
end = s.find("\n", start)
109
98
if end == -1:
110
99
end = len(s)
@@ -133,19 +122,11 @@ def _extract_balanced_json(s: str, start: int) -> tuple[str, int]:
133
122
if depth == 0:
134
123
return s[start : i + 1], i + 1
135
124
i += 1
136
# Unbalanced — return everything from start as a best effort.
137
125
return s[start:].strip(), len(s)
138
126
139
127
140
128
def _parse_stringified_tool_calls(text: str) -> list[dict]:
141
"""Parse the human-readable ``[Tool call: NAME] (id=ID)\\nArguments: {JSON}``
142
format back into a list of tool-call dicts.
143
144
This handles the case where a web-API model echoes back the stringified
145
tool-call format (the same format produced by ``_stringify_tool_calls``)
146
instead of emitting a raw JSON tool-call object. Returns an empty list when
147
no stringified tool calls are found.
148
"""
129
"""Parse the human-readable ``[Tool call: NAME] (id=ID)\\nArguments: {JSON}`` format."""
149
130
calls: list[dict] = []
150
131
if not text:
151
132
return calls
@@ -156,8 +137,6 @@ def _parse_stringified_tool_calls(text: str) -> list[dict]:
156
137
args_str, _ = _extract_balanced_json(text, args_start)
157
138
if not name:
158
139
continue
159
# ``arguments`` may be a JSON object, a JSON string, or plain text.
160
arguments: object
161
140
if args_str:
162
141
try:
163
142
arguments = json.loads(args_str)
@@ -176,10 +155,9 @@ def _parse_stringified_tool_calls(text: str) -> list[dict]:
176
155
177
156
178
157
def _stringify_tool_response(message: dict) -> str:
179
"""Render a ``role: tool`` message as a human-readable text block."""
158
"""Render a ``role: tool`` or ``role: function`` message as a human-readable text block."""
180
159
content = message.get("content")
181
160
if isinstance(content, list):
182
# Concatenate text parts from a multipart content list.
183
161
text_parts = []
184
162
for part in content:
185
163
if isinstance(part, dict) and part.get("type") == "text":
@@ -189,8 +167,8 @@ def _stringify_tool_response(message: dict) -> str:
189
167
content = "\n".join(text_parts)
190
168
if content is None:
191
169
content = ""
192
tool_call_id = message.get("tool_call_id", "")
193
name = message.get("name", "")
170
tool_call_id = message.get("tool_call_id") or message.get("id") or ""
171
name = message.get("name") or ""
194
172
header = "[Tool response"
195
173
if name:
196
174
header += f": {name}"
@@ -216,13 +194,7 @@ def _extract_text(content) -> str:
216
194
217
195
218
196
def _merge_messages_to_single_user(messages: Messages) -> Messages:
219
"""Merge all assistant and user messages into a single ``role: user`` message.
220
221
Web-API providers (e.g. Qwen, Copilot) that rely on ``get_last_user_message``
222
only forward the last user message to the server when no ``conversation``
223
handle is available, dropping all prior context. Folding the whole history
224
into one user message ensures the model still sees the full conversation.
225
"""
197
"""Merge all assistant and user messages into a single ``role: user`` message."""
226
198
if not messages:
227
199
return messages
228
200
parts: list[str] = []
@@ -243,23 +215,11 @@ def _merge_messages_to_single_user(messages: Messages) -> Messages:
243
215
244
216
245
217
def _preprocess_tool_messages(messages: Messages) -> Messages:
246
"""Convert ``tool_calls`` on assistant messages and ``role: tool`` messages
247
into readable text so web-only providers can follow the conversation history.
248
249
Assistant messages keep their textual ``content`` (if any) and get the
250
stringified tool calls appended. Tool response messages are rewritten as
251
``role: user`` messages with the stringified response as content.
252
253
``role: system`` messages are folded into the next ``role: user`` message
254
(prefixed with a ``[System]`` header) so providers that only accept
255
``user``/``assistant`` roles still receive the system instructions. If no
256
user message follows, the system content is emitted as a user message.
257
"""
218
"""Convert ``tool_calls`` on assistant messages and ``role: tool`` messages into readable text."""
258
219
processed: Messages = []
259
220
pending_system: list[str] = []
260
221
for msg in messages:
261
222
if not isinstance(msg, dict):
262
# Flush any pending system text before non-dict entries.
263
223
if pending_system:
264
224
processed.append(
265
225
{
@@ -270,15 +230,30 @@ def _preprocess_tool_messages(messages: Messages) -> Messages:
270
230
pending_system = []
271
231
processed.append(msg)
272
232
continue
233
273
234
role = msg.get("role")
274
tool_calls = msg.get("tool_calls")
235
tool_calls = msg.get("tool_calls") or msg.get("function_call")
236
237
content = msg.get("content")
238
anthropic_tool_uses = []
239
anthropic_tool_results = []
240
if isinstance(content, list):
241
for part in content:
242
if isinstance(part, dict):
243
if part.get("type") == "tool_use":
244
anthropic_tool_uses.append(part)
245
elif part.get("type") == "tool_result":
246
anthropic_tool_results.append(part)
247
275
248
if role == "system":
276
249
text = _extract_text(msg.get("content"))
277
250
if text:
278
251
pending_system.append(text)
279
252
continue
280
if role == "assistant" and isinstance(tool_calls, list) and tool_calls:
281
new_msg = {k: v for k, v in msg.items() if k != "tool_calls"}
253
254
if role == "assistant" and (tool_calls or anthropic_tool_uses):
255
calls_to_stringify = tool_calls or anthropic_tool_uses
256
new_msg = {k: v for k, v in msg.items() if k not in ("tool_calls", "function_call")}
282
257
text_parts = []
283
258
existing_content = new_msg.get("content")
284
259
if isinstance(existing_content, str) and existing_content.strip():
@@ -291,11 +266,12 @@ def _preprocess_tool_messages(messages: Messages) -> Messages:
291
266
text_parts.append(t)
292
267
elif isinstance(part, str) and part:
293
268
text_parts.append(part)
294
rendered = _stringify_tool_calls(tool_calls)
269
rendered = _stringify_tool_calls(
270
calls_to_stringify if isinstance(calls_to_stringify, list) else [calls_to_stringify]
271
)
295
272
if rendered:
296
273
text_parts.append(rendered)
297
274
new_msg["content"] = "\n\n".join(text_parts) if text_parts else rendered
298
# Flush any pending system text before this assistant message.
299
275
if pending_system:
300
276
processed.append(
301
277
{
@@ -305,9 +281,20 @@ def _preprocess_tool_messages(messages: Messages) -> Messages:
305
281
)
306
282
pending_system = []
307
283
processed.append(new_msg)
308
elif role == "tool":
309
rendered = _stringify_tool_response(msg)
310
# Fold any pending system text into this rewritten user message.
284
elif role in ("tool", "function") or anthropic_tool_results:
285
if anthropic_tool_results:
286
rendered_parts = []
287
for res in anthropic_tool_results:
288
res_msg = {
289
"name": res.get("name", ""),
290
"tool_call_id": res.get("tool_use_id", ""),
291
"content": res.get("content", ""),
292
}
293
rendered_parts.append(_stringify_tool_response(res_msg))
294
rendered = "\n\n".join(rendered_parts)
295
else:
296
rendered = _stringify_tool_response(msg)
297
311
298
if pending_system:
312
299
rendered = "[System]\n" + "\n".join(pending_system) + "\n\n" + rendered
313
300
pending_system = []
@@ -324,7 +311,6 @@ def _preprocess_tool_messages(messages: Messages) -> Messages:
324
311
pending_system = []
325
312
processed.append(new_msg)
326
313
else:
327
# Flush any pending system text before unhandled roles.
328
314
if pending_system:
329
315
processed.append(
330
316
{
@@ -334,7 +320,7 @@ def _preprocess_tool_messages(messages: Messages) -> Messages:
334
320
)
335
321
pending_system = []
336
322
processed.append(msg)
337
# Flush any trailing system text as a user message.
323
338
324
if pending_system:
339
325
processed.append(
340
326
{"role": "user", "content": "[System]\n" + "\n".join(pending_system)}
@@ -347,9 +333,7 @@ class ToolSupportProvider(AsyncGeneratorProvider):
347
333
348
334
Injects a system prompt instructing the model to emit a JSON tool-call plan,
349
335
delegates to the real provider, parses the JSON response and converts it into
350
``ToolCalls`` + ``FinishReason("tool_calls")`` chunks. ``Reasoning`` / thinking
351
chunks emitted by the underlying provider are forwarded to the caller so the
352
client still sees the model's reasoning.
336
``ToolCalls`` + ``FinishReason("tool_calls")`` chunks.
353
337
"""
354
338
355
339
working = True
@@ -371,76 +355,59 @@ class ToolSupportProvider(AsyncGeneratorProvider):
371
355
model, provider = get_model_and_provider(
372
356
model, provider, stream, logging=False, has_images=media is not None
373
357
)
374
tool_names: list[str] = []
375
tool_schemas: dict[str, dict] = {}
376
if tools:
377
tool_defs = tools if isinstance(tools, list) else []
378
for t in tool_defs:
379
if not isinstance(t, dict) or t.get("type") != "function":
380
continue
381
fn = t.get("function")
382
if not isinstance(fn, dict):
383
continue
384
name = fn.get("name")
385
if not isinstance(name, str) or not name:
386
continue
387
tool_names.append(name)
388
params = fn.get("parameters")
389
if isinstance(params, dict):
390
tool_schemas[name] = params
391
392
if tool_names:
393
# Only force JSON output when the caller hasn't requested a
394
# specific format. Some web providers reject/ignore this field.
395
if response_format is None:
396
response_format = {"type": "json"}
397
398
lines = [
399
*getattr(provider, "tool_support_prompts", []),
400
"You have access to the following tools. When you decide a tool is needed, "
401
"respond with ONLY a valid JSON object (no markdown, no explanation) in this format:",
402
'{"tool_calls": [{"name": "TOOL_NAME", "arguments": {}}]}',
403
"You may include multiple tool calls in the array. The `arguments` value MUST be "
404
"a JSON object matching the tool's parameter schema.",
405
"If no tool is needed, respond normally with plain text. Don't try to call a tool, simply respond only with the JSON object.",
406
f"Available tools: {', '.join(tool_names)}",
407
]
408
if tool_schemas:
358
359
normalized_tools = normalize_tool_defs(tools) if tools else []
360
tool_names: list[str] = [
361
t["function"]["name"]
362
for t in normalized_tools
363
if isinstance(t, dict) and t.get("function", {}).get("name")
364
]
365
366
if tool_names:
367
if response_format is None:
368
response_format = {"type": "json"}
369
370
lines = [
371
*getattr(provider, "tool_support_prompts", []),
372
"You have access to the following tools. When you decide a tool is needed, "
373
"respond with ONLY a valid JSON object (no markdown, no explanation) in this format:",
374
'{"tool_calls": [{"name": "TOOL_NAME", "arguments": {}}]}',
375
"You may include multiple tool calls in the array. The `arguments` value MUST be "
376
"a JSON object matching the tool's parameter schema.",
377
"If no tool is needed, respond normally with plain text. Don't try to call a tool, simply respond only with the JSON object.",
378
f"Available tools: {', '.join(tool_names)}",
379
]
380
for t in normalized_tools:
381
fn = t["function"]
382
desc = fn.get("description", "")
383
tool_str = f"- Tool `{fn['name']}`" + (f": {desc}" if desc else "")
384
lines.append(tool_str)
385
if fn.get("parameters"):
386
lines.append(
387
f" Parameter Schema: {json.dumps(fn['parameters'], ensure_ascii=True)}"
388
)
389
390
if tool_choice is not None:
391
if tool_choice == "required":
409
392
lines.append(
410
"Tool parameter schemas (JSON Schema): "
411
f"{json.dumps(tool_schemas, ensure_ascii=True)}"
393
"You MUST call at least one tool. Respond with the JSON tool-call object only."
412
394
)
413
if tool_choice is not None:
414
if tool_choice == "required":
415
lines.append(
416
"You MUST call at least one tool. Respond with the JSON tool-call object only."
417
)
418
elif tool_choice == "none":
419
lines.append(
420
"Do not call any tools. Respond with plain text only."
421
)
422
elif isinstance(tool_choice, dict):
423
fn = (
424
tool_choice.get("function")
425
if tool_choice.get("type") == "function"
426
else None
427
)
428
if isinstance(fn, dict) and fn.get("name"):
429
lines.append(f"You must call the tool `{fn['name']}`.")
430
else:
431
lines.append(f"Tool choice: {tool_choice}")
432
messages = [{"role": "system", "content": "\n".join(lines)}] + messages
433
434
# Rewrite any prior assistant tool_calls and tool-role response messages
435
# into readable text so the underlying web provider can follow the
436
# conversation history.
395
elif tool_choice == "none":
396
lines.append("Do not call any tools. Respond with plain text only.")
397
elif isinstance(tool_choice, dict):
398
fn = (
399
tool_choice.get("function")
400
if tool_choice.get("type") == "function"
401
else None
402
)
403
if isinstance(fn, dict) and fn.get("name"):
404
lines.append(f"You must call the tool `{fn['name']}`.")
405
else:
406
lines.append(f"Tool choice: {tool_choice}")
407
messages = [{"role": "system", "content": "\n".join(lines)}] + messages
408
437
409
messages = _preprocess_tool_messages(messages)
438
410
439
# When no conversation handle is provided, web-API providers (e.g. Qwen,
440
# Copilot) only forward the last user message to the server via
441
# ``get_last_user_message``, dropping all prior context. Merge the
442
# whole history into a single user message so the model still sees the
443
# full conversation.
444
411
if kwargs.get("conversation") is None:
445
412
messages = _merge_messages_to_single_user(messages)
446
413
@@ -460,16 +427,11 @@ class ToolSupportProvider(AsyncGeneratorProvider):
460
427
if isinstance(chunk, str):
461
428
content_chunks.append(chunk)
462
429
elif isinstance(chunk, Reasoning):
463
# Forward thinking output to the client; do not mix it into
464
# the content that will be parsed as a tool-call JSON.
465
430
yield chunk
466
431
elif isinstance(chunk, Usage):
467
432
yield chunk
468
433
has_usage = True
469
434
elif isinstance(chunk, FinishReason):
470
# Store the finish reason but keep consuming chunks so we don't
471
# miss trailing ``Usage`` / ``JsonConversation`` chunks that
472
# some providers (e.g. Qwen image-gen) emit *after* the finish.
473
435
finish = chunk
474
436
else:
475
437
yield chunk
@@ -483,83 +445,8 @@ class ToolSupportProvider(AsyncGeneratorProvider):
483
445
content = "".join(content_chunks)
484
446
485
447
if tool_names:
486
payload = filter_json(content)
487
obj = _parse_json_maybe(payload)
488
calls = None
489
if isinstance(obj, dict) and isinstance(obj.get("tool_calls"), list):
490
calls = obj.get("tool_calls")
491
elif isinstance(obj, dict) and ("name" in obj or "tool" in obj):
492
calls = [obj]
493
elif isinstance(obj, list):
494
calls = obj
495
496
openai_calls = []
497
if isinstance(calls, list):
498
idx = -1
499
for c in calls:
500
if not isinstance(c, dict):
501
continue
502
name = c.get("name") or c.get("tool")
503
if not isinstance(name, str) or not name or name not in tool_names:
504
continue
505
args = c.get("arguments")
506
if isinstance(args, str):
507
arguments_str = args
508
else:
509
try:
510
arguments_str = json.dumps(
511
args if isinstance(args, dict) else {},
512
ensure_ascii=True,
513
)
514
except Exception:
515
arguments_str = "{}"
516
idx += 1
517
openai_calls.append(
518
{
519
"index": idx,
520
"id": f"call_{idx}",
521
"type": "function",
522
"function": {"name": name, "arguments": arguments_str},
523
}
524
)
525
526
# Fallback: the model may have echoed back the stringified
527
# ``[Tool call: NAME] (id=ID)\nArguments: {JSON}`` format that
528
# ``_stringify_tool_calls`` produces instead of emitting a raw
529
# JSON tool-call object. Parse those too so the conversation can
530
# continue with real tool execution.
531
if not openai_calls:
532
stringified = _parse_stringified_tool_calls(content)
533
if stringified:
534
idx = -1
535
for c in stringified:
536
name = c.get("name")
537
if (
538
not isinstance(name, str)
539
or not name
540
or name not in tool_names
541
):
542
continue
543
args = c.get("arguments")
544
if isinstance(args, str):
545
arguments_str = args
546
else:
547
try:
548
arguments_str = json.dumps(
549
args if isinstance(args, dict) else {},
550
ensure_ascii=True,
551
)
552
except Exception:
553
arguments_str = "{}"
554
idx += 1
555
openai_calls.append(
556
{
557
"index": idx,
558
"id": f"call_{idx}",
559
"type": "function",
560
"function": {"name": name, "arguments": arguments_str},
561
}
562
)
448
parsed_calls = parse_tool_calls_from_text(content, tool_names)
449
openai_calls = normalize_tool_calls(parsed_calls)
563
450
564
451
if openai_calls:
565
452
yield ToolCalls(openai_calls)
@@ -43,9 +43,11 @@ from ..config import AppConfig
43
43
from .web_search import do_search, get_search_message
44
44
from .auth import AuthManager
45
45
from .files import read_bucket, get_bucket_dir
46
from .tool_support import normalize_tool_defs, normalize_tool_calls
46
47
from .. import debug
47
48
48
49
50
49
51
# ---- In-memory conversation cache -------------------------------------------
50
52
# Stores the ``JsonConversation`` session state yielded by the underlying
51
53
# provider, keyed by a hash of all messages except the last user message and the
@@ -338,11 +340,18 @@ async def async_iter_run_tools(
338
340
339
341
stream = bool(kwargs.get("stream"))
340
342
tools = kwargs.get("tools")
343
if tools:
344
tools = normalize_tool_defs(tools)
345
kwargs["tools"] = tools
346
if tool_calls:
347
tool_calls = normalize_tool_calls(tool_calls)
348
341
349
# Auto-enable tool emulation for providers without native tool support
342
350
# (i.e. web-API providers that are not OpenaiTemplate subclasses).
343
351
if tools and not tool_calls and not tool_emulation:
344
352
if not provider_supports_native_tools(provider):
345
353
tool_emulation = True
354
346
355
if tool_emulation and tools and not tool_calls:
347
356
from ..providers.tool_support import ToolSupportProvider
348
357
@@ -536,11 +545,18 @@ def iter_run_tools(
536
545
537
546
stream = bool(kwargs.get("stream"))
538
547
tools = kwargs.get("tools")
548
if tools:
549
tools = normalize_tool_defs(tools)
550
kwargs["tools"] = tools
551
if tool_calls:
552
tool_calls = normalize_tool_calls(tool_calls)
553
539
554
# Auto-enable tool emulation for providers without native tool support
540
555
# (i.e. web-API providers that are not OpenaiTemplate subclasses).
541
556
if tools and not tool_calls and not tool_emulation:
542
557
if not provider_supports_native_tools(provider):
543
558
tool_emulation = True
559
544
560
if tool_emulation and tools and not tool_calls:
545
561
from ..providers.tool_support import ToolSupportProvider
546
562