-
Notifications
You must be signed in to change notification settings - Fork 10.8k
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)
@ochafik This functionality would very cool to explore. I'm not familiar with Pyodide, but if it is something lightweight that would allow tool usage with the existing web ui it's worth a shot. The tool that I am looking forward the most is to be able to OCR my screen and provide the contents to the request. |
isnt that expensive, model has to communicate to browser, browser executes pydiode, then model has to read what pydiode outputs. |
I think with tool calling you can achieve this by adding: async function execute_python({ code, packages }) {
async function _loadScript(url) {
if (!window.loadedScripts) {
window.loadedScripts = {};
}
if (window.loadedScripts[url]) {
return;
}
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = url;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
}).then(() => (window.loadedScripts[url] = true));
}
await _loadScript("https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.js");
// Initialize Pyodide
let pyodide;
if (!window.pyodide) {
pyodide = await loadPyodide();
window.pyodide = pyodide; // Cache it globally for future use
} else {
pyodide = window.pyodide;
}
try {
// Redirect standard output to a variable
pyodide.runPython(`
import io
import sys
sys.stdout = io.StringIO()
`);
// Load packages
if (packages && packages.length > 0) {
for (const packageName of packages) {
try {
await pyodide.loadPackage(packageName);
} catch (e) {
// If packages fail to load, notify in the output
return { error: `Failed to load package ${packageName}. Error: ${e.message}` };
}
}
}
// Execute the Python code
pyodide.runPython(code);
// Get the captured output
let output = pyodide.runPython("sys.stdout.getvalue()");
// Reset standard output
pyodide.runPython(`
sys.stdout = sys.__stdout__
`);
return { output: output };
} catch (error) {
return { error: error.message };
}
} and it should work with python execution and python package loading, but note that pyodide has a limited selection of python packages, and it is very... very slow |
@benhaotang @ochafik IMO we should wait a bit more to see if the python tool will become standarized by new models. My POV is that it is still extremely experimental and only work with a small number of models, so probably not worth adding it right now, as it may add more headaches. For now, let's focus mainly on having proper support for OAI-compat API for tool calls, so user can freely use llama.cpp in their existing code base. |
@ngxson Part of the problem is most tool call formats pass the arguments (code included) as JSON, and some models struggle to properly escape double quotes inside there (part of why Llama 3.1 <=8B struggles with basic hello worlds in the tests - attempts to open a python string cause the entire python code json string to close 🤦♂️, although most other models I've tried manage to sort their escapes well). Formats that pass verbatim code back such as functionary v3.1 (freeform It would be good to get examples of code that people manage to squeeze out of the known working models (for DeepSeek R1, need to use this branch #11607 ) |
Tbh, that sounds like a bad design to be (If anyone ever actually uses this approach). I can assure you that no company in the world want to spend time to train a model just to write python wrapped inside a JSON. Indeed, if you think as a model maker, it make more sense to train the model to give straight-forward tool call request. For example, if I ask the model to turn on the light in my house, I should provide it the function prototype and it should response with a JSON like And for example, if you still want to return the python code (provided that you have a good prompt engineering skill), it's better to just ask the LLM to return in a markdown codeblock starting with "``` python-tool" And now have a look at the But then, let me tell you how bad this design decision is, even Meta don't want to use it! Just have a look at the model card, they just do prompt engineering instead of using that <|python_tag|>` |
unrelated but, I've seen deepseek and propietary models use non-ascii tags, they use utf-8 characters something like |
Simple reason why And for why some models use Fullwidth Vertical Line, I don't know. If anyone know, please tell me! A clue that I found is that this started from some chinese models (before deepseek) |
The why is clear, because unicode symbols are rarer in text, <| is more likely to appear since it's ASCII printable. So they want to make very very unlikely to collide tags. Why they chose that character specifically, no idea. |
@ngxson Absolutely! And unfortunately it's the approach most seems to be using right now (at least as far as documentation and/or jinja templates show). And then there are the inherent risks of prompt injection (should be easy to SEO a modern DeepSeek has maybe the closest syntax to something good (cf. test-chat), although its template seems terribly broken rn (I'm toying with a revamped version and trying to get it to generate python code blocks, since it already generates json blocks), and plan on writing a Jinja templating good practices doc in a near future / think a bit harder about safe escaping options (maybe pass the special pseudo-tokens to minja for escapes). |
Just an FYI, I am working on adding mcp to the webui client. |
The JSON schema is how OpenAI handles calling functions. Not the literal json structure, but just metadata describing the call. The model produces the call, but the response is formatted according to the defined schema. Not sure if there's a sane way, but using HTML would be naive for the reasons stated here. The The raw JSON format is more of a hacky solution. Personally, not a fan. Ideally, function calls would be language agnostic. Not sure why you would have language specific calls when you just need to describe the function, parameters, and ouput. Still working my way there. I'm open to template recommendations. |
@brucepro lemme know if you need a review, even on draft code I was thinking of wrapping MCP servers in a siloed environment and expose them as an openapi endpoint (similar to that) but i guess I could expose the wrapped / federated siloed servers as... an MCP server. (Also, not sure i understand it all, looks like Claude desktop launches its MCP servers as subprocesses / using the stdio transport? didn't see easy prepackaged versions of HTTP / SSE transport servers) |
I saw a pretty cool SSE proxy ( https://github.com/supercorp-ai/supergateway ) recently that allowed you to install mcp servers that the mcp client could then just make calls to. Right now I am testing the typescript sdk in the webui using the stdio support built in. It might be too heavy to bundle, so might be better to have it as a standalone. I love using the webui in the server but honestly, I think the server should just focus on being the best server. Soon as I have it working mostly will post it. |
I'm surprised about this. From my POV, the MCP is mostly like a wrapper that adds ability to do real-time communication on top of existing application logic, so it should be lightweight. If it ends up being bigger than 10kb, then I can already smell some over-engineering here. In anw, I think it could be a cool idea to try out MCP if the adoption is somewhat acceptable (ref this list). Probably can add this as an experimental flag and people who want to try out can activate it manually. Big scripts can be loaded via CDN instead of bundling into |
It would be good to keep a fully local AI mode tho ;-) (speaking of which, the model url loading logic doesn't handle offline mode this well yet) |
Added a simple example outputs for "count times Olivier appears on https://ochafik.com" coding task, DeepSeek R1 Distill Qwen 32B does decently there (and thinks a lot, which will now appear in its own hidden field): |
Great work! |
It seems like it adds double BOS when using LLama 3.1 models. Doesn't happen without --jinja |
@Dampfinchen should be fixed as of #11641 / b4641, which version of llama-server & exact model did you test this with? |
So, I've had surprisingly good results with a simple pseudo-Python grammar that ensures code strings are valid structured token soups, guaranteeing string tokens aren't split (restricting allowed nested escapes) & open parentheses / braces / brackets are closed (in this branch). It makes even Llama 3.x 1B / 3B / 8B super compliant & able to overcome the code escapes issues, even at very high temperatures (tested up to 5). Once finalized, it may also be a great way to guard against prompt injection (e.g. from tool results) for models that use special unicode tokens to close / open tool calls (if we mandate that unicode be escaped in the code's JSONified string), which is could be another reason why unicode symbols may have been chosen (cc/ @Kreijstal @ngxson re/ discussion above). NOTE: results above and below are from my tool-bench branch which builds on top of #1160
FYI I've looked into benchmark options (cc/ @Maximilian-Winter ):
![]() |
…istral, Firefunction, DeepSeek) w/ lazy grammars (ggml-org#9639) --------- Co-authored-by: Xuan Son Nguyen <[email protected]> Co-authored-by: Georgi Gerganov <[email protected]> Co-authored-by: Xuan Son Nguyen <[email protected]>
Call updated to match the tool used in the output just below, following the example in #9639
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:
server
: fix tool-call of DeepSeek R1 Qwen, return reasoning_content (Command 7RB & DeepSeek R1) unless--reasoning-format none
#11607tool-call
: support Command R7B (+ return tool_plan "thoughts" in API) #11585Show 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 (Edited: bumped to quants / models that work w/ my agent example):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