Repository navigation
update openai - #1190
update openai#1190
Conversation
WalkthroughAdds a type guard for tool_call handling across OpenAI agent converters so non-function tool calls yield an empty name and empty arguments object instead of causing undefined access or JSON parse errors. Also updates the OpenAI SDK dependency to ^5.12.2. No exported/public API changes. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as OpenAI response
participant Conv as convToolCall / convertOpenAIChatCompletion
participant Parser as JSON.parse
Client->>Conv: returns message with tool_call (type + function?)
alt tool_call.type == "function"
Conv->>Conv: name = tool_call.function.name
Conv->>Parser: parse(tool_call.function.arguments)
Parser-->>Conv: arguments object
else non-function tool_call
Conv->>Conv: name = ""
Conv->>Parser: parse("{}")
Parser-->>Conv: {}
end
Conv-->>Client: sanitized tool object (name, arguments)
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 1
🔭 Outside diff range comments (4)
llm_agents/openai_agent/lib/openai_agent.js (2)
17-22: Harden failure path and logging for argument parsingReturn an empty object on parse failure to keep the output shape stable, and log as an error with context.
- try { - return JSON.parse(tool_call.type === "function" ? tool_call.function.arguments : "{}"); - } - catch (__e) { - console.log(__e); - return undefined; - } + try { + return JSON.parse(tool_call.type === "function" ? tool_call.function.arguments : "{}"); + } + catch (__e) { + console.error("Failed to parse tool_call.arguments", { id: tool_call.id, type: tool_call.type, error: __e }); + return {}; + }
55-61: Unprotected JSON.parse may throw when response_format is setIf text is not valid JSON (model outputs plain text), this will throw and abort the call path.
- if (maybeResponseFormat && text) { - const parsed = JSON.parse(text); - if (typeof parsed === "object" && parsed !== null) { - return parsed; - } - } + if (maybeResponseFormat && text) { + try { + const parsed = JSON.parse(text); + if (typeof parsed === "object" && parsed !== null) { + return parsed; + } + } catch (e) { + // Non-JSON content; ignore and fall through. + } + }llm_agents/openai_agent/src/openai_agent.ts (2)
53-60: Stabilize error handling: prefer {} over undefined and improve loggingKeep the return shape stable and log with more context.
arguments: (() => { try { - return JSON.parse(tool_call.type === "function" ? tool_call.function.arguments : "{}"); + return JSON.parse(tool_call.type === "function" ? tool_call.function.arguments : "{}"); } catch (__e) { - console.log(__e); - return undefined; + console.error("Failed to parse tool_call.arguments", { id: tool_call.id, type: tool_call.type, error: __e }); + return {}; } })(),
103-111: Unprotected JSON.parse on text when response_format is requestedThis can throw if the model returns non-JSON text.
- const responseFormat = (() => { - if (maybeResponseFormat && text) { - const parsed = JSON.parse(text); - if (typeof parsed === "object" && parsed !== null) { - return parsed; - } - } - return null; - })(); + const responseFormat = (() => { + if (maybeResponseFormat && text) { + try { + const parsed = JSON.parse(text); + if (typeof parsed === "object" && parsed !== null) { + return parsed; + } + } catch { + // Not JSON; ignore. + } + } + return null; + })();
🧹 Nitpick comments (4)
llm_agents/openai_agent/lib/openai_agent.js (2)
11-11: Nit: clarify union type in commentConsider noting the full union (ChatCompletionMessageToolCall) and that only the “function” variant carries .function.*. Helps context when reading the guard.
30-38: Variable shadowing of tool_calls can confuse maintenanceOuter tool_calls holds converted calls while inner destructuring reuses the same name for the raw OpenAI shape. Consider renaming the outer to convertedToolCalls for clarity.
llm_agents/openai_agent/src/openai_agent.ts (2)
48-49: Nit: expand the comment to reference the unionAdd that tool_call is OpenAI.Chat.Completions.ChatCompletionMessageToolCall and only the “function” variant exposes .function.*.
75-90: Avoid shadowing tool_callsThe local tool_calls (converted) and the destructured newMessage.tool_calls (raw) share the same name. Rename the converted one to convertedToolCalls to reduce confusion.
- const tool_calls = functionResponses.map(convToolCall); - const tool = tool_calls && tool_calls.length > 0 ? tool_calls[0] : undefined; + const convertedToolCalls = functionResponses.map(convToolCall); + const tool = convertedToolCalls && convertedToolCalls.length > 0 ? convertedToolCalls[0] : undefined; @@ return { ...response, text, tool, - tool_calls, + tool_calls: convertedToolCalls,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
yarn.lockis excluded by!**/yarn.lock,!**/*.lock
📒 Files selected for processing (3)
llm_agents/openai_agent/lib/openai_agent.js(1 hunks)llm_agents/openai_agent/package.json(1 hunks)llm_agents/openai_agent/src/openai_agent.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
llm_agents/openai_agent/src/openai_agent.ts (1)
llm_agents/anthropic_agent/lib/anthropic_agent.js (1)
tool_call(10-10)
llm_agents/openai_agent/lib/openai_agent.js (1)
llm_agents/anthropic_agent/lib/anthropic_agent.js (1)
tool_call(10-10)
🔇 Additional comments (3)
llm_agents/openai_agent/package.json (1)
32-33: Upgrade to openai ^5.12.2 looks goodMatches the code changes that guard tool_call.function access. No API surface changes detected.
llm_agents/openai_agent/lib/openai_agent.js (1)
14-18: Good guard against non-function tool callsThis prevents undefined access and JSON parse errors when tool_call.type !== "function".
llm_agents/openai_agent/src/openai_agent.ts (1)
52-56: Type guard is correct and prevents crashes on non-function tool callsSolid change; matches the SDK’s union shape and avoids undefined access and bad JSON.parse.
| "openai": "^5.12.2" | ||
| }, |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Verify lockfile update and runtime compatibility
Ensure yarn.lock/package-lock.json is updated and that all packages using openai are aligned on ^5.12.x. openai v5 requires Node 18+. Confirm engines across workspace.
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "OpenAI dependency versions across the repo:"
fd -t f package.json | while read -r f; do
ver="$(jq -r '.dependencies.openai // ""' "$f")"
if [ -n "$ver" ]; then
echo "$f => $ver"
fi
done
echo
echo "Node engines across the repo (if defined):"
fd -t f package.json | while read -r f; do
eng="$(jq -r '.engines.node // ""' "$f")"
if [ -n "$eng" ]; then
echo "$f => engines.node=$eng"
fi
doneLength of output: 7590
Add Node 18+ engine requirement and update lockfile
- openai@^5.12.2 is only used in llm_agents/openai_agent/package.json—no version alignment issues.
- No
engines.nodefields found; openai v5 requires Node 18+, so add to your workspace (e.g. root package.json and/or this package):{ … + "engines": { + "node": ">=18" + }, "dependencies": { "openai": "^5.12.2" } } - After installing/upgrading, commit the updated yarn.lock or package-lock.json.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "openai": "^5.12.2" | |
| }, | |
| "engines": { | |
| "node": ">=18" | |
| }, | |
| "dependencies": { | |
| "openai": "^5.12.2" | |
| }, |
🤖 Prompt for AI Agents
In llm_agents/openai_agent/package.json around lines 32 to 33, add an
engines.node field requiring Node 18+ and update the repo lockfile: modify this
package.json (or root package.json) to include "engines": {"node": ">=18"} so it
aligns with openai@^5.12.2 requirements, then run a fresh install (npm install
or yarn install) to regenerate and commit the updated package-lock.json or
yarn.lock file alongside the package.json change.
There was a problem hiding this comment.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (1)
159-161: Fix streaming chunk concatenation order (can corrupt JSON framing).New chunks are prepended to the buffer, reversing order and risking JSON parse failures across chunk boundaries. Append instead.
Apply this diff:
- text_buffer = text + text_buffer; + text_buffer = text_buffer + text;
🧹 Nitpick comments (2)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (2)
164-176: Streaming path ignores tool_calls deltas.Only delta.content is accumulated. If the assistant streams tool_calls, they’ll be dropped and tool won’t be populated, diverging from non-streaming behavior.
Minimal approach: detect and buffer tool_calls deltas alongside content, then surface them to convertOpenAIChatCompletion. I can draft a small helper to merge streamed tool_calls if you want.
134-139: Improve error messages with status/body for easier debugging.Errors are generic. Include status and response body excerpt.
Example:
if (!stream) { if (response.ok) { const result = await response.json(); return convertOpenAIChatCompletion(result, messagesCopy); } const errText = await response.text().catch(() => ""); throw new Error(`OPENAI API Error: ${response.status} ${response.statusText} ${errText?.slice(0, 500)}`); } // streaming if (response.status !== 200 || !reader) { const errText = await response.text().catch(() => ""); throw new Error(`Request failed: ${response.status} ${response.statusText} ${errText?.slice(0, 500)}`); }Also applies to: 144-146
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (4)
llm_agents/openai_fetch_agent/lib/bundle.cjs.js (1)
functionResponse(72-72)llm_agents/openai_fetch_agent/lib/bundle.esm.js (1)
functionResponse(70-70)llm_agents/openai_fetch_agent/lib/bundle.umd.js (1)
functionResponse(74-74)llm_agents/openai_fetch_agent/lib/openai_fetch_agent.js (1)
functionResponse(9-9)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: build (22.x)
- GitHub Check: build (24.x)
🔇 Additional comments (2)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (2)
35-39: Solid type-guard for tool_calls; prevents undefined access and JSON.parse errors.The guard on tool_call.type correctly avoids accessing function fields for non-function calls and defaults arguments to "{}".
1-1: Verify OpenAI SDK v5.12.2 type names; prefer importing types directly.With SDK v5.x, top-level namespace type aliases can differ. Importing types from "openai/resources/chat/completions" is safer.
Suggested change (types only):
import OpenAI from "openai"; import type { ChatCompletion, ChatCompletionMessageParam } from "openai/resources/chat/completions"; // ... const convertOpenAIChatCompletion = (response: ChatCompletion, messages: ChatCompletionMessageParam[]) => { /* ... */ }Please confirm the current build passes type-checking with OpenAI ^5.12.2.
Also applies to: 25-25
Summary by CodeRabbit
Bug Fixes
Chores