Skip to content

Add tolerant OpenAI tool-call parsing for chat completions - #145

Merged
davide221 merged 17 commits into
Luce-Org:mainfrom
jkyamog:feat-agent-tool-calls
May 10, 2026
Merged

davide221 merged 17 commits into
Luce-Org:mainfrom
jkyamog:feat-agent-tool-calls

Conversation

@jkyamog

@jkyamog jkyamog commented May 9, 2026

Copy link
Copy Markdown
Contributor

This PR improves OpenAI-compatible tool calling for /v1/chat/completions.

It keeps Howard's existing tool-call support #132 and adds tolerant parsing for the additional textual tool-call shapes observed from agent clients and Qwen-style models. The goal is to make clients like Hermes/OpenClaw work with OpenAI Chat Completions semantics without making the implementation specific to one tool such as web_search.

What Changed

  • Parses multiple model-emitted tool-call formats:
    • Qwen XML tool calls
    • malformed function-signature style calls such as <function=web_search(query="...")</function>
    • bare JSON objects such as {"name":"web_search","arguments":{...}}
    • wrapped JSON such as <tool_code>{...}</tool_code>
  • Supports multiple tool calls in one assistant turn.
  • Converts valid textual tool calls into OpenAI message.tool_calls.
  • Keeps unknown or malformed tool-call-looking output safe instead of guessing arguments.
  • Preserves normal assistant text when tool_choice: "auto" does not require a call.
  • Keeps continuation requests working when the next request includes previous assistant.tool_calls and role: tool messages without resending tools.

Validation

./.conda/bin/python -m pytest dflash/scripts/test_server.py

Live checks performed against deployed /v1/chat/completions:

  • no-tools chat returns normal assistant content
  • tool_choice: "required" returns finish_reason: "tool_calls"
  • tool continuation without resending tools returns normal assistant content, not HTTP 500
  • streaming tool calls emit delta.tool_calls and finish with finish_reason: "tool_calls"

NOTE:

this is based on #132 assumption will be merged, so this PR is based on that tree.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="dflash/scripts/server.py">

<violation number="1" location="dflash/scripts/server.py:1742">
P2: Responses SSE tool-call lifecycle is inconsistent: a message item is added first, but the final done event is for a different function_call item without a matching added event.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread dflash/scripts/server.py Resolved
howard0su and others added 14 commits May 10, 2026 13:57
add the missing feature, integrate tools call support for server.py
- Rewrite test_server.py with 36 comprehensive tests (was 10):
  - TestParseReasoning: 8 tests covering tags, headless, disabled, started_in_thinking
  - TestParseToolCalls: 6 tests for single/multi/params/text preservation
  - TestStopHelpers: 7 tests for normalize_stop and first_stop_match
  - Endpoint tests: health, CORS, models (OpenAI+Codex), chat completions
    (non-streaming, streaming, tool calls), Responses API (non-streaming,
    string input, instructions, streaming, tools, function_call_output,
    developer role mapping)
- Fix UnboundLocalError for started_in_thinking in streaming closures
  by adding nonlocal declarations in chat and anthropic SSE generators
- Add DEVELOPER.md with environment, setup, build, and test documentation

Co-authored-by: Copilot <[email protected]>
Change tool_choice type from 'str | None' to 'Any | None' in
ResponsesCreateRequest so object-style payloads like
{"type": "function", "name": "..."}  pass Pydantic validation
and reach the mapping logic. Matches ChatRequest which already uses Any.

Add test_responses_object_tool_choice to cover this case.

Co-authored-by: Copilot <[email protected]>
Pass started_in_thinking through to _responses_non_stream and forward
it to parse_reasoning so prefixed <think> generations are correctly
classified as reasoning instead of leaking into output content.
Also reset started_in_thinking=False on cache hits (consistent with
chat completions path).

Add test_responses_non_streaming_started_in_thinking regression test.

Co-authored-by: Copilot <[email protected]>
Qwen's chat template requires the system message at position 0 and
rejects multiple system messages. Codex sends both 'instructions' and
developer-role input items, which _map_responses_input was converting
into separate system messages, causing 'System message must be at the
beginning' errors.

Fix: collect all system/developer content and merge into a single
system message prepended to the message list.

Also add name='DFlash' to the Codex config docs (required by v0.130.0)
and remove temporary debug try/except wrapper.

Co-authored-by: Copilot <[email protected]>
Log each incoming request with: response_id, stream mode, message count
by role, tool count, prompt token count, max output tokens, max_ctx,
and model name. Log completion with output types and token counts.

Add WARNING-level logs when prompt exceeds max_ctx (the silent
response.failed that was causing Codex to disconnect).

Co-authored-by: Copilot <[email protected]>
Report elapsed time and tok/s in DONE log lines for both
chat completions and responses endpoints (stream + non-stream).

Example output:
  responses DONE resp_abc  in=4096 out=512  3.2s  160.0 tok/s  output=['message']  text_len=2048

Co-authored-by: Copilot <[email protected]>
When enabled, the ~3.3 GB decode draft model is parked (freed from VRAM)
at startup and between requests. It is automatically unparked before each
generate command and parked again after tokens are consumed.

This frees VRAM for longer KV cache context (e.g. +247K tokens with TQ3_0
KV type) at the cost of ~200-500ms per-request overhead for the GPU reload.

Implementation:
- Park draft in _startup() after daemon ready
- Unpark draft in _write_cmd() before sending generate command
- Park draft via _park_draft_if_lazy() after token consumption in all
  7 generate paths (3 endpoints × stream/non-stream + early stop return)
- DEBUG-level logging for park/unpark events

Co-authored-by: Copilot <[email protected]>
Break down elapsed time into phases: compress, unpark, prefill, decode,
park. Prefill is measured as time-to-first-token after command sent.
Decode shows wall time and tok/s for tokens 2..N (excluding TTFT).

Example log output:
  responses DONE resp_xxx  in=15451 out=102  55.8s  1.8 tok/s  ...
    compress=45.2s  unpark=0.3s  prefill=7.1s  decode=2.9s(34.8tok/s)  park=0.0s

Implementation: thread a timing dict through _write_cmd, _park_draft_if_lazy,
_astream_tokens, _collect_tokens_sync, and _token_stream. The _timing_summary
helper formats the breakdown for log lines.

Co-authored-by: Copilot <[email protected]>
When the daemon returns 0 tokens (e.g. 'empty prompt' from missing/empty
.bin file), confirm_inline_snap/confirm_full_snap was registering cache
entries for snapshots that were never actually taken. Future requests
hitting those entries would RESTORE from corrupt/stale KV data.

Changes:
- Add _confirm_or_abort_snap() helper: confirms snap only when n_tokens>0,
  otherwise calls abort_inline_snap/abort_full_snap to release reservation
- Replace all 6 raw confirm_inline_snap/confirm_full_snap call sites with
  the new helper (chat/anthropic/responses × stream/non-stream)
- Add .bin file validation in _write_cmd: warns if file is missing or
  0 bytes before sending the generate command to the daemon

Co-authored-by: Copilot <[email protected]>
@jkyamog
jkyamog force-pushed the feat-agent-tool-calls branch from 272f723 to 85c44a9 Compare May 10, 2026 06:00

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="dflash/scripts/server.py">

<violation number="1" location="dflash/scripts/server.py:153">
P2: Permissive parsing can turn ordinary assistant text into `tool_calls` when no tools were declared.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Comment thread dflash/scripts/server.py Resolved
@jkyamog
jkyamog force-pushed the feat-agent-tool-calls branch from 09b0df7 to df8c199 Compare May 10, 2026 07:18
@davide221

Copy link
Copy Markdown
Contributor

@jkyamog great contribution! lgtm

@davide221
davide221 merged commit 09e46e0 into Luce-Org:main May 10, 2026
1 check passed
@jkyamog
jkyamog deleted the feat-agent-tool-calls branch May 17, 2026 21:57
oliveagle pushed a commit to oliveagle/lucebox-hub that referenced this pull request May 22, 2026
Add tolerant OpenAI tool-call parsing for chat completions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants