MCPcopy Create free account
hub / github.com/ZyphrZero/z.ai2api_python / _preprocess_openai_messages

Function _preprocess_openai_messages

app/core/upstream.py:296–348  ·  view source on GitHub ↗

Normalize OpenAI history into shapes accepted by the upstream service.

(
    messages: List[Dict[str, Any]],
)

Source from the content-addressed store, hash-verified

294
295
296def _preprocess_openai_messages(
297 messages: List[Dict[str, Any]],
298) -> List[Dict[str, Any]]:
299 """Normalize OpenAI history into shapes accepted by the upstream service."""
300 tool_call_index = _build_tool_call_index(messages)
301 normalized: List[Dict[str, Any]] = []
302
303 for message in messages:
304 if not isinstance(message, dict):
305 continue
306
307 role = message.get("role")
308
309 if role == "developer":
310 converted = dict(message)
311 converted["role"] = "system"
312 normalized.append(converted)
313 continue
314
315 if role == "tool":
316 tool_call_id = message.get("tool_call_id")
317 content = _extract_text_from_content(message.get("content"))
318 tool_info = tool_call_index.get(
319 tool_call_id,
320 {
321 "name": str(message.get("name") or "unknown_tool"),
322 "arguments": "{}",
323 },
324 )
325 normalized.append(
326 {
327 "role": "user",
328 "content": _format_tool_result_message(
329 tool_info["name"],
330 tool_info["arguments"],
331 content,
332 ),
333 }
334 )
335 continue
336
337 if role == "assistant" and isinstance(message.get("tool_calls"), list):
338 content = _extract_text_from_content(message.get("content"))
339 tool_calls_text = _format_assistant_tool_calls(message["tool_calls"])
340 merged_content = "\n".join(
341 part for part in (content, tool_calls_text) if part
342 ).strip()
343 normalized.append({"role": "assistant", "content": merged_content})
344 continue
345
346 normalized.append(dict(message))
347
348 return normalized
349
350
351def _extract_last_user_text(messages: List[Dict[str, Any]]) -> str:

Callers 1

transform_requestMethod · 0.85

Calls 4

_build_tool_call_indexFunction · 0.85

Tested by

no test coverage detected