Repository navigation
Function calling for OpenAI backend - #573
Yiyun-Liang wants to merge 5 commits into
Conversation
0b7d7f1 to
fbe44c2
Compare
Ying1123
left a comment
There was a problem hiding this comment.
Thanks for the PR! I left a few comments. The review is still in progress.
There was a problem hiding this comment.
use dictionary order instead.
There was a problem hiding this comment.
Removing this given we are moving it to be part of SglGen.
There was a problem hiding this comment.
We may also want to retrieve the results from function call.
Add tests for state["func_call_1"] in the function single().
There was a problem hiding this comment.
s.messages_ should be updated after function call finished rather than in generate, and the append logic should happen in interpreter.py, see _execute_role_end() as a reference.
Additionally, changes prompt implicitly changes s.messages_. This is not safe. Changes s.messages_ then set prompt = s.messages_ is better.
There was a problem hiding this comment.
Restructured the code a little bit based on your suggestions (with some minor tweaks but I can update if you think it's still better to move the function call generate call outside of generate (we will just have a simpler generate call):
Within openai.py
build_function_call_messages(): a new function which builds function call messages. Given function signature is specific to open ai models, keeping the logic to parse inputs and produce function call messages within the backend code.generate(): Given prompt is local to thegenerate()call, I directly addedfunction_call_messagesto it so that we can call with function call messages during the current completion call's prompt. The main intuition is to try resuing the generate call logic and it also only appends function call response (comp) without intermediate messages into the final text/messages.
Within interpreter.py
- Updated
_execute_gen()logic to include building function call messages if tools are provided, and handle both parallel function calling and non-parallel function calling by either callingbackend.generateone time for parallel function call supported models, or multiple times if parallel call is not supported.
There was a problem hiding this comment.
keep in mind that the set of models that support function calling and parallel function calling are different.
There was a problem hiding this comment.
Thanks for pointing out! Updated to have different handling logic.
There was a problem hiding this comment.
In this case, assert tool_choice is in names of candidate functions.
There was a problem hiding this comment.
I think it is better to put the logic of real function call into the interpreter, so that it can be reused when we develop the feature for local models.
And remember to handle the logic of appending s.messages_ and s.text_ in the interpreter.
There was a problem hiding this comment.
Makes sense, returning just the function call messages here so we can do real function call separately.
There was a problem hiding this comment.
I think yes, by default. Although accumulating functions could be an option.
There was a problem hiding this comment.
A design suggestion is that it might be better to just have sgl.gen with func_call as an argument.
There was a problem hiding this comment.
I agree, I think it's more straightforward to have it as part of sgl.gen. Would it make sense to have something like sgl.gen("answer_1", max_tokens=256, sgl.func_call(...)) or simply expose parameters directly to sgl.gen like sgl.gen("answer_1", max_tokens=256, tools=[...])?
There was a problem hiding this comment.
Let's simply expose parameters directly to sgl.gen.
e859d3e to
edc30d2
Compare
2463404 to
d737da5
Compare
5b3918a to
075b053
Compare
7eda0c8 to
41d1f67
Compare
e1cbcf5 to
2a01552
Compare
f58f983 to
1e978c2
Compare
16b1dbf to
f1389dc
Compare
|
Any updates on this? :) |
|
It is now supported #2544 |
|
Close this due to inactivity and #2544. |
…-project#601 and sgl-project#628 Merge target: d958a63 "Return bad request for malformed DSV4 tool arguments (sgl-project#602)". Excludes b4de164 (sgl-project#601 "Fix DSV4 C128 state mapping lifecycle") and f59f166 (sgl-project#628 "Sync clean SM90 FP8+FP4 MegaMoE from main") per user instruction. Brings in 13 upstream commits including: - 3e31718 [HiCache] DeepSeek-V4 host-mem L2 + NVMe/disk L3 (sgl-project#564) - 6dddb6d Fix DSv4 draft extend replay forward batch (sgl-project#569) - 9d212a9 add observability (sgl-project#570) - 104a38d Bytedance/deepseek v4 fix draft extend padding (sgl-project#573) - d958a63 Return bad request for malformed DSV4 tool arguments (sgl-project#602) - 8 docker/codex build hardening commits Conflict resolutions (all 8 files stability-critical, memory-related): 1. tree_component.py / full_component.py / swa_component.py / mamba_component.py -- commit_hicache_transfer signature: keep HEAD's typed (insert_result, pool_storage_result) kwargs. Callers in unified_radix_cache.py explicitly pass these; their **kw variant is strictly a superset but less safe. Also drop their side's manual `kw.get(...)` extraction in mamba PREFETCH branch since the params are now directly bound. 2. hybrid_cache_controller.py -- extra_host_mem_release_queues type annotation: keep HEAD's Queue[torch.Tensor] (more precise). 3. swa_memory_pool.py -- their side added a full duplicate SWATokenToKVPoolAllocator class inline in this file, but our fork moved the class to allocator/swa.py in an earlier refactor. Drop their duplicate; instead apply sgl-project#573's free_swa fix (guard against negative sentinels and out-of-range indices, expand page-aligned free) directly to allocator/swa.py where the class actually lives. 4. hybrid_pool_assembler.py: - kvcache.compress_state_pools indexing: keep either form (addition is commutative); use HEAD's ordering for local consistency. - C128 state pool registration: keep HEAD's explicit non-registration with the "C128 State pool intentionally not registered" comment. Our HEAD's upstream sgl-project#27293 deliberately opted out; their side (from before sgl-project#601) still registers it. Silently reintroducing the pool would regress the fix and pressure host memory. - attach_hybrid_pool_to_unified_cache body: keep HEAD's _select_strategy(...).build() dispatch (from upstream sgl-project#26295) over their 245-line inline if-elif chain. Our _DeepSeekV4Strategy already handles the deepseek_v4 stack; the strategy signature already accepts storage_backend / storage_extra_config / storage_prefetch_threshold. 5. unified_radix_cache.py (24 conflicts) -- keep HEAD wholesale: - HEAD has 10 methods theirs lacks (all from upstream sgl-project#26881, sgl-project#27285, sgl-project#27391, sgl-project#27489, sgl-project#27554, sgl-project#27655 L3 support + our PR sgl-project#27010 port: prefetch_sync_thread, ack-driven sync, handle_prefetch_result, _drain_async_work, _finish_write_through_ack, etc.) - Their only extra method (terminate_prefetch(rid)) was deliberately removed by our PR sgl-project#27010 port. - HEAD's load_back_threshold=10 matches hi_mamba_radix_cache and hiradix_cache (theirs=256 was an inconsistent local tuning). - HEAD passes total_len to InsertResult (dataclass field exists) and priority to UnifiedTreeNode (LRU correctness). - HEAD's write_backup early-returns on written==0 (upstream sgl-project#27108 safety fix); theirs drops the check. - HEAD's _drain_queue is blocking with qsize MIN-reduce (our PR sgl-project#27010's lockstep drain); theirs is old get_nowait+Empty pattern that would desync PP/TP. - sgl-project#564's L2/L3 additions in this file are functionally covered by upstream sgl-project#26881 (already in HEAD via ep_main). No net feature loss from taking HEAD. Verified: AST parse OK for all 9 mem_cache files, compileall exit=0 on managers + mem_cache trees. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
sgl-project#573. The first utterance of a session kills the turn. `_identify` returns the literal string "speaker-unknown" when the registry is EMPTY and the segment cannot be embedded -- either shorter than the embedder's min_seconds, or the embedder raised BackendError. `_run_turn_locked` then journals "reference_seconds": round(self.speakers.get(speaker_id)...) if speaker_id and `if speaker_id` is TRUTHY for a non-empty sentinel, so the guard does not fire, `SpeakerRegistry.get` raises KeyError, and the whole turn dies. The user says something and nothing comes back. Live twice after the 19:07 restart, once at 19:11:40 in session 84ff8dd17a91 while the user was testing. Structurally a FIRST-turn failure: with any profile present, `_identify` attributes the segment to the most recent speaker instead. Both sentinel returns need an empty registry, so this is the worst possible moment for it. NOT FIXED BY MINTING A PROFILE, and that is the decision rather than the omission. `speakers.create_speaker` needs no embedding and was available. But the user's standing complaint on this feature is that it opens speakers it should not (sgl-project#565, "er hätte eigentlich gar keinen weiteren speaker am anfang aufmachen dürfen"), and minting for a segment we could not even embed manufactures exactly that spurious roster entry -- carrying centroid=None into a registry whose entire purpose is matching. Fixing a crash by creating the symptom next door is the wrong trade. The turn is UNATTRIBUTED, which is a fact about it, and the crash is fixed at the consumer. Three parts: * `is_attributed()` replaces `if speaker_id` at the crash site. Zero reference seconds for an unattributed speaker is a FACT -- no profile, so no reference buffer, so no seconds -- not a fallback. An id that is attributed but missing still raises: that would be a broken invariant, and turning it into a silent zero is the failure mode this change exists to remove. * The comment at the `min_seconds` return claimed it minted a provisional id. It never did, and believing it is what cost the turn -- the sgl-project#501 class, a comment-asserted invariant the code does not hold. It now says what happens and why not minting is deliberate. * `_speaker_label` gives the sentinel words. The client renders `speaker_label` and falls back to the raw `speaker_id`, so the bubble was about to be captioned with the internal token "speaker-unknown". There is no client-side localisation table to emit into (`speakerLabel()` just falls back), and the app's chrome is lowercase English -- "who spoke?", "translating", "undo" -- while only transcript CONTENT is German or Spanish, so "unknown speaker" matches what it sits next to. The sentinel value itself is unchanged: journals and transcripts already on disk carry that string, and changing it would silently reclassify them. FALSIFIER, AND IT WAS PROVED TO FAIL FIRST. test_speaker_unattributed.py drives `_identify` with an empty registry and a segment below min_seconds, then `_run_turn_locked` through the journal call. Before the fix it fails with exactly the field's error, KeyError: "unknown speaker 'speaker-unknown'"; with the old truthy guard restored afterwards, 4 of the 6 tests fail again. It asserts the turn is SPOKEN, not merely non-None -- audio present and carrying samples -- which needs a preset voice pool in the harness, because an unattributed speaker has no reference audio by construction and production builds that pool at server.py:159. Without it the turn completes silently and the assertion would have been weaker than the user's experience. The BackendError arm needs its OWN test and has one: the min_seconds test never reaches the embedder, so a single falsifier would leave the second return uncovered. A test also pins that no profile is minted, so the rejected fix cannot be applied later by someone reading only the crash. AUDIT CORRECTION. The claim that the other nine `speakers.get()` sites all catch KeyError is not right. Five do (871, 2320, 2376, 2416, 2979); four deliberately propagate it -- name_speaker:890, arm_speaker:1130 and both merge reads:1242-1243 -- each with a comment saying refusal is intended. The operative claim survives: :1728 was the only uncaught site on the automatic turn path, and the other four take a caller-supplied id from an explicit user command. Worth noting that those four become reachable if the sentinel is ever displayed as a tappable speaker chip, which is a reason the label fix matters beyond cosmetics. Tested: 652 tests pass (test/registered/translator), 6 of them new, ruff clean, CUDA_VISIBLE_DEVICES=99 throughout -- no card touched.
Adding skeleton code for function calling with Open API models.
Example output (when
tool_choice is "auto" or "required"):Example output (when
tool_choice is "none"):The current implementation does not support: