zyxtoworld commited on
Commit
1376667
·
1 Parent(s): 055c097

Add web search compatibility support

Browse files
README.md CHANGED
@@ -255,7 +255,7 @@ curl http://localhost:8000/v1/images/edits \
255
  <summary><code>POST /v1/chat/completions</code></summary>
256
  <br>
257
 
258
- 面向图片场景的 Chat Completions 兼容接口,不是完整通用聊天代理。
259
 
260
  ```bash
261
  curl http://localhost:8000/v1/chat/completions \
@@ -279,10 +279,12 @@ curl http://localhost:8000/v1/chat/completions \
279
 
280
  | 字段 | 说明 |
281
  |:-----------|:------------------|
282
- | `model` | 图片模型,默认按图片生成场景处理 |
283
- | `messages` | 消息数组,需要是图片相关请求内容 |
284
- | `n` | 生成数量,按当前实现解析为图片数量 |
285
- | `stream` | 已实现,但仍在测试 |
 
 
286
 
287
  <br>
288
  </details>
@@ -292,7 +294,7 @@ curl http://localhost:8000/v1/chat/completions \
292
  <summary><code>POST /v1/responses</code></summary>
293
  <br>
294
 
295
- 面向图片生成工具调用的 Responses API 兼容接口,不是完整通用 Responses API 代理。
296
 
297
  ```bash
298
  curl http://localhost:8000/v1/responses \
@@ -315,9 +317,9 @@ curl http://localhost:8000/v1/responses \
315
 
316
  | 字段 | 说明 |
317
  |:---------|:------------------------------|
318
- | `model` | 响应中会回显该模型字段,但图片生成当前仍走图片生成兼容逻辑 |
319
- | `input` | 输入内容,需要能解析出图片生成提示词 |
320
- | `tools` | 必须包含 `image_generation` 工具请求 |
321
  | `stream` | 已实现,但仍在测试 |
322
 
323
  <br>
 
255
  <summary><code>POST /v1/chat/completions</code></summary>
256
  <br>
257
 
258
+ 面向文本、网页搜索与图片场景的 Chat Completions 兼容接口,不是完整通用聊天代理。
259
 
260
  ```bash
261
  curl http://localhost:8000/v1/chat/completions \
 
279
 
280
  | 字段 | 说明 |
281
  |:-----------|:------------------|
282
+ | `model` | 文本、搜索或图片模型;搜索模型会触发网页搜索兼容逻辑 |
283
+ | `messages` | 消息数组,支持文本、搜索和图片请求内容 |
284
+ | `n` | 图片生成数量,按当前实现解析为图片数量 |
285
+ | `stream` | 文本、搜索和图片场景均支持,仍在测试 |
286
+ | `tools` | 文本场景支持 `web_search` / `web_search_preview` / `web_search_preview_2025_03_11` |
287
+ | `web_search_options` | 传入时会触发网页搜索兼容逻辑 |
288
 
289
  <br>
290
  </details>
 
294
  <summary><code>POST /v1/responses</code></summary>
295
  <br>
296
 
297
+ 面向文本、网页搜索和图片生成工具调用的 Responses API 兼容接口,不是完整通用 Responses API 代理。
298
 
299
  ```bash
300
  curl http://localhost:8000/v1/responses \
 
317
 
318
  | 字段 | 说明 |
319
  |:---------|:------------------------------|
320
+ | `model` | 响应中会回显该模型字段,搜索和图片生成会走对应兼容逻辑 |
321
+ | `input` | 输入内容;搜索使用最后一条用户文本,图片生成需能解析出提示词 |
322
+ | `tools` | 支持 `image_generation`、`web_search`、`web_search_preview`、`web_search_preview_2025_03_11` |
323
  | `stream` | 已实现,但仍在测试 |
324
 
325
  <br>
services/protocol/openai_v1_chat_complete.py CHANGED
@@ -21,6 +21,14 @@ from services.protocol.conversation import (
21
  stream_text_deltas,
22
  text_backend,
23
  )
 
 
 
 
 
 
 
 
24
  from utils.helper import build_chat_image_markdown_content, extract_chat_image, extract_chat_prompt, is_image_chat_request, parse_image_count
25
  from utils.image_tokens import (
26
  chat_usage_from_image_usage,
@@ -30,7 +38,7 @@ from utils.image_tokens import (
30
  )
31
 
32
  TOOL_UNAVAILABLE_SYSTEM_MESSAGE = (
33
- "This compatibility backend cannot execute local tools, shell commands, web searches, "
34
  "or file operations. Do not claim to have run tools or inspected external resources. "
35
  "If a user asks you to use a tool, say that tool execution is unavailable through this backend."
36
  )
@@ -51,11 +59,15 @@ def completion_response(
51
  content: str,
52
  created: int | None = None,
53
  messages: list[dict[str, Any]] | None = None,
 
54
  ) -> dict[str, Any]:
55
  prompt_text_tokens = count_message_text_tokens(messages, model) if messages else 0
56
  prompt_image_tokens = count_message_image_tokens(messages, model) if messages else 0
57
  prompt_tokens = prompt_text_tokens + prompt_image_tokens
58
  completion_tokens = count_text_tokens(content, model) if messages else 0
 
 
 
59
  return {
60
  "id": f"chatcmpl-{uuid.uuid4().hex}",
61
  "object": "chat.completion",
@@ -63,7 +75,7 @@ def completion_response(
63
  "model": model,
64
  "choices": [{
65
  "index": 0,
66
- "message": {"role": "assistant", "content": content},
67
  "finish_reason": "stop",
68
  }],
69
  "usage": {
@@ -137,12 +149,52 @@ def chat_image_args(body: dict[str, Any]) -> tuple[str, str, int, list[tuple[byt
137
  def text_chat_parts(body: dict[str, Any]) -> tuple[str, list[dict[str, Any]]]:
138
  model = str(body.get("model") or "auto").strip() or "auto"
139
  messages = normalize_text_messages(normalize_messages(chat_messages_from_body(body)))
140
- tools = body.get("tools")
141
- if isinstance(tools, list) and tools:
142
  messages.insert(0, {"role": "system", "content": TOOL_UNAVAILABLE_SYSTEM_MESSAGE})
143
  return model, messages
144
 
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  def image_result_content(result: dict[str, Any]) -> str:
147
  data = result.get("data")
148
  if isinstance(data, list) and data:
@@ -212,6 +264,8 @@ def handle(body: dict[str, Any]) -> dict[str, Any] | Iterator[dict[str, Any]]:
212
  if is_image_chat_request(body):
213
  return image_chat_events(body)
214
  model, messages = text_chat_parts(body)
 
 
215
  key = cache_key(body, messages, stream=True)
216
  return chat_completion_cache.get_or_compute_stream(
217
  key,
@@ -220,6 +274,8 @@ def handle(body: dict[str, Any]) -> dict[str, Any] | Iterator[dict[str, Any]]:
220
  if is_image_chat_request(body):
221
  return image_chat_response(body)
222
  model, messages = text_chat_parts(body)
 
 
223
  key = cache_key(body, messages, stream=False)
224
  return chat_completion_cache.get_or_compute_response(
225
  key,
 
21
  stream_text_deltas,
22
  text_backend,
23
  )
24
+ from services.protocol.web_search_tool import (
25
+ WEB_SEARCH_TOOL_TYPES,
26
+ has_unsupported_tools,
27
+ is_web_search_chat_request,
28
+ run_web_search,
29
+ search_query_from_messages,
30
+ text_with_url_citations,
31
+ )
32
  from utils.helper import build_chat_image_markdown_content, extract_chat_image, extract_chat_prompt, is_image_chat_request, parse_image_count
33
  from utils.image_tokens import (
34
  chat_usage_from_image_usage,
 
38
  )
39
 
40
  TOOL_UNAVAILABLE_SYSTEM_MESSAGE = (
41
+ "This compatibility backend cannot execute local tools, shell commands, non-search tools, "
42
  "or file operations. Do not claim to have run tools or inspected external resources. "
43
  "If a user asks you to use a tool, say that tool execution is unavailable through this backend."
44
  )
 
59
  content: str,
60
  created: int | None = None,
61
  messages: list[dict[str, Any]] | None = None,
62
+ annotations: list[dict[str, Any]] | None = None,
63
  ) -> dict[str, Any]:
64
  prompt_text_tokens = count_message_text_tokens(messages, model) if messages else 0
65
  prompt_image_tokens = count_message_image_tokens(messages, model) if messages else 0
66
  prompt_tokens = prompt_text_tokens + prompt_image_tokens
67
  completion_tokens = count_text_tokens(content, model) if messages else 0
68
+ message = {"role": "assistant", "content": content}
69
+ if annotations:
70
+ message["annotations"] = annotations
71
  return {
72
  "id": f"chatcmpl-{uuid.uuid4().hex}",
73
  "object": "chat.completion",
 
75
  "model": model,
76
  "choices": [{
77
  "index": 0,
78
+ "message": message,
79
  "finish_reason": "stop",
80
  }],
81
  "usage": {
 
149
  def text_chat_parts(body: dict[str, Any]) -> tuple[str, list[dict[str, Any]]]:
150
  model = str(body.get("model") or "auto").strip() or "auto"
151
  messages = normalize_text_messages(normalize_messages(chat_messages_from_body(body)))
152
+ if has_unsupported_tools(body, WEB_SEARCH_TOOL_TYPES):
 
153
  messages.insert(0, {"role": "system", "content": TOOL_UNAVAILABLE_SYSTEM_MESSAGE})
154
  return model, messages
155
 
156
 
157
+ def chat_completion_annotations(annotations: list[dict[str, Any]]) -> list[dict[str, Any]]:
158
+ output = []
159
+ for item in annotations:
160
+ if item.get("type") != "url_citation":
161
+ continue
162
+ output.append({
163
+ "type": "url_citation",
164
+ "url_citation": {
165
+ "start_index": item.get("start_index", 0),
166
+ "end_index": item.get("end_index", 0),
167
+ "url": item.get("url", ""),
168
+ "title": item.get("title", ""),
169
+ },
170
+ })
171
+ return output
172
+
173
+
174
+ def web_search_chat_response(messages: list[dict[str, Any]], model: str) -> dict[str, Any]:
175
+ query = search_query_from_messages(messages)
176
+ if not query:
177
+ raise HTTPException(status_code=400, detail={"error": "messages or prompt is required for web search"})
178
+ text, annotations = text_with_url_citations(run_web_search(query))
179
+ return completion_response(
180
+ model,
181
+ text,
182
+ messages=messages,
183
+ annotations=chat_completion_annotations(annotations),
184
+ )
185
+
186
+
187
+ def stream_web_search_chat_completion(messages: list[dict[str, Any]], model: str) -> Iterator[dict[str, Any]]:
188
+ query = search_query_from_messages(messages)
189
+ if not query:
190
+ raise HTTPException(status_code=400, detail={"error": "messages or prompt is required for web search"})
191
+ text, _annotations = text_with_url_citations(run_web_search(query))
192
+ completion_id = f"chatcmpl-{uuid.uuid4().hex}"
193
+ created = int(time.time())
194
+ yield completion_chunk(model, {"role": "assistant", "content": text}, None, completion_id, created)
195
+ yield completion_chunk(model, {}, "stop", completion_id, created)
196
+
197
+
198
  def image_result_content(result: dict[str, Any]) -> str:
199
  data = result.get("data")
200
  if isinstance(data, list) and data:
 
264
  if is_image_chat_request(body):
265
  return image_chat_events(body)
266
  model, messages = text_chat_parts(body)
267
+ if is_web_search_chat_request(body) and not has_unsupported_tools(body, WEB_SEARCH_TOOL_TYPES):
268
+ return stream_web_search_chat_completion(messages, model)
269
  key = cache_key(body, messages, stream=True)
270
  return chat_completion_cache.get_or_compute_stream(
271
  key,
 
274
  if is_image_chat_request(body):
275
  return image_chat_response(body)
276
  model, messages = text_chat_parts(body)
277
+ if is_web_search_chat_request(body) and not has_unsupported_tools(body, WEB_SEARCH_TOOL_TYPES):
278
+ return web_search_chat_response(messages, model)
279
  key = cache_key(body, messages, stream=False)
280
  return chat_completion_cache.get_or_compute_response(
281
  key,
services/protocol/openai_v1_response.py CHANGED
@@ -19,6 +19,15 @@ from services.protocol.conversation import (
19
  stream_text_deltas,
20
  text_backend,
21
  )
 
 
 
 
 
 
 
 
 
22
  from utils.helper import extract_image_from_message_content, extract_response_prompt, has_response_image_generation_tool
23
  from utils.image_tokens import (
24
  count_image_content_tokens,
@@ -28,7 +37,7 @@ from utils.image_tokens import (
28
  )
29
 
30
  TOOL_UNAVAILABLE_SYSTEM_MESSAGE = (
31
- "This compatibility backend cannot execute local tools, shell commands, web searches, "
32
  "or file operations. Do not claim to have run tools or inspected external resources. "
33
  "If a user asks you to use a tool, say that tool execution is unavailable through this backend."
34
  )
@@ -40,14 +49,8 @@ def is_text_response_request(body: dict[str, Any]) -> bool:
40
  return not has_response_image_generation_tool(body)
41
 
42
 
43
- def has_non_image_tools(body: dict[str, Any]) -> bool:
44
- tools = body.get("tools")
45
- if not isinstance(tools, list):
46
- return False
47
- return any(
48
- isinstance(tool, dict) and str(tool.get("type") or "").strip() != "image_generation"
49
- for tool in tools
50
- )
51
 
52
 
53
  def response_image_tool(body: dict[str, Any]) -> dict[str, object]:
@@ -165,13 +168,43 @@ def messages_from_input(input_value: object, instructions: object = None) -> lis
165
  return messages
166
 
167
 
168
- def text_output_item(text: str, item_id: str | None = None, status: str = "completed") -> dict[str, Any]:
 
 
 
 
 
169
  return {
170
  "id": item_id or f"msg_{uuid.uuid4().hex}",
171
  "type": "message",
172
  "status": status,
173
  "role": "assistant",
174
- "content": [{"type": "output_text", "text": text, "annotations": []}],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  }
176
 
177
 
@@ -236,7 +269,7 @@ def response_completed(
236
  def text_response_parts(body: dict[str, Any]) -> tuple[str, list[dict[str, Any]]]:
237
  model = str(body.get("model") or "auto").strip() or "auto"
238
  messages = normalize_text_messages(normalize_messages(messages_from_input(body.get("input"), body.get("instructions"))))
239
- if has_non_image_tools(body):
240
  messages.insert(0, {"role": "system", "content": TOOL_UNAVAILABLE_SYSTEM_MESSAGE})
241
  return model, messages
242
 
@@ -265,6 +298,44 @@ def stream_text_response(backend, body: dict[str, Any], messages: list[dict[str,
265
  yield response_completed(response_id, model, created, [item], usage)
266
 
267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  def stream_image_response(
269
  image_outputs: Iterable[ImageOutput],
270
  prompt: str,
@@ -319,6 +390,9 @@ def collect_response(events: Iterable[dict[str, Any]]) -> dict[str, Any]:
319
  def response_events(body: dict[str, Any]) -> Iterator[dict[str, Any]]:
320
  if is_text_response_request(body):
321
  model, messages = text_response_parts(body)
 
 
 
322
  key = cache_key(body, messages, stream=bool(body.get("stream")))
323
  yield from chat_completion_cache.get_or_compute_stream(
324
  key,
 
19
  stream_text_deltas,
20
  text_backend,
21
  )
22
+ from services.protocol.web_search_tool import (
23
+ WEB_SEARCH_TOOL_TYPES,
24
+ has_unsupported_tools,
25
+ has_web_search_tool,
26
+ normalized_sources,
27
+ run_web_search,
28
+ search_query_from_messages,
29
+ text_with_url_citations,
30
+ )
31
  from utils.helper import extract_image_from_message_content, extract_response_prompt, has_response_image_generation_tool
32
  from utils.image_tokens import (
33
  count_image_content_tokens,
 
37
  )
38
 
39
  TOOL_UNAVAILABLE_SYSTEM_MESSAGE = (
40
+ "This compatibility backend cannot execute local tools, shell commands, non-search tools, "
41
  "or file operations. Do not claim to have run tools or inspected external resources. "
42
  "If a user asks you to use a tool, say that tool execution is unavailable through this backend."
43
  )
 
49
  return not has_response_image_generation_tool(body)
50
 
51
 
52
+ def has_unsupported_response_tools(body: dict[str, Any]) -> bool:
53
+ return has_unsupported_tools(body, {"image_generation", *WEB_SEARCH_TOOL_TYPES})
 
 
 
 
 
 
54
 
55
 
56
  def response_image_tool(body: dict[str, Any]) -> dict[str, object]:
 
168
  return messages
169
 
170
 
171
+ def text_output_item(
172
+ text: str,
173
+ item_id: str | None = None,
174
+ status: str = "completed",
175
+ annotations: list[dict[str, Any]] | None = None,
176
+ ) -> dict[str, Any]:
177
  return {
178
  "id": item_id or f"msg_{uuid.uuid4().hex}",
179
  "type": "message",
180
  "status": status,
181
  "role": "assistant",
182
+ "content": [{"type": "output_text", "text": text, "annotations": annotations or []}],
183
+ }
184
+
185
+
186
+ def web_search_call_item(
187
+ query: str,
188
+ item_id: str | None = None,
189
+ status: str = "completed",
190
+ sources: list[dict[str, str]] | None = None,
191
+ ) -> dict[str, Any]:
192
+ action: dict[str, Any] = {
193
+ "type": "search",
194
+ "query": query,
195
+ "queries": [query],
196
+ }
197
+ if sources:
198
+ action["sources"] = [
199
+ {"type": "url", "url": source["url"]}
200
+ for source in sources
201
+ if source.get("url")
202
+ ]
203
+ return {
204
+ "id": item_id or f"ws_{uuid.uuid4().hex}",
205
+ "type": "web_search_call",
206
+ "status": status,
207
+ "action": action,
208
  }
209
 
210
 
 
269
  def text_response_parts(body: dict[str, Any]) -> tuple[str, list[dict[str, Any]]]:
270
  model = str(body.get("model") or "auto").strip() or "auto"
271
  messages = normalize_text_messages(normalize_messages(messages_from_input(body.get("input"), body.get("instructions"))))
272
+ if has_unsupported_response_tools(body):
273
  messages.insert(0, {"role": "system", "content": TOOL_UNAVAILABLE_SYSTEM_MESSAGE})
274
  return model, messages
275
 
 
298
  yield response_completed(response_id, model, created, [item], usage)
299
 
300
 
301
+ def stream_web_search_response(body: dict[str, Any], messages: list[dict[str, Any]] | None = None) -> Iterator[dict[str, Any]]:
302
+ model = str(body.get("model") or "auto").strip() or "auto"
303
+ messages = messages if messages is not None else messages_from_input(body.get("input"), body.get("instructions"))
304
+ query = search_query_from_messages(messages) or extract_response_prompt(body.get("input"))
305
+ if not query:
306
+ raise HTTPException(status_code=400, detail={"error": "input text is required for web_search"})
307
+
308
+ response_id = f"resp_{uuid.uuid4().hex}"
309
+ search_id = f"ws_{uuid.uuid4().hex}"
310
+ item_id = f"msg_{uuid.uuid4().hex}"
311
+ created = int(time.time())
312
+ yield response_created(response_id, model, created)
313
+
314
+ searching_item = web_search_call_item(query, search_id, "in_progress")
315
+ yield {"type": "response.output_item.added", "output_index": 0, "item": searching_item}
316
+ yield {"type": "response.web_search_call.in_progress", "output_index": 0, "item_id": search_id}
317
+ yield {"type": "response.web_search_call.searching", "output_index": 0, "item_id": search_id}
318
+ result = run_web_search(query)
319
+ search_item = web_search_call_item(query, search_id, "completed", normalized_sources(result))
320
+ yield {"type": "response.web_search_call.completed", "output_index": 0, "item_id": search_id}
321
+ yield {"type": "response.output_item.done", "output_index": 0, "item": search_item}
322
+
323
+ text, annotations = text_with_url_citations(result)
324
+ message_item = text_output_item("", item_id, "in_progress", annotations)
325
+ yield {"type": "response.output_item.added", "output_index": 1, "item": message_item}
326
+ if text:
327
+ yield {"type": "response.output_text.delta", "item_id": item_id, "output_index": 1, "content_index": 0, "delta": text}
328
+ yield {"type": "response.output_text.done", "item_id": item_id, "output_index": 1, "content_index": 0, "text": text}
329
+ message_item = text_output_item(text, item_id, "completed", annotations)
330
+ yield {"type": "response.output_item.done", "output_index": 1, "item": message_item}
331
+ usage = token_usage(
332
+ input_text_tokens=count_message_text_tokens(messages, model),
333
+ input_image_tokens=count_message_image_tokens(messages, model),
334
+ output_text_tokens=count_text_tokens(text, model),
335
+ )
336
+ yield response_completed(response_id, model, created, [search_item, message_item], usage)
337
+
338
+
339
  def stream_image_response(
340
  image_outputs: Iterable[ImageOutput],
341
  prompt: str,
 
390
  def response_events(body: dict[str, Any]) -> Iterator[dict[str, Any]]:
391
  if is_text_response_request(body):
392
  model, messages = text_response_parts(body)
393
+ if has_web_search_tool(body) and not has_unsupported_response_tools(body):
394
+ yield from stream_web_search_response(body, messages)
395
+ return
396
  key = cache_key(body, messages, stream=bool(body.get("stream")))
397
  yield from chat_completion_cache.get_or_compute_stream(
398
  key,
services/protocol/web_search_tool.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any
5
+
6
+ from services.account_service import account_service
7
+ from services.openai_backend_api import OpenAIBackendAPI
8
+
9
+ WEB_SEARCH_TOOL_TYPES = {"web_search", "web_search_preview", "web_search_preview_2025_03_11"}
10
+ SEARCH_CHAT_MODEL_PREFIXES = (
11
+ "gpt-4o-search-preview",
12
+ "gpt-4o-mini-search-preview",
13
+ "gpt-5-search-api",
14
+ )
15
+
16
+
17
+ def _tool_type(tool: object) -> str:
18
+ return str(tool.get("type") or "").strip() if isinstance(tool, dict) else ""
19
+
20
+
21
+ def has_web_search_tool(body: dict[str, Any]) -> bool:
22
+ tools = body.get("tools")
23
+ if isinstance(tools, list):
24
+ return any(_tool_type(tool) in WEB_SEARCH_TOOL_TYPES for tool in tools)
25
+ tool_choice = body.get("tool_choice")
26
+ return _tool_type(tool_choice) in WEB_SEARCH_TOOL_TYPES
27
+
28
+
29
+ def is_web_search_chat_request(body: dict[str, Any]) -> bool:
30
+ model = str(body.get("model") or "").strip()
31
+ return (
32
+ has_web_search_tool(body)
33
+ or isinstance(body.get("web_search_options"), dict)
34
+ or any(
35
+ model == prefix or model.startswith(f"{prefix}-")
36
+ for prefix in SEARCH_CHAT_MODEL_PREFIXES
37
+ )
38
+ )
39
+
40
+
41
+ def has_unsupported_tools(body: dict[str, Any], allowed_types: set[str]) -> bool:
42
+ tools = body.get("tools")
43
+ if not isinstance(tools, list):
44
+ return False
45
+ return any(_tool_type(tool) not in allowed_types for tool in tools if isinstance(tool, dict))
46
+
47
+
48
+ def message_text(value: object) -> str:
49
+ if isinstance(value, str):
50
+ return value.strip()
51
+ if isinstance(value, list):
52
+ parts: list[str] = []
53
+ for item in value:
54
+ if isinstance(item, str):
55
+ text = item.strip()
56
+ elif isinstance(item, dict):
57
+ text = str(item.get("text") or item.get("input_text") or "").strip()
58
+ else:
59
+ text = ""
60
+ if text:
61
+ parts.append(text)
62
+ return "\n".join(parts).strip()
63
+ return ""
64
+
65
+
66
+ def search_query_from_messages(messages: list[dict[str, Any]]) -> str:
67
+ for message in reversed(messages):
68
+ if str(message.get("role") or "").strip().lower() != "user":
69
+ continue
70
+ text = message_text(message.get("content"))
71
+ if text:
72
+ return text
73
+ return ""
74
+
75
+
76
+ def _readable_annotation_part(parts: list[str]) -> str:
77
+ for part in parts:
78
+ value = part.strip()
79
+ lower = value.lower()
80
+ if value and not (
81
+ lower.startswith(("turn", "source", "sources"))
82
+ or re.fullmatch(r"\d+", value)
83
+ ):
84
+ return value
85
+ return ""
86
+
87
+
88
+ def clean_search_text(text: str) -> str:
89
+ def replace_annotation(match: re.Match[str]) -> str:
90
+ parts = [part.strip() for part in match.group(1).split("\ue202")]
91
+ kind = (parts[0] if parts else "").lower()
92
+ data = parts[1:]
93
+ if kind == "url":
94
+ label = data[0] if data else ""
95
+ url = data[1] if len(data) > 1 else ""
96
+ if label and url.startswith(("http://", "https://")):
97
+ return f"{label} ({url})"
98
+ return label or url
99
+ if kind == "cite":
100
+ return _readable_annotation_part(data)
101
+ return _readable_annotation_part(data)
102
+
103
+ text = re.sub(r"\ue200([^\ue201]*)\ue201", replace_annotation, text)
104
+ text = re.sub(r"\ue200[^\ue201]*$", "", text)
105
+ return re.sub(r"\s+([.,;:!?])", r"\1", text).strip()
106
+
107
+
108
+ def normalized_sources(result: dict[str, Any]) -> list[dict[str, str]]:
109
+ sources = result.get("sources")
110
+ if not isinstance(sources, list):
111
+ return []
112
+ output: list[dict[str, str]] = []
113
+ seen: set[str] = set()
114
+ for item in sources:
115
+ if not isinstance(item, dict):
116
+ continue
117
+ url = str(item.get("url") or "").strip()
118
+ title = str(item.get("title") or "").strip()
119
+ snippet = str(item.get("snippet") or "").strip()
120
+ if not url or url in seen:
121
+ continue
122
+ seen.add(url)
123
+ output.append({"title": title, "url": url, "snippet": snippet})
124
+ return output
125
+
126
+
127
+ def text_with_url_citations(result: dict[str, Any]) -> tuple[str, list[dict[str, Any]]]:
128
+ text = clean_search_text(str(result.get("answer") or ""))
129
+ annotations: list[dict[str, Any]] = []
130
+ sources = normalized_sources(result)
131
+ if sources:
132
+ text = text.rstrip()
133
+ if text:
134
+ text += "\n\n"
135
+ text += "Sources:\n"
136
+ for index, source in enumerate(sources, start=1):
137
+ title = source["title"] or source["url"]
138
+ line_prefix = f"{index}. {title}"
139
+ text += line_prefix
140
+ if source["url"]:
141
+ if source["title"]:
142
+ text += " - "
143
+ start = len(text)
144
+ text += source["url"]
145
+ annotations.append({
146
+ "type": "url_citation",
147
+ "start_index": start,
148
+ "end_index": len(text),
149
+ "url": source["url"],
150
+ "title": source["title"] or source["url"],
151
+ })
152
+ text += "\n"
153
+ return text.strip(), annotations
154
+
155
+
156
+ def run_web_search(query: str) -> dict[str, Any]:
157
+ token = account_service.get_text_access_token()
158
+ result = OpenAIBackendAPI(token).search(query)
159
+ account_service.mark_text_used(token)
160
+ return result
test/test_chat_completion_cache.py CHANGED
@@ -237,6 +237,142 @@ class ChatCompletionCacheTests(unittest.TestCase):
237
  self.assertEqual(messages[0]["role"], "system")
238
  self.assertIn("cannot execute local tools", str(messages[0]["content"]))
239
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  def test_chat_completions_accepts_remote_image_url(self) -> None:
241
  class FakeImageResponse:
242
  status_code = 200
 
237
  self.assertEqual(messages[0]["role"], "system")
238
  self.assertIn("cannot execute local tools", str(messages[0]["content"]))
239
 
240
+ def test_responses_web_search_tool_returns_search_output(self) -> None:
241
+ search_result = {
242
+ "answer": "Latest answer.",
243
+ "sources": [{"title": "Example", "url": "https://example.com/news", "snippet": "Snippet"}],
244
+ }
245
+ body = {
246
+ "model": "auto",
247
+ "input": "latest example news",
248
+ "tools": [{"type": "web_search"}],
249
+ }
250
+
251
+ with mock.patch("services.protocol.openai_v1_response.run_web_search", return_value=search_result) as search:
252
+ response = openai_v1_response.handle(body)
253
+
254
+ search.assert_called_once_with("latest example news")
255
+ self.assertEqual(response["output"][0]["type"], "web_search_call")
256
+ self.assertEqual(response["output"][0]["status"], "completed")
257
+ self.assertEqual(response["output"][0]["action"]["query"], "latest example news")
258
+ message = response["output"][1]
259
+ self.assertEqual(message["type"], "message")
260
+ content = message["content"][0]
261
+ self.assertIn("Latest answer.", content["text"])
262
+ self.assertEqual(content["annotations"][0]["type"], "url_citation")
263
+ self.assertEqual(content["annotations"][0]["url"], "https://example.com/news")
264
+
265
+ def test_responses_web_search_tool_streams_search_events(self) -> None:
266
+ search_result = {
267
+ "answer": "Streamed search answer.",
268
+ "sources": [{"title": "Example", "url": "https://example.com/stream", "snippet": ""}],
269
+ }
270
+ body = {
271
+ "model": "auto",
272
+ "stream": True,
273
+ "input": "stream search",
274
+ "tools": [{"type": "web_search_preview"}],
275
+ }
276
+
277
+ with mock.patch("services.protocol.openai_v1_response.run_web_search", return_value=search_result):
278
+ events = list(openai_v1_response.handle(body))
279
+
280
+ event_types = [event["type"] for event in events]
281
+ self.assertIn("response.web_search_call.in_progress", event_types)
282
+ self.assertIn("response.web_search_call.searching", event_types)
283
+ self.assertIn("response.web_search_call.completed", event_types)
284
+ completed = events[-1]["response"]
285
+ self.assertEqual(completed["output"][0]["type"], "web_search_call")
286
+ self.assertEqual(completed["output"][1]["type"], "message")
287
+
288
+ def test_responses_versioned_web_search_tool_returns_search_output(self) -> None:
289
+ search_result = {
290
+ "answer": "Versioned search answer.",
291
+ "sources": [{"title": "Example", "url": "https://example.com/versioned", "snippet": ""}],
292
+ }
293
+ body = {
294
+ "model": "auto",
295
+ "input": "versioned search",
296
+ "tools": [{"type": "web_search_preview_2025_03_11"}],
297
+ }
298
+
299
+ with mock.patch("services.protocol.openai_v1_response.run_web_search", return_value=search_result) as search:
300
+ response = openai_v1_response.handle(body)
301
+
302
+ search.assert_called_once_with("versioned search")
303
+ self.assertEqual(response["output"][0]["type"], "web_search_call")
304
+ self.assertIn("Versioned search answer.", response["output"][1]["content"][0]["text"])
305
+
306
+ def test_chat_completions_web_search_tool_returns_search_answer(self) -> None:
307
+ search_result = {
308
+ "answer": "Chat search answer.",
309
+ "sources": [{"title": "Example", "url": "https://example.com/chat", "snippet": ""}],
310
+ }
311
+ body = {
312
+ "model": "auto",
313
+ "messages": [{"role": "user", "content": "search chat"}],
314
+ "tools": [{"type": "web_search"}],
315
+ }
316
+
317
+ with mock.patch("services.protocol.openai_v1_chat_complete.run_web_search", return_value=search_result) as search:
318
+ response = openai_v1_chat_complete.handle(body)
319
+
320
+ search.assert_called_once_with("search chat")
321
+ message = response["choices"][0]["message"]
322
+ self.assertIn("Chat search answer.", message["content"])
323
+ self.assertEqual(message["annotations"][0]["type"], "url_citation")
324
+ self.assertEqual(message["annotations"][0]["url_citation"]["url"], "https://example.com/chat")
325
+
326
+ def test_chat_completions_web_search_options_trigger_search(self) -> None:
327
+ search_result = {
328
+ "answer": "Options search answer.",
329
+ "sources": [{"title": "Example", "url": "https://example.com/options", "snippet": ""}],
330
+ }
331
+ body = {
332
+ "model": "auto",
333
+ "messages": [{"role": "user", "content": "search options"}],
334
+ "web_search_options": {"search_context_size": "low"},
335
+ }
336
+
337
+ with mock.patch("services.protocol.openai_v1_chat_complete.run_web_search", return_value=search_result) as search:
338
+ response = openai_v1_chat_complete.handle(body)
339
+
340
+ search.assert_called_once_with("search options")
341
+ self.assertIn("Options search answer.", response["choices"][0]["message"]["content"])
342
+
343
+ def test_chat_completions_search_model_triggers_search(self) -> None:
344
+ search_result = {
345
+ "answer": "Search model answer.",
346
+ "sources": [{"title": "Example", "url": "https://example.com/model", "snippet": ""}],
347
+ }
348
+ body = {
349
+ "model": "gpt-5-search-api-2026-06-01",
350
+ "messages": [{"role": "user", "content": "search model"}],
351
+ }
352
+
353
+ with mock.patch("services.protocol.openai_v1_chat_complete.run_web_search", return_value=search_result) as search:
354
+ response = openai_v1_chat_complete.handle(body)
355
+
356
+ search.assert_called_once_with("search model")
357
+ self.assertEqual(response["model"], "gpt-5-search-api-2026-06-01")
358
+ self.assertIn("Search model answer.", response["choices"][0]["message"]["content"])
359
+
360
+ def test_chat_completions_search_like_model_does_not_trigger_search(self) -> None:
361
+ body = {
362
+ "model": "gpt-5-search-apiary",
363
+ "messages": [{"role": "user", "content": "not actually a search model"}],
364
+ }
365
+
366
+ with (
367
+ mock.patch("services.protocol.openai_v1_chat_complete.run_web_search") as search,
368
+ mock.patch("services.protocol.openai_v1_chat_complete.text_backend", return_value=object()),
369
+ mock.patch("services.protocol.openai_v1_chat_complete.collect_text", return_value="plain text answer"),
370
+ ):
371
+ response = openai_v1_chat_complete.handle(body)
372
+
373
+ search.assert_not_called()
374
+ self.assertIn("plain text answer", response["choices"][0]["message"]["content"])
375
+
376
  def test_chat_completions_accepts_remote_image_url(self) -> None:
377
  class FakeImageResponse:
378
  status_code = 200