Plan, Run, Look Again


 

Last time it still could not see its own results

The last post ended with a prediction. The steps were not chained, step two did not see what step one returned, and changing that meant results needed stable names, the plan would stop being a flat list and become a small dataflow graph, with cycles and types that change shape between two steps. "It is not a small change dressed up as one."

It was a small change. I had just solved the wrong problem.

You need a dataflow graph when the whole plan has to be fixed up front. It does not. If the planner sees the results after every round and gets asked again, it simply writes the value from step one into step two as a concrete parameter. The graph never exists, because the model is the dataflow.

The agent, now as a loop

defp loop(%{steps: []} = plan, agent, _context, rounds, _left, _opts),
  do: finish(agent, rounds, plan.reasoning, :answered)

defp loop(plan, agent, context, rounds, left, opts) do
  steps = Enum.map(plan.steps, &run_step(&1, agent, opts))
  rounds = rounds ++ [%{reasoning: plan.reasoning, steps: steps}]

  if left <= 1 do
    finish(agent, rounds, nil, :max_rounds)
  else
    context = %{context | observations: context.observations ++ steps}
    # ... plan again with what the steps returned
  end
end

Plan, run, hand the results back, plan again. An empty step list ends the loop, and the reasoning of that last round is the answer. After five rounds at the most, it stops. The planner's contract did not change: "an empty list is a valid answer" was already in the last post. The only new thing is that the context now carries a section called "Results so far". The line in the prompt I had written back then with such conviction, that steps do not pass their results to each other, has been replaced by one that says: you see the results, plan on.

The mock planner can do it too, so the demo runs without an API key. Given "Count the words in the title of the page www.example.com", it reads the page in round one, counts the words of the title in round two, then answers. Because the mock generator only echoes its parameters, round two counts the words of "url=https://www.example.com". The flow is right, the content is nonsense, and that is exactly what I want from a mock.

The more important part has nothing to do with success. In the old version a failed step was the end of the story. In the loop it is an observation like any other and reaches the planner in the next round, which can try again with different parameters or a different tool. Errors became input. That changed more than I expected when I wrote the loop.

A name is an atom is a file name

Shortly after the loop was merged, the chat crashed with a SystemLimitError.

** (SystemLimitError) a system limit has been reached
    :erlang.binary_to_atom("Elixir.AgentDemo.Actions.Dynamic.ExtractHtmlTitle',
      'description': 'Fetch the HTML title of http:./innoq.com.De'}], ...

The planner had not written a name into the tool name field but half a JSON document. The pipeline turned it into a module name unchecked, an atom, and atoms may be 255 characters at most. The same name also went into the file path "#{name}_v#{version}.ex", so a name like ../../x would have written outside the directory.

The form from the post before last always checked the name. The path through the agent did not, because back then I typed the name myself and the check lived on the page where I typed. Now the pipeline checks it itself, at the point where the name turns into an atom and a path. A broken name is a failed step, and thanks to the loop the planner sees it and can pick a proper one.

Right after the last post the same lesson had caught me once already, only more quietly. The tool list showed the planner every schema key, so it read ai_plan(goal, backend). The planner sees names only, no types, no allowed values, and the prompt tells it to pass what the tool needs. So it filled in backend and guessed "openai". Since then it only sees the required parameters. What you show the model and what you accept from it are two sides of the same boundary, and both times I had only watched one.

The agent moves out of the LiveView

Up to here the conversation lived in the LiveView. Every message ran there in a start_async, a page reload lost the conversation, and the result only arrived once all rounds were done. With a loop that can generate code for five rounds, that means: a minute of spinner, then everything at once.

So every conversation is now a process of its own, a ChatAgent as a Jido.AgentServer, one per /chat/:id. A Jido.Agent.InstanceManager starts it on demand and stops it fifteen minutes after the last tab closed. That was the plan, and it had a flaw I only saw when reading Jido's source.

The AgentServer drains its directives in its own process. RunInstruction calls Jido.Exec.run right there. Had the loop run inside the agent, the server would have been blocked during every planner and generator call, which easily takes half a minute. But AgentServer.state/1 has a five second timeout. A LiveView reconnecting during a running task would have crashed, in exactly the case the whole rebuild was for.

So the agent only keeps the state and never waits. The loop runs in a worker the agent starts with a Spawn directive. The worker reports every planned round and every finished step back as a signal, and the agent publishes the new state over PubSub with an Emit.

The agent keeps the state, the worker waits. That is the only way state/1 stays under five seconds.

A spike beforehand showed two things that were not in the docs where I looked. Without its own Jido instance the agent crashes on the first Emit, because Jido.TaskSupervisor is missing. And an action does not run in the server process, self() was a different pid. The worker therefore gets its agent's address from context.agent_server_pid.

The worker has one rule that is not negotiable: whatever happens, the agent hears chat.finished. Raises, throws, exits, everything is caught and reported as {:crashed, message}. Without that, the agent would have stayed busy forever after the SystemLimitError above and refused every further message.

:ok from a dead process

The next bug was one no test would have found, because it makes no sound. When a ChatAgent crashes, the InstanceManager restarts it right away, under the same id, with a new pid and an empty state. The open LiveView held the old pid. And AgentServer.cast/2 to a dead process returns :ok. Every further message vanished, no error, no log, and the chat kept showing a conversation the new agent no longer knew.

The fix is a Process.monitor. When the agent dies, the LiveView attaches to the new one, clears the chat and says that the conversation starts over. I decided against restoring the old messages: initial_state only applies to the first start, and the restart after a crash is done by the supervisor with the original, empty initial state.

Then I wanted to rule out a race I suspected, and killed and immediately reopened an agent fifty times in a row. The script ended with exit code 0 and no output at all. Not even the warning Erlang prints on every start.

There was no race. Instead the InstanceManager's DynamicSupervisor dies on the fourth crash within five seconds, the OTP default of three restarts in five seconds. It counts across all conversations together. After that the InstanceManager restarts, and every conversation is empty. If those restarts pile up, the same limit trips one level higher, and the application stops. On the fiftieth time, without a word.

The limit and the restart strategy are hard-coded in the InstanceManager. I documented it and did not fix it. The alternative would be building registry, supervisor and idle timeout myself, and for a demo with rare crashes that was too much. It is the part of this post where I am least sure I made the right call.

When does generated code first run?

Since the post before last, code a model wrote runs inside my application, and so far nobody saw it before it ran. I wanted an approval: the chat shows the code, I click, only then it runs. "Before it runs for the first time" sounded unambiguous. It was not.

The obvious moment is the first call. But the compiler already evaluates use Jido.Action and every module attribute while compiling. And the pipeline calls every new action once with the example parameters before handing it out, the trial call from the post before last. An approval before the first call would be too late twice over.

with {:ok, ast} <- Sanitizer.verify(code, module: module, sandbox_dir: sandbox_dir()),
     :ok <- approve(approve, spec, version, code),
     {:ok, path} <- Storage.persist(spec.name, version, code),
     {:ok, module} <- load_or_discard(module, ast, path),
     :ok <- check_schema(module, spec, path),
     :ok <- probe(module, spec, path) do

The approval sits right behind the sanitizer. Code the sanitizer rejects is never shown to anyone, and what is up for approval has not been stored, compiled or run yet.

Code runs from the compiler on, not from the first call. The approval has to come first.

The waiting happens in the worker, not in the agent, for the same reason as above. The worker sends chat.approval_requested and blocks in a receive, the agent puts the open question into its state, the chat shows name, description and code with two buttons. The decision goes back to the worker's pid with an Emit. Only the decision for the question that is open right now counts; a second click or a second tab is ignored. Without an answer the tool counts as rejected after ten minutes, less than the fifteen after which the agent gives up.

A rejection is final. The pipeline repairs every other failure by having the model write a new version, and that is exactly what would be wrong here: a no would immediately bring the next question. Every repair after an approval, on the other hand, is new code nobody has seen, and is shown again.

What the approval is not is written right in the box in the chat: a sandbox. Approved code runs in the same BEAM with the rights of the application. The approval makes the step visible and deliberate, not safe.

The test that was green twice

No sanitizer stops an endless loop or a list that grows until the node runs out of memory. So every tool step now runs in a process of its own with max_heap_size and a timeout, stopped after sixty seconds or above 64 MB. Jido had a say in this: with a timeout, Jido.Exec starts the action in a task of its own under its supervisor, and that task cannot be given a memory limit. With timeout: 0 it runs in the calling process instead, so that is how I call it, inside my bounded process.

I also wanted to switch off the automatic retry. I had seen a refused action twice in the log, and a tool that reads a page should not request it twice. I set max_retries: 0 and wrote a test: a tool that returns {:error, :always} and counts how often it runs. Green. Then I took the fix out again. Still green.

Jido does not retry an action that returns an error, only one that raises. I switched the test to raise, took the fix out, and it was green again. This time because I had set the timeout in that test to 200 milliseconds and Jido waits 250 milliseconds before a retry. My timeout killed the step before the retry could happen, and the assertion accepted any error. Only the third version, with more time and a timeout explicitly ruled out, counts two runs without the fix and one with it.

Green twice, checking nothing twice. Since then I take every fix out once before I believe the test.

On top came a small thing with a big effect. Every call to the Claude API is a POST, and Req only retries GET and HEAD on its own. A single "overloaded" response aborted the whole planning. Even retry: :transient would not have helped, because 529, the status Anthropic uses for overload, is not in Req's list. Now there is a rule of my own with three attempts.

Where the time went

Every response from the Claude API says how many tokens it cost. The application used to throw that away. Now :telemetry spans measure every planner call, every generation, every tool step and every wait for an approval, and under every answer in the chat a table folds out, with duration, tokens and totals.

The nicest part is how the measurements of one run find each other. A telemetry handler runs in the process that emits the event.

def handle_event([:agent_demo, kind, :stop], measurements, metadata, _config) do
  case Process.get(@key) do
    nil -> :ok
    entries -> Process.put(@key, [entry(kind, measurements, metadata) | entries])
  end
end

One handler for the whole application, which only appends to a list in its own process, and that list only exists while the process is inside Trace.collect/1. All four measuring points run in the worker, so the worker gets exactly the trace of its run and nothing from other conversations. The tool step does run in its own bounded process, but the worker wraps its measurement around it from the outside.

The same events feed metrics in the LiveDashboard, without per-tool tags. The model makes up tool names, and one metric per name would grow without bound. It is the same lesson as with the atom, only friendlier.

What it remembers

The history covers the last four turns of a conversation. Anything meant to last, that I live in Hamburg, that I want metric units, was gone with the next conversation. Now there are facts, for all conversations, across restarts, stored as a JSON file. Two built-in tools, remember and forget, and because they are in the hand written catalog, they need no approval. The planner sees every fact with its id in every prompt, and the context is re-read every round, so a fact from round one is already known in round two.

Every fact costs tokens in every prompt, which is why there are at most fifty of three hundred characters each. I left out embeddings and semantic search as long as everything fits into the prompt.

The mock planner reacts to "Remember that ..." and "forget fact N", and one detail needed fixing there. "Remember that I prefer 20 degrees Celsius" contains the keyword for the temperature conversion. Without precedence for the command, the mock would have remembered the sentence and converted twenty degrees to Fahrenheit on the side.

The facts come from the user and go into the prompt unchecked. For a demo with one user that is fine. With several, each would need their own memory.

And one thing I have to add: the tests run against the mocks. Whether Claude plans on sensibly in the loop, what it does after a rejection and when it decides to remember something, they do not cover. That only shows in a real run.

What changed

Last post This post
Who decides the next stepthe planner, once, up frontthe planner, after every round, with the results
What a failed step isthe endan observation for the next round
Where the conversation livesin the LiveViewin one agent process per conversation
When you see progressat the endper round and step, live
When new code first runsunseen, at compile timeafter an approval, before it is stored
What a tool may doas long and as much as it likes60 seconds, 64 MB, once
What a task costunknownduration and tokens per call
What it remembersfour turns of one conversationplus facts across all conversations

If you are thinking of building this

Before you turn a plan into a dataflow graph, try the loop. A model that sees the results chains steps by copying values. That is less elegant than a graph and has none of its failure modes.

Check what comes from the model at the point where it becomes an atom, a path or a module name, not at the point where you expect it. And only show the model what it is supposed to fill in.

Keep the AgentServer free of waiting. It drains its directives in its own process, and anything waiting there waits in front of every state/1. Waiting belongs in a worker that reports back.

Monitor what you cast to. A cast to a dead process returns :ok, and a supervisor restarting things for you only moves the problem to the next message. And look at what your supervisors' restart limits count before a stress test shows you.

Ask exactly when code first runs. For generated Elixir that is the compiler, not the first call. An approval belongs before it, and a no must not trigger a new question.

Take every fix out once before you believe the test.

This time a good 2,000 lines came in and almost 600 went, plus about 1,300 lines of tests. The whole thing is on GitLab at gitlab.com/public_elixir/agent_demo. If you know how to teach the InstanceManager more than three crashes in five seconds without rebuilding it, say so in the comments. I would like to know.

Kommentare

Beliebte Posts aus diesem Blog

Splitting an ML model and a web app across two BEAM nodes — the technical blueprint

Jido in Practice: Agents in Elixir as Composable Actions

A Foundation Model in the BEAM: On-Chain Anomalies with Google TimesFM in Elixir