Skip to content

llm: functional tool calling scheme - #9956

Merged
vito merged 71 commits into
dagger:mainfrom
vito:llm-evals
Mar 26, 2025
Merged

vito merged 71 commits into
dagger:mainfrom
vito:llm-evals

Conversation

@vito

@vito vito commented Mar 24, 2025 •

Copy link
Copy Markdown
Contributor

New evals system

(EDIT: this is still really experimental, moved to https://github.com/vito/daggerverse/tree/main/botsbuildingbots)

  • Added the beginning of a new suite of evals so we can quickly get a sense of how well each model understands our tool calling scheme as we iterate on it.
    • Gemini is great for this
  • Adds an agent loop module for iterating on a system prompt based on how those evals go.
    • We maintain a README for the tool calling scheme.
    • The agent generates a system prompt from the README, runs evals, observes behavior, corrects, and keeps going until all evals pass.
    • Sometimes it stops too early - I might just wrap it in a code loop.

New tool calling scheme

Based on these evaluations I've ended up with a pretty svelte tool calling scheme:

  • select<Type>(id: "<Type>#123"):
    • e.g. selectContainer(id: "Container#1")
    • Description:

      Set the current state to a Container.

      Provides the following tools:

      • Container_withExec
      • ...

      Possible selections:
      $foo = Directory#1

    • Returns {"selected":"Container#123"}
  • <Type>_<function>(...)
    • e.g. Container_withExec(args: ["foo", "bar"])
    • e.g. Container_withMountedDirectory(source: "Directory#1")
    • Returns {"selected":"Container#123"} for Object responses
    • Returns {"result":42} for Scalar or Array-of-Scalar responses
    • Returns {"objects":["Container#123", "Container#124]} for Array-of-Object responses

Those two are foundational, and get us really far on their own, but the following tools were added after to support more cases and situations:

  • currentSelection
    • Description: Your current selection: Container#1
    • Currently exists solely as a hint to the model that it has a currently selected object that it is operating against. There's no point actually calling it, and a lot of the time the model doesn't, and just takes the hint.
    • This might turn into a return tool someday.
  • readVariable(name: "foo")
    • Description:

      Read the string value from an assigned variable.

      Available variables:
      $readme (length: 1024, hash: xxh3:abcdef)

This new scheme is strongly influenced by the idea that our LLM API should work just like functions. You set variables as a jumping off point, let the model traverse the DAG, and inspect the resulting state.

Sequence IDs vs. hashes

The key idea that unlocked this scheme was a new LLM-optimized format for referring to objects.

Container@xxh3:abcdef1234567890 becomes simply Container#1. We just keep track of what IDs we've seen within the session, with per-type sequence numbers.

With this primitive, we don't need _undo or one-tool-per-variable. We just need a tool for changing the current selection to an ID, and to have the response from each tool (including functions) clearly indicate the ID of any new selection.

In my testing and research LLMs can easily handle this scheme, compared to hashes which are (theoretically) more difficult for them to juggle, and variables which come with a high cost (see below).

Sequence IDs vs. variables

An earlier iteration exposed variables as individual tools, to assist with models like Gemini that needed strong hints as to what objects were available to them and what tools they had.

  • select_foo: Set the current context to $foo (Container@xxh3:abcdef1234567890). Available tools: ...

That same iteration also exposed _saveAs so the model can 1) make checkpoint variables and 2) return values to the user.

This scheme combined had poor scaling characteristics:

  • If the only way to select a value is by variable, that means the model has to make an extra roundtrip to set a variable at nearly every turn. It would also often immediately select the variable it just set, so each intermediate state resulted in 2 additional roundtrips - with the set of tools being high token cost, this was awfully expensive.
  • If each variable has to list its available tools, we're now listing the same sometimes-large list of tools for each variable, which is redundant.
  • Each variable also consumed 1 of only 128 tool slots.

Switching to select<Type> addresses all of these concerns:

  • Now the model can switch to any previous value it saw, without having to spend cycles setting variables and selecting them.
  • Now we scale once-per-type (dynamically exposed based on available/observed objects), instead of once-per-variable with an increasing number of variables.

Bug fixes & expanded capabilities

  • Now supports traversing through lists of objects
    • Previously this was straight up unhandled and possibly panicked
  • Now resilient to a model calling unknown tools
    • Previously this was dropped on the floor, leading to wonky message history for the next API call, leading to a cryptic error (mismatched tool_use/tool_response or something)
    • Now the model will get a "tool not found" error and a hint nudging it in the right direction
  • Gigantic string responses are now truncated at 8k 80k characters
    • This should maybe be configurable
  • Binary string responses are shown as digests instead
    • Helps avoid blowing up your token budget when the model calls File.contents against the binary it built

@vito
vito force-pushed the llm-evals branch 2 times, most recently from 94a8730 to ede207c Compare March 24, 2025 20:12
@shykes

shykes commented Mar 24, 2025 •

Copy link
Copy Markdown
Contributor

@vito I like the Container#42 scheme, it's a clever way to simplify. Was wondering if you could simplify even further with selectContainer(number: Int!) to reduce the ambiguity ("do I pass Container#42 or 42 as the ID?" This is a question I myself asked myself reading the PR :) ) and tighten everything even further. Less tokens, more constraints. wdyt?

@shykes

shykes commented Mar 24, 2025

Copy link
Copy Markdown
Contributor

@vito one thing I don't understand in this scheme: if I inject a variable "foo" of type Container in the environment, how is that variable exposed to the llm? As a function?

@vito

vito commented Mar 24, 2025 •

Copy link
Copy Markdown
Contributor Author

@shykes Sweet!

I like the Container#42 scheme, it's a clever way to simplify. Was wondering if you could simplify even further with selectContainer(number: Int!) to reduce the ambiguity ("do I pass Container#42 or 42 as the ID?" :)

Funny you say that, because I tried Gemini without the system prompt and that's immediately what it did. 😂

Agree, will give that a shot!

One risk to consider is that this same value is also what gets passed to function arguments. For example:

  • Container_withMountedDirectory(source: "Directory#1")

Technically, your idea should work here too:

  • Container_withMountedDirectory(source: 1)

But the question is whether the LLM will figure that out. Something tells me the reinforcement of "Directory#1" might help when it's juggling a lot of numbers. But my instincts here could be totally wrong. I'll try!

one thing I don't understand in this scheme: if I inject a variable "foo" of type Container in the environment, how is that variable exposed to the llm? As a function?

Currently, it gets expanded in the prompt like a regular prompt variable - so the pattern is to explicitly reference it:

return m.LLM().
SetDirectory("repo", dag.Git("https://github.com/vito/booklit").Head().Tree()).
SetContainer("ctr",
dag.Container().
From("golang").
WithMountedCache("/go/pkg/mod", dag.CacheVolume("go-mod")).
WithEnvVariable("GOMODCACHE", "/go/pkg/mod").
WithMountedCache("/go/build-cache", dag.CacheVolume("go-build")).
WithEnvVariable("GOCACHE", "/go/build-cache").
WithEnvVariable("BUSTER", fmt.Sprintf("%d-%s", m.Attempt, time.Now())),
).
WithPrompt("Mount $repo into $ctr, set it as your workdir, and build ./cmd/booklit with CGO_ENABLED=0.").
WithPrompt("Return the binary as a File.")

The LLM never actually learns their names at the moment - it just jumps right into action with the Container#1 and Directory#1 values you give it.

To be clear, this tool calling scheme has no concept of variables, or named values, based on the theory that we don't need it to, which needs more testing but seems plausible to me so far. I think if this can work, it's better (more efficient, simpler mechanics).

Essentially, setting a variable for an LLM does two things:

  • Installs it into the namespace, giving it e.g. Container#1, Container#2
  • Sets the ID as a prompt var

If we ever need to, we can maybe preserve a hint in the expanded value, like $repo=Container#1.

@vito

vito commented Mar 25, 2025 •

Copy link
Copy Markdown
Contributor Author

re: "Container#1" vs. 1 I think we'll just have to accept both.

In either case at least one model is probably going to mess up.

@vito
vito force-pushed the llm-evals branch 3 times, most recently from 4fcbbeb to 6675d38 Compare March 25, 2025 15:52
vito added 21 commits March 25, 2025 13:24
one of my tests actually benefits from _undo, so let's just keep them
all enabled, as this was more out of an abundance of caution

Signed-off-by: Alex Suraci <[email protected]>
usage:

    dagger run go test

Signed-off-by: Alex Suraci <[email protected]>
* do a bit of world-building
* clarify immutability/state interaction
* nudge it towards using tools to explore before giving up
* suggest setting a variable at the end
* make system prompt consistent across all models
  * always apply system prompt (previously OpenAI was excepted)
  * allow being overridden (previously Gemini didn't)

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
* don't need _objects if we just add a tool for each var
* listing tools ahead of time helps Gemini realize it needs to select
  tools

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
saw some guessing, don't want none of that

Signed-off-by: Alex Suraci <[email protected]>
This reverts commit 63f4266.

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
kind of silly implementation, but gets the job done

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
vito added 3 commits March 25, 2025 15:13
model behavior seems to vary wildly at the moment - it's pretty hesitant
to follow instructions, but that seems like a problem independent from
the goal of this test

Signed-off-by: Alex Suraci <[email protected]>
vito added 4 commits March 25, 2025 16:10
Explanation in comment. Without this tool gpt-4o reliably refuses to
operate on the current state. The problem goes away by the mere presence
of this tool, without even calling it.

Signed-off-by: Alex Suraci <[email protected]>
so that it knows it can swap back to it, even if it was never told its
ID

currentState ALMOST helps with this, but not really, since it doesn't go
into message history

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
@vito
vito marked this pull request as ready for review March 25, 2025 21:31
@vito
vito requested review from a team as code owners March 25, 2025 21:31
For when you can't/don't want to reference them directly in your prompt.

Tested with GPT-4o and Claude 3.7 sonnet, but Gemini has trouble.

Signed-off-by: Alex Suraci <[email protected]>
@vito vito changed the title llm: refine tool calling scheme, add evals llm: functional tool calling scheme Mar 26, 2025
Comment thread core/llm_env.go
Comment on lines +119 to +120
// strip $foo var prefix
key = strings.TrimPrefix(key, "$")

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.

What does this do?

@vito vito Mar 26, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Mostly a remnant of when it was all variable-oriented, since some models (or even the same model) would opt to include the $ prefix when referencing variables. The general idea is to be liberal in what we accept, considering how moody a lot of models can be, and a lot of them aren't capable of strictly adhering to a format. (Even Gemini has very very limited support for it - only date-time and one other type I can't remember, no regexes)

@vito

vito commented Mar 26, 2025

Copy link
Copy Markdown
Contributor Author

Last few commits made some incremental improvements to the tool scheme:

  • currentSelection: new tool that just provides a hint to the model as to the current state. Makes a significant impact on GPT-4 when given an initial state and asked to do something with it. This might turn into a return of some kind.
  • When the state changes, we now include a "previous":"Foo#123" value. That way the LLM can know how to switch back to the original state, which may have never been referenced by ID.
  • A readVariable tool has been added to read the value of a string variable, with a list of available variables in its description.
  • selectFoo will now list available variables in its description.

@vito
vito requested review from cwlbraa and jedevc March 26, 2025 13:55
vito added 3 commits March 26, 2025 13:21
seems like more models need this than don't

Signed-off-by: Alex Suraci <[email protected]>
dont want the model to think these are the ONLY possible
inputs

Signed-off-by: Alex Suraci <[email protected]>
this is supported, and some models try it

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito merged commit 20e8a17 into dagger:main Mar 26, 2025
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.

2 participants