-
Notifications
You must be signed in to change notification settings - Fork 10.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Tool call support (generic + native for Llama, Functionary, Hermes, Mistral, Firefunction, DeepSeek) w/ lazy grammars #9639
Conversation
Apologies for this PR being a moving target. I've now stabilized things (except older gcc giving me sweats), added tests & included basic usage instructions (w/ a tiny agent helper adapted from #6389) for Llama-3.1-8B-Instruct, Hermes-2-Pro-Llama-3-8B and functionary-small-3.2 (which still needs a bit of work). |
@ochafik Your BTW: My current tool-calling solution is to write dummy functions in python and generate grammar files with pydantic, awkward and ugly. I'll definitely give it a try when you finish this PR. Exciting work! |
Thanks @rujialiu !
Thanks for the pointer, at first glance inja seems too limited to support actual templates (we're at the mercy of each and every model maker, some use lots of jinja features, e.g. NousResearch/Hermes-3-Llama-3.1, Cohere/command-r-plus, meetkai/functionary-medium-v3.2 ). Filters (w/ the pipe syntax, e.g.
Yeah I'm doing the same, that's why I spent so much energy improving the JSON schema support tbh.
Hopefully soon! (famous last words haha) |
Ouch, I was not aware of that. That's crazy. Now I'm really impressed that your little code already supports these. Maybe I should use your |
@ochafik I really like your idea of using lazy grammar, I would love to help you. I'm the developer of llama-cpp-agent. Let me know if we can collaborate somehow. |
@Maximilian-Winter thanks / sorry for the slow reply! (frantically busy few weeks 😅) I'd love help on this, anything from just testing out instructions above, to finding new cool examples / bugs, reporting on any other model's tool call styles, or new ideas. I'm trying to release minja in its own mini-repo w/ better testing, but the lazy grammar part is probably going to be what needs most work on next. Depending on your timezone, happy to jump into a video chat too :-) (DM on x?) (Also, llama-cpp-agent looks suuuper cool! 💜) |
@ochafik Sure, that would be great. I'm living in germany. I actually tried to verify on X, by buying premium to write you, but I still have to wait for verification. If you want to reach out me by email or discord, feel free! My email is [email protected] |
… dumb for function call)
I'm getting this error while running
Probably not important to make In the near future, we can have a dedicated CI workflow to run all the slow tests. I can setup a HF space with T4 or L4 GPU, to be discussed with HF team.. |
@ngxson hopefully fixed (slight hack), the bartowski version of the model i switched to is marking (correctly) |
…en completion & tool call tests?)
@ngxson I think this is mergeable once you're happy with it; had to disable the plain non-tools jinja test for now (not critical as i've only introduced it to support tool calls), one of many things to follow up on 😅 |
That sounds ok to me, let's merge this |
minor fix diff --git a/examples/server/server.cpp b/examples/server/server.cpp
index d1ea343d..8efc18ad 100644
--- a/examples/server/server.cpp
+++ b/examples/server/server.cpp
@@ -1813,7 +1813,7 @@ struct server_context {
n_ctx = llama_n_ctx(ctx);
- add_bos_token = llama_vocab_get_add_bos(vocab);
+ add_bos_token = llama_vocab_get_add_bos(vocab) && !params.use_jinja;
has_eos_token = llama_vocab_eos(vocab) != LLAMA_TOKEN_NULL;
if (!params_base.speculative.model.empty() || !params_base.speculative.hf_repo.empty()) { Edit: This fix doesn't seem to work 😞 Nonetheless, it seems the Llama models still have a double bos token while using jinja templates |
Today I am getting odd behavior in the WebUI with DeepSeek-R1-Distill-Llama-8B-Q8_0
|
Thanks for reporting! Which flags / exact model repo id did you launch with? (There’s an interference with ‘—jinja’ I think) |
.\llama-server.exe -m "...\DeepSeek-R1-Distill-Llama-8B-Q8_0.gguf" --port 8082 --jinja -c 30720 -ngl 33 -t 8 |
Tested with pydantic-ai, had to modify their _util.py since the schema doesn't seem to set tool_call_id and it gets model = OpenAIModel( ) agent = Agent( @agent.tool_plain @agent.tool dice_result = agent.run_sync('My guess is 4', deps='Anne') Modify the site-packages\pydantic_ai_utils.py", line 201, in guard_tool_call_id to ignore the check. If I get a less hacky fix, I will share it. Full pydantic-ai support is pretty cool. |
Hey @brucepro, thanks for sharing your experimentation! Only a few models seem to spontaneously generate a tool call id on their own (and use it in their template; mostly models that support parallel tool calls), I'll look into forcing it for the others. Mistral Nemo is one of them, works without hack rn: llama-server --jinja -fa -hf bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q6_K_L (incidentally, I'm forcing a tool call id for the generic support when |
很牛逼 |
so uh we can finally make models run code with chat? |
This supersedes #6389 (now using a fully C++ approach), #5695 (first attempt at supporting Functionary) and #9592 (more recent Python wrapper).
Which models are supported (in their native style)?
While any model should work (w/ generic fallback using JSON schema constraints), this PR supports the native call style of a few models:
Show all templates supported by minja and which handler they use
For natively supported models, it's important to have the right template (it might not be in the GGUF; note that we prefer the
tool_use
variant of the Jinja template if it's present in the GGUF metadata). You can check which template is defined by inspectinghttp://localhost:8080/props
, and inspect the logs forChat format:
.Any
tool_calls
field returned byllama-server
should always conform to the JSON schema (to the extent that it uses supported features of JSON schemas), so there's no need to use any post-processor.How to use / test
You can test tool calls as follows:
Get and build this PR's branch
Run
llama-server
w/ any model:Call the chat completions endpoint (in non-streamed mode) with any OpenAI-compatible library, or plain curl:
It will output something like (once piped in
jq
):I've also created some minimalistic Agent loop code in this Gist: it contains a few python tools & supports running them in a siloed docker container, along with examples (used to be part of this PR).
Background
This PR tackles two main problems related to tool calling:
Lazy grammars: Helping / forcing the model to follow the tool schemas w/ grammar constraints is tricky as in most cases the model may also output normal, unconstrained content (except if
"tool_choice": "required"
is specified in the request). It's not currently possible to say.* "<tool_call>" constrained "</tool_call>"
as the leading.*
will match eagerly. In [WIP] agent example (w/ sandboxable Tools!) & improved OAI compatibility layer (in Python) #6389 I was avoid this issue in thethoughtful_steps
style, but the native tool call styles were still problematic.Solved w/ lazy grammars activated by trigger words (similar to stop words, but awaited in the grammar implementation itself). Output is completely unconstrained before triggers, and completely constrained after, which allows for
content
vs.tool_call
outputs, and even mixes of the two (for the few models that support that).For Llama 3.x (cf. these docs: 1, 2, 3), triggers are
<|python_tag|>
if any of the builtin tools are detected (wolfram_alpha
,brave_search
/web_search
withquery
param,code_interpreter
withcode
param); NOT for Llama 3.2{"name": "toolN"
(for eachtoolN
in the list oftools
in the request){"name":
(needed for very small 1B/3B models which get confused very quickly otherwise), and some other variations (to allow the somewhat popular{"type": "function", "name": ...
)For Functionary v3.1, we trigger on
<function=
and<|python_tag|>
(NOTE: seems to work well w/Llama-3.1-Instruct
, e.g. it's on together.ai's docs). Note that<|python_tag|>
here introduces freeform Python code, whereas for Llama-3.1-Instruct's template it introduces builtin tool calls in Python syntax. Almost the same, but handled quite differently.For Functionary v3.2, it's
>>>toolN\n
for eachtoolN
(technically also triggering ontoolN\n
for the first tool call, there's a todo to avoid spurious matches by forcing a match at the very start)For Hermes Pro (cf. Hermes-Function-Calling repo), the trigger is
<tool_call>
.For Mistral Nemo, the trigger is the special
[TOOL_CALLS]
tokenFor DeepSeek R1 and its distills, it's
<|tool▁calls▁begin|>
(Note: DeepSeek-R1 seems more eager to talk than to call tools for now, lemme know if you get it to work)For Firefunction v2, the trigger is
functools[
For other models ("generic" chat format), no lazy grammars are used, just a normal JSON schema that can contain schema-constrained tool calls or content (unless
tool_choice
isrequired
)Jinja chat templates for tool-call-able models are getting increasingly complex, and implementing each of them in C++ is a maintenance hazard.
minja.hpp
), with just enough to render all the templates I could find in the wild. That's still a lot of code (2.5k LOC), but about 10x less so than Jinja2Cpp (not even counting its dependencies - it needs a subset of Boost and some C++ backfills). It's trivial to extend (say, to add support for a new filter / test), and it comes with decent error reporting and simple tests. And we could always switch to another implementation in the future.With this intro out of the way, here are the main parts of this PR:
minja.hpp
: minimal Jinja templating engine and its tests against actual templates & a few test contexts--jinja
flag in Add Jinja template support #11016Tool call grammar generation + output parsing logic for 8 different tool call styles (covering most of the popular models, incl. Llama 3.x, Functionary 3, Qwen 2.5, DeepSeek R1, Mistral Nemo...), with a generic fallback.
Lazy grammar wired into the sampler, using a mix of trigger words and trigger tokens to enable the grammar. Trigger tokens are also used to override printability of special tokens, even when the grammar is not lazy (e.g. when
"tool_choice": "required"
is passed in the request)Integration with
llama-server
(fulltools
&tool_choice
support).( cd examples/server/tests && ./tests.sh -m slow -v -x )
).TODOs
Blocking:
sync
: minja #11499 (this PR's diff won't include chat-template.hpp or minja.hpp)python_code_argument_name
in favour ofexpect_tool_arguments
Nice to haves:
at_first
semantics to require trigger word to be at start of output (equiv. to ^ regex behaviour; not using regexes as ^ can't be made to mean "start of entire string" reliably afaict), to reduce spurious triggers w/ Llama 3.xSee draft-times TODOs
[ ] Support streaming (of content - as long as it doesn't trigger any partial antiprompt match - and of individual tool calls)"all\n"
in non-tool-call outputs forCommand R Plus,DeepSeek)[ ] e2e tests for agent[ ] Add Google search tool as alternative to Brave--special
for Nemo since last merge[TOOL_CALLS]
token<|python_tag|>
tokenthoughtful_steps
tool support from [WIP] agent example (w/ sandboxable Tools!) & improved OAI compatibility layer (in Python) #6389 (using JSON structured output even with models not trained for tool calling)--cache-prompt
defaults to true; follow up will be to allow in-slot restoration and saving of cache, see this branch for instancechat_template
should maybe be resolved earlier? (now allama_chat_template
class)llama_apply_chat_template would benefit from a massive facelift. Maybe passing in a struct?(have introduced a new C++ APIllama_chat_template::apply
)llama_token_to_piece(ctx, token)
should really take(model, token)
instead, but that's a breaking API change_llama_token_to_piece
that takes model. Movedllama_chat_template_from_model
helper tocommon.cpp
builtin_tools
andtodays_date
in llama3.1's template)test-chat-templates
&test-minja
(write each test case in a.jinja
file)bos_token
in the current chat template logicexamples/tool-call
) from [WIP] agent example (w/ sandboxable Tools!) & improved OAI compatibility layer (in Python) #6389Possible follow ups:
-hft
/--hf_template
flag to override the GGUF's chat templates from a HF model repo