Skip to content

Function calling for OpenAI backend - #573

Closed
Yiyun-Liang wants to merge 5 commits into
sgl-project:mainfrom
Yiyun-Liang:func-call
Closed

Yiyun-Liang wants to merge 5 commits into
sgl-project:mainfrom
Yiyun-Liang:func-call

Conversation

@Yiyun-Liang

@Yiyun-Liang Yiyun-Liang commented Jun 29, 2024 •

Copy link
Copy Markdown

Adding skeleton code for function calling with Open API models.
Example output (when tool_choice is "auto" or "required"):

system : You are a helpful assistant.
user : What's the weather like in San Francisco, Tokyo, Paris, and Beijing?
assistant : The current weather in San Francisco is 72°F, in Tokyo it is 10°C, and in Paris it is 22°C. Unfortunately, I couldn't retrieve the weather information for Beijing at the moment.

Example output (when tool_choice is "none"):

system : You are a helpful assistant.
user : What's the weather like in San Francisco, Tokyo, Paris, and Beijing?
assistant : I'm sorry for the inconvenience, but as an AI model developed by OpenAI, I don't have real-time capabilities to provide the current weather in San Francisco, Tokyo, Paris, and Beijing. I recommend using a reliable weather forecast service or website to get real-time weather updates for these cities.

The current implementation does not support:

  • chat models not listed by OpenAI as of 07/25/24.
  • non-chat models
  • speculative execution

@Yiyun-Liang
Yiyun-Liang force-pushed the func-call branch 4 times, most recently from 0b7d7f1 to fbe44c2 Compare June 29, 2024 22:00

@Ying1123 Ying1123 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.

Thanks for the PR! I left a few comments. The review is still in progress.

Comment thread python/sglang/lang/interpreter.py Outdated

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.

use dictionary order instead.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Removing this given we are moving it to be part of SglGen.

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.

We may also want to retrieve the results from function call.
Add tests for state["func_call_1"] in the function single().

Comment thread python/sglang/backend/openai.py Outdated

@Ying1123 Ying1123 Jun 30, 2024 •

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.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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 the generate() call, I directly added function_call_messages to 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 calling backend.generate one time for parallel function call supported models, or multiple times if parallel call is not supported.

Comment thread python/sglang/backend/openai.py Outdated

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.

keep in mind that the set of models that support function calling and parallel function calling are different.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks for pointing out! Updated to have different handling logic.

Comment thread python/sglang/backend/openai.py Outdated

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.

In this case, assert tool_choice is in names of candidate functions.

Comment thread python/sglang/backend/openai.py Outdated
Comment on lines 318 to 342

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.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Makes sense, returning just the function call messages here so we can do real function call separately.

Comment thread python/sglang/lang/interpreter.py Outdated

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.

I think yes, by default. Although accumulating functions could be an option.

@Ying1123 Ying1123 self-assigned this Jun 30, 2024
@Ying1123 Ying1123 changed the title Func call Function calling for OpenAI backend Jun 30, 2024

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.

A design suggestion is that it might be better to just have sgl.gen with func_call as an argument.

@Yiyun-Liang Yiyun-Liang Jun 30, 2024 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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=[...])?

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.

Let's simply expose parameters directly to sgl.gen.

@Yiyun-Liang
Yiyun-Liang force-pushed the func-call branch 3 times, most recently from e859d3e to edc30d2 Compare June 30, 2024 23:44
@merrymercy
merrymercy force-pushed the main branch 2 times, most recently from 2463404 to d737da5 Compare July 4, 2024 07:57
@Yiyun-Liang
Yiyun-Liang force-pushed the func-call branch 9 times, most recently from 5b3918a to 075b053 Compare July 9, 2024 05:26
@merrymercy
merrymercy force-pushed the main branch 2 times, most recently from 7eda0c8 to 41d1f67 Compare July 16, 2024 03:44
@Ying1123 Ying1123 mentioned this pull request Jul 17, 2024
15 of 29 tasks
@Yiyun-Liang
Yiyun-Liang force-pushed the func-call branch 3 times, most recently from e1cbcf5 to 2a01552 Compare July 21, 2024 19:15
@Yiyun-Liang
Yiyun-Liang force-pushed the func-call branch 3 times, most recently from f58f983 to 1e978c2 Compare July 26, 2024 03:45
@Yiyun-Liang
Yiyun-Liang force-pushed the func-call branch 2 times, most recently from 16b1dbf to f1389dc Compare July 26, 2024 04:13
@merrymercy

Copy link
Copy Markdown
Collaborator

@felixdivo

Copy link
Copy Markdown

Any updates on this? :)

@Tushar-ml

Copy link
Copy Markdown
Contributor

It is now supported #2544

@merrymercy

Copy link
Copy Markdown
Collaborator

Close this due to inactivity and #2544.
We can revisit the tool support for the language frontend later.

@merrymercy merrymercy closed this Jan 2, 2025
hzwzwzw pushed a commit to hzwzwzw/sglang that referenced this pull request Jul 2, 2026
hzwzwzw added a commit to hzwzwzw/sglang that referenced this pull request Jul 2, 2026
…-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]>
efschu added a commit to efschu/htsglang that referenced this pull request Aug 4, 2026
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.
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.

5 participants