2727
2828import asyncio
2929import json
30+ import os
3031from typing import Any , AsyncIterator
3132
3233import litellm
6263)
6364
6465
66+ def _shim_num_retries () -> int :
67+ """Backend retry count for transient errors (429/5xx/overloaded/timeout).
68+
69+ Previously the backend call used ``num_retries=0`` with no timeout, so a
70+ transient Ark error or a stalled connection failed the turn outright and
71+ the eval client's read timeout (default 300s) fired before any recovery.
72+ Retrying lets litellm apply its built-in exponential backoff. Env-tunable
73+ via ``CODEX_SHIM_NUM_RETRIES`` (default 2).
74+ """
75+ try :
76+ return max (0 , int (os .getenv ("CODEX_SHIM_NUM_RETRIES" , "2" )))
77+ except ValueError :
78+ return 2
79+
80+
81+ def _shim_timeout () -> float :
82+ """Per-backend-call timeout (seconds) so a hung connection cannot exhaust
83+ the whole client budget. ``0``/unset keeps litellm's default. Env-tunable
84+ via ``CODEX_SHIM_TIMEOUT``.
85+ """
86+ try :
87+ return max (0.0 , float (os .getenv ("CODEX_SHIM_TIMEOUT" , "0" )))
88+ except ValueError :
89+ return 0.0
90+
91+
92+ def _shim_max_tool_iters () -> int :
93+ """Max shim-internal web tool round-trips per request (``0`` = disabled).
94+
95+ Codex only speaks the Responses API and its hosted ``web_search`` tool is
96+ stripped before Ark (Ark rejects its schema), so a Codex+Ark agent has no
97+ web capability. When this is > 0, the shim translates the hosted web tools
98+ into Ark-accepted ``function`` tools, executes the veADK builtins itself,
99+ and loops until the model stops calling them. Default ``0`` keeps the path
100+ byte-identical to before. Env-tunable via ``CODEX_SHIM_MAX_TOOL_ITERS``
101+ (recommended 6 when enabling).
102+ """
103+ try :
104+ return max (0 , int (os .getenv ("CODEX_SHIM_MAX_TOOL_ITERS" , "0" )))
105+ except ValueError :
106+ return 0
107+
108+
109+ # Hosted web tools (Codex emits these; Ark rejects their schema) translated to
110+ # plain Responses ``function`` tools that the shim executes against veADK's own
111+ # builtins. Kept minimal — the builtins own the real parameter handling.
112+ _EXECUTABLE_TOOLS : list [dict [str , Any ]] = [
113+ {
114+ "type" : "function" ,
115+ "name" : "web_search" ,
116+ "description" : "Search the web for a query and return result documents." ,
117+ "parameters" : {
118+ "type" : "object" ,
119+ "properties" : {
120+ "query" : {"type" : "string" , "description" : "The search query." }
121+ },
122+ "required" : ["query" ],
123+ },
124+ },
125+ {
126+ "type" : "function" ,
127+ "name" : "web_fetch" ,
128+ "description" : (
129+ "Fetch a public web page or PDF over HTTP(S) and return its "
130+ "readable main content."
131+ ),
132+ "parameters" : {
133+ "type" : "object" ,
134+ "properties" : {
135+ "url" : {"type" : "string" , "description" : "The http(s) URL to fetch." },
136+ "extract_mode" : {
137+ "type" : "string" ,
138+ "enum" : ["markdown" , "text" ],
139+ "description" : "Output format; defaults to markdown." ,
140+ },
141+ "max_chars" : {
142+ "type" : "integer" ,
143+ "description" : "Truncate content to at most this many chars." ,
144+ },
145+ },
146+ "required" : ["url" ],
147+ },
148+ },
149+ ]
150+
151+ _EXECUTABLE_TOOL_NAMES = {t ["name" ] for t in _EXECUTABLE_TOOLS }
152+
153+
154+ async def _run_tool (name : str , args : dict [str , Any ]) -> str :
155+ """Execute a veADK built-in web tool and return a JSON string.
156+
157+ The web builtins use blocking ``requests``, so they run in a worker thread
158+ to avoid stalling the shim's event loop. Any error is returned as a JSON
159+ payload (never raised) so the model can recover on the next turn.
160+ """
161+ try :
162+ from veadk .tools import get_builtin_tool
163+
164+ fn = get_builtin_tool (name )
165+ result = await asyncio .to_thread (fn , ** args )
166+ return json .dumps (result , ensure_ascii = False , default = str )
167+ except Exception as e : # noqa: BLE001 - surfaced to the model, not raised
168+ return json .dumps ({"error" : str (e )})
169+
170+
65171class ResponsesShim :
66172 """In-process Responses ``/v1/responses`` server backed by a chat endpoint.
67173
@@ -98,11 +204,22 @@ async def responses(request: Request) -> Any:
98204 # Codex injects its built-in tools (e.g. `web_search`) whose schema
99205 # carries fields like `external_web_access` that non-OpenAI Responses
100206 # backends (Ark) reject. Keep only standard `function` tools, which
101- # the bridged chat backend understands.
207+ # the bridged chat backend understands. When the tool loop is enabled
208+ # (CODEX_SHIM_MAX_TOOL_ITERS > 0), additionally translate the stripped
209+ # hosted web tools into Ark-accepted `function` tools that the shim
210+ # executes itself (see the tool loop below), so a Codex+Ark agent
211+ # regains web search/fetch.
102212 if isinstance (call_kwargs .get ("tools" ), list ):
103- call_kwargs ["tools" ] = [
104- t for t in call_kwargs ["tools" ] if t .get ("type" ) == "function"
105- ]
213+ inbound = call_kwargs ["tools" ]
214+ wants_web = any (
215+ t .get ("type" ) in ("web_search" , "web_search_preview" )
216+ for t in inbound
217+ )
218+ kept = [t for t in inbound if t .get ("type" ) == "function" ]
219+ if wants_web and _shim_max_tool_iters () > 0 :
220+ have = {t .get ("name" ) for t in kept }
221+ kept .extend (t for t in _EXECUTABLE_TOOLS if t ["name" ] not in have )
222+ call_kwargs ["tools" ] = kept
106223 # On multi-step turns Codex replays prior assistant messages in
107224 # `input` without a `status` field, but Ark's Responses API
108225 # requires `status` on assistant messages (MissingParameter:
@@ -123,18 +240,83 @@ async def responses(request: Request) -> Any:
123240 api_key = self .api_key ,
124241 custom_llm_provider = "openai" ,
125242 drop_params = True ,
126- num_retries = 0 ,
243+ num_retries = _shim_num_retries () ,
127244 stream = False ,
128245 )
246+ timeout = _shim_timeout ()
247+ if timeout :
248+ call_kwargs ["timeout" ] = timeout
129249
130250 # Always call the backend non-streaming. litellm's chat->Responses
131251 # bridge can only emit a single degenerate `response.completed`
132252 # event when streaming a chat backend, which Codex's strict SSE
133253 # parser rejects (surfaced as a generic "high demand" error). So we
134254 # fetch the full result and, when Codex asked for a stream,
135255 # synthesize the canonical Responses event sequence ourselves.
136- result = await litellm .aresponses (** call_kwargs )
137- resp = _to_dict (result )
256+ # Bounded shim-internal tool loop: call the backend, and while it
257+ # asks for an executable web tool, run the veADK builtin and feed
258+ # the result back as a paired function_call + function_call_output
259+ # (append BOTH so the chat bridge sees [user, assistant(tool_calls),
260+ # tool] regardless of its internal cache). Exit purely on the absence
261+ # of executable function_calls in the fresh output — the always-empty
262+ # `message` item is ignored. The loop is invisible to Codex: only the
263+ # final, tool-free turn is returned/synthesized.
264+ max_iters = _shim_max_tool_iters ()
265+ iters = 0
266+ while True :
267+ result = await litellm .aresponses (** call_kwargs )
268+ resp = _to_dict (result )
269+ if max_iters <= 0 or iters >= max_iters :
270+ break
271+ conv = call_kwargs .get ("input" )
272+ if not isinstance (conv , list ):
273+ break
274+ calls = [
275+ it
276+ for it in (resp .get ("output" ) or [])
277+ if it .get ("type" ) == "function_call"
278+ and it .get ("name" ) in _EXECUTABLE_TOOL_NAMES
279+ ]
280+ if not calls :
281+ break
282+ for fc in calls :
283+ cid = fc .get ("call_id" ) or fc .get ("id" )
284+ try :
285+ args = json .loads (fc .get ("arguments" ) or "{}" )
286+ except json .JSONDecodeError :
287+ args = {}
288+ out = await _run_tool (fc ["name" ], args )
289+ conv .append (
290+ {
291+ "type" : "function_call" ,
292+ "call_id" : cid ,
293+ "id" : fc .get ("id" ) or cid ,
294+ "name" : fc ["name" ],
295+ "arguments" : fc .get ("arguments" ) or "{}" ,
296+ "status" : "completed" ,
297+ }
298+ )
299+ conv .append (
300+ {
301+ "type" : "function_call_output" ,
302+ "call_id" : cid ,
303+ "output" : out ,
304+ }
305+ )
306+ iters += 1
307+
308+ # If we broke at the iteration cap with an executable function_call
309+ # still pending, strip it so it never leaks to Codex (which cannot
310+ # run it and would desync the next turn / emit a null delta).
311+ if max_iters > 0 and isinstance (resp .get ("output" ), list ):
312+ resp ["output" ] = [
313+ it
314+ for it in resp ["output" ]
315+ if not (
316+ it .get ("type" ) == "function_call"
317+ and it .get ("name" ) in _EXECUTABLE_TOOL_NAMES
318+ )
319+ ]
138320
139321 if stream :
140322 return StreamingResponse (
0 commit comments