{mvGPT}
  • Episode 25
  • 27 min

AI agent with a graph database and a calculator

Our agent gets a fourth role, which queries smollerGraph in Cypher, so it can take two facts from a graph database and combine them with the calculator, and we measure what it kept of its old tasks.

Watch on YouTube

Open in Colab

In this episode, our agent gets a fourth role. Next to the calculator and the files, it can now hand a question to a subagent that writes a Cypher query for smollerGraph, the graph database we build from scratch in its own series. So asked how much heavier the king penguin is than the great white pelican, it asks the graph twice and the calculator once. We generate forty-five thousand examples, almost half of them the agent's old tasks, fine-tune episode twenty-four's model for thirty minutes on the laptop, and measure the new tasks, the graph role on its own, and what the agent kept of its old tasks.

Topics: Agents

The code

Each step on screen is a tag in the code's repository. The code at the end of the episode is ep025/end.

  1. 3:05ep025/step-1A fourth roleBrowseChanges
  2. 5:04ep025/step-2The tasksBrowseChanges
  3. 10:51ep025/step-3Fine-tuningBrowseChanges
  4. 14:55ep025/step-4Measuring itBrowseChanges
  5. 25:18ep025/step-5In the chat appBrowseChanges

Transcript

Intro

0:00 Hello and welcome back to episode twenty-five, where our agent gets a fourth role, one that asks smollerGraph, the graph database from last time, so that it can put facts from the graph and the calculator together in one answer. Let's begin with a quick look at where we're going to be by the end of the episode.

0:16 By the end of today, we ask our agent how much heavier the king penguin is than the great white pelican, two birds that training doesn't ask about, and it hands the question out. A graph subagent queries smollerGraph for each weight, a math subagent works out the difference, and the agent answers about two thousand six hundred and thirty grams. Asked whether the king penguin and the African penguin share a family, it asks the graph twice, and compares the two names on its own: both are in Spheniscidae.

0:45 On the website of the series, you can find more information about the project. The code is open source on GitHub, tagged at each step of each episode, so that you can follow along, and the docs get a page on the agent asking the graph today. And each episode has a page here as well, with its chapters and its code.

1:04 Now, before we get to today's work, let's quickly go over what we did last time. Our model learned to write Cypher queries for smollerGraph, the graph database we build from scratch in a series of its own, and to answer from what came back. On species that training didn't ask about, it answered about eighty-nine percent right, and with the graph off, none. Before that, in episode twenty-one, it became an agent, which hands parts of a task to subagents: a math role with the calculator, and a files role. Last time, the queries were a model of their own, answering one question each. Today, the query becomes a role of the agent, so it can ask the graph for facts and then do something with them.

1:45 Today, the agent gets a fourth role, graph, which writes last time's queries in a context of its own and hands back its sentence. We generate tasks that need a fact or two from the graph, and for those about weights, a sum as well, and keep the agent's old tasks in the mix. We fine-tune last episode's model on them for thirty minutes on the laptop. We measure the new tasks, the graph role on its own, and how much of its old tasks the agent kept. And we run it in episode twenty-one's chat app, which shows each subagent's steps. All right, let's get started with the roles.

A fourth role

2:20 The agent is one model, with a line at the top of its prompt that says its role, and the tools that role may call. The agent hands work out with ask math, ask files and now ask graph, and writes and lists files on its own. Each ask starts a subagent, which is our model's weights again, in a fresh context and another role. Math has the calculator, files reads and writes in a sandbox, and the graph's one tool is a Cypher query to sg serve. The graph role gets no calculator, so each subagent does one job, and putting the facts together is the agent's job. When a subagent finishes, all that goes back to the agent is its answer, and for the graph, that's its whole sentence, as we're going to see in the code.

3:06 The role goes in agent dot py, from episode twenty-one. We import two names from last episode's graph dot py: server, where sg serve is listening, and run query, which sends a query and turns sg's answer into text. The comment above the roles now says one model, four roles, and that the agent delegates to the other three. The agent's tools get ask graph, next to ask math and ask files. And the graph role gets a single tool, cypher, last episode's call. Next is what a subagent hands back to the agent when it's done. Math and files hand back the first number of their final sentence, which is all the agent needs from a sum. The graph hands back its whole sentence instead, without the full stop. The comment says why: the graph's facts are names as often as numbers, and the three in a list's and three more isn't the answer. The old comment goes under it, now for math and files. The agent takes a server, which defaults to the one graph dot py reads from the SMOLLERGRAPH variable, and keeps it for the graph's queries. When a call is cypher, it goes to run query with the agent's server. As the comment says, it's last episode's query, as plain text, to sg serve, which can read the graph and can't change it. So the limits come with it: three hundred characters at most, and five rows, with the rest counted. And the command line gets dash dash server too, for when sg serve is somewhere else. The tests get three more, with episode twenty-one's scripted model, and a stand-in for run query. The first scripts a graph subagent that lists five cats and three more, and checks that the agent gets the whole sentence back, not the three. The second checks that the roles keep to their tools: the agent writing a query on its own gets no such tool, and so does the graph role asking for the calculator. And the third checks the agent's and the graph's lines of tools.

The tasks

5:05 First, a small change to last episode's graph data dot py: rank and property, which write a question about a species, take a wording, so a caller can ask one way each time instead of a random one. Graph agent data dot py makes the agent's new tasks. It imports prompt from agent dot py, which writes a role's first lines. From episode twenty-one's agent data dot py, it takes its maker for file names, its load, show, and trace, which builds an example from its calls and their results. From graph data dot py, it takes the share of each kind of question, its maker and read facts, and calculate from tools dot py, so each sum in the data is the calculator's. Train is forty-five thousand examples, and the share says what's in them. Forty-five percent is episode twenty-one's examples, so the agent keeps its three roles, and a quarter is last episode's questions, under the graph role's line. The rest is the new tasks: how much heavier one species is than another, two weights together, a weight in kilograms, and whether two species share a family. And two more: a question handed to the graph as it's asked, and a fact from the graph saved to a file. Unknown and missing are how often a task about weights names a species the graph has no weight for, or one it hasn't got at all. Then how the agent asks the graph: one way for a weight and one for a family, both from last episode's training wordings. So the graph role stays on wordings it was trained on, and new wordings are for the agent to read. Tasks holds the wordings of each new task: two to five that training uses, and one held out, like how much more weight does the penguin carry than the pelican. As the comment says, episode twenty-one's held-out wordings stay out as well, so its held-out sets still measure something. Question text takes the question out of one of last episode's examples, and handed back is what the agent gets from a graph subagent, its final sentence. As role puts last episode's example under the graph role's line, with its query, sg's answer and its sentence as they were. And the next function gives episode twenty-one's examples the agent's new line of tools, on a copy. The maker builds the new tasks, and its docstring says how: each fact comes from a graph subagent, whose sentence is built from sg serve's answer, and each sum from the calculator, so the examples can't disagree with the database. Fact is a graph subagent's run for one fact: the agent's call, the sentence it gets back, sg's own answer, and the subagent's example, which the tests replay through agent dot py. Weights makes the heavier, together and kilograms tasks. It picks one or two species with a weight, and in the unknown and missing cases, swaps one for a species with no weight, or a name the graph hasn't got. For heavier, the heavier species goes first, as the question asks it that way round. Then the calls go in order, and the agent stops at the first weight it can't get, and says why, so it doesn't make a number up. With both weights, it asks math for the difference, the sum, or the weight over a thousand, and writes its sentence with the calculator's answer. Same family asks the graph for two families, half of the pairs from one family, and the agent compares the two names with no calculator. Delegate hands one of last episode's questions to the graph as it's asked, the way episode twenty-one's agent hands word problems to math. And graph save gets a fact and writes it to a file with episode twenty-one's write. Build mixes the training set from one seed and shuffles it. The held-out sets come from a generator of their own, about species and families that training doesn't ask about, and in the phrasing set, file names it doesn't use. Seen is the training's wordings, phrasing is the held-out ones, and unknown is the tasks where a weight or a species is missing. It writes each set, and prints its counts, how many queries it sent to sg serve, and how many found nothing. The tests swap sg serve for a stand-in on a small graph of big cats and a bear. They check that the heavier one comes first, and that the lion against the tiger gives seven thousand grams. And each kind of task is replayed through agent dot py, with a scripted model writing the example's own text, so what the data says comes back from a call is what the runtime gives back.

9:25 We run the agent's tests and the new ones with pytest, and all fourteen pass, with no model and no database, as scripted models write the calls and a stand-in answers for sg serve.

9:36 We run it with smollerGraph's facts file, and sg serve running on port eighty-four eighty-four. It prints the size of each set, then an example of each new task. It writes about forty-five thousand training examples, and took about twenty thousand distinct queries to sg serve, of which about thirteen hundred found nothing, mostly names the graph hasn't got. In the examples, the parts the model is given are in square brackets. Asked which family a hummingbird belongs to, the agent hands the question to the graph word for word. Under it, indented, is the graph subagent's own run: its query, sg's answer, and the sentence that goes back. And in the last one, the graph has no weight for the second species, a skunk, so the agent stops at that call, and says that it can't answer.

10:25 The held-out sets have two hundred tasks each, about species and families that training doesn't ask about. The first uses the training's wordings, so the agent has to copy names it wasn't asked about in training into its calls. The second asks each task in the wording held out for it, with file names training doesn't use. And in the third, a weight is missing from the graph, or a species isn't in it, and the right answer is to say so, not to make up a number.

Fine-tuning

10:52 Graph agent SFT dot py follows episode twenty-one's agent SFT dot py, so most of it is familiar. It imports what that did, shutil and tempfile among them, for a folder the demo can use as its sandbox. From agent dot py, it takes the agent, the sandbox and show, for the demo, and from agent SFT, batches, which groups examples of like lengths. From tool SFT, it takes the learning rate, encode, make batch and estimate loss, with the mask that leaves the prompt and the tools' results out of the loss. Run dir is checkpoints, graph agent, and it evaluates each two hundred and fifty steps. The demo is the okapi against the Baikal seal, and the comment says why: two weights from the graph and a subtraction, mvGPT, smollerGraph and the calculator in one answer, about two species that training doesn't name. Main fixes the seeds, for torch and for Python's random, which shuffles the batches, so each run draws them in one order. It picks the device, the Mac's GPU here, and loads last episode's model, the agent fine-tuned to write Cypher. As the comment says, that model already writes the queries, and now it has to write them as a role of its own. Block size is the context, a thousand and twenty-four tokens, and encode cuts an example that's longer than that. It encodes the training set and the held-out seen set, and prints how many tokens there are to learn, as each example's mask counts them. The optimizer is AdamW, with weight decay on the matrices and none on the biases and gains, as before, and the writer logs the run for TensorBoard. Each evaluation measures the loss on the two hundred held-out examples, in order, so the evaluations compare like with like. Then it runs the demo through the agent, with a fresh temporary folder for its sandbox, which it deletes after, so the demo can't leave files behind for the next one. The demo asks sg serve, as the agent will, so sg serve has to be running. It logs the loss and the run to TensorBoard, and prints the step, the loss and the whole tree of calls, with each subagent's under the agent's. Then it puts the model back in training mode. The loop runs against a budget in seconds. When its queue of batches runs out, it draws a fresh pass from batches, of about six thousand tokens each, so a short example doesn't wait on a long one's padding. Then the forward and backward passes, the gradients clipped to a norm of one, and the optimizer's step, and the counts of steps and examples seen go up. Each fifty steps, as the comment says, batches come in many lengths, and PyTorch keeps memory for each shape it has seen, so on the Mac's GPU, it gives that memory back. Then it logs the batch's loss, and prints it with the minutes so far, and each two hundred and fifty steps, it evaluates. At the end comes a last evaluation, the model goes to checkpoints, graph agent, and it prints the steps, the examples and the passes. Thirty minutes is the default, as for episode twenty-one's agent.

13:53 Then thirty minutes on the laptop, with sg serve running for the demo. There are about two point five million tokens to learn. At step zero, before any training, last episode's model is asked as the agent, and writes a Cypher query on its own, which the agent's role doesn't have, so it gets no such tool. From step two hundred and fifty on, the agent hands the okapi's weight to the graph, as it should. But the graph role copies the name wrong into its query, here as Oakapi, and sg finds nothing. So the agent stops there, and says that the graph has no okapi, which is the right thing to do with what came back. Each evaluation goes that way, with Ookapi and Otapi along the way, and we're going to come back to the okapi. The held-out loss falls from about three point zero to about zero point zero one five by step two hundred and fifty, and stays about there. In thirty minutes, it takes about seventeen hundred steps, and sees about fifty-three thousand examples, about one point two passes through the training set.

Measuring it

14:56 First, attempt, in episode twenty-one's agent eval dot py, runs a task and checks its answer and its files. It now also returns the calls the agent made, each with its result. Graph agent eval dot py measures three things: today's tasks, the graph role on its own, and what the agent kept of episode twenty-one's tasks. It imports argparse, json, os, and a default dictionary, which starts each new key with an empty list. Then episode twenty-one's agent data and last episode's graph data, as modules, for their held-out sets. From agent eval, it takes attempt and summary, and then the checkpoint loader, the server, and as role and load from today's data. The results folder comes from hellaswag dot py, and pick device from the model. New sets are today's three held-out sets: seen, phrasing and unknown. Graph sets are last episode's held-out questions, which we ask the graph role, and old sets are episode twenty-one's five held-out sets. Facts reads the answers that the graph subagents should bring back, from a task's trace: the result after each ask graph, without the equals sign in front. For the penguin and the pelican, those are the two sentences with the weights. Before reads a set's score from an earlier episode's results, when the file is there, for the comparison. When it isn't, before returns none, and the table prints a dash instead. Main is a command line, and its parser says what the script is for: how well the agent asks the graph, and what it kept of the rest. It takes the checkpoint, dash dash limit for a quick look at the first examples of each set, and dash dash server, for where sg serve is listening. It loads the model on the GPU, and names the results after the checkpoint's folder, graph agent here. The results start as the model's name and an empty dictionary of sets, which fills up with a key for each set as it goes. Agent for makes an agent for a sandbox, with the server, which is how attempt runs each task in a folder of its own. Then it prints the first table's header: the set, the share right, facts right, and the calls, subagents and tokens, on average. For each of today's sets, it loads the set, cut to the limit when there is one, and attempts each task. Attempt runs the agent greedily, and checks its final sentence and its files against the example's. Then main notes whether the graph subagents brought back what the task needs. Facts right takes the results of the agent's calls to ask graph, in order, and compares them with what facts read from the example. As the comment says, when they did, and the answer is wrong anyway, the slip came after the graph: in the agent, or in the math it asked for, a number copied wrong, say. When they didn't, it went wrong before that, with a name copied wrong, say. On the seen and phrasing sets, it keeps each task's right or wrong under its kind, as the unknown set's tasks are of another sort. It sums up each set with episode twenty-one's summary, the share right, the calls, the subagents and the tokens. Then it adds facts right, and each kind's share right, as its right answers over its tasks in the set, for each kind the set has. It keeps three wrong answers, to read later, and prints the set's row, with each column padded to the header's width, so the table lines up. Over the seen and phrasing sets together, each kind's share right is its list's right answers over its length. Then the kinds are sorted by their share right, with a minus sign in the sort key so the best come first, and a line prints each kind with its share as a percentage. The second table is the graph role on its own, and its comment says where the questions come from: graph data dot py's held-out sets, which last episode measured its model on. Its header has a column for last episode's score. It asks the four hundred questions, each put under the graph role's line by as role, so the graph answers with no agent above it. It sums each set up as before, keeps it under graph and the set's name, and reads last episode's score from its results file, with a dash when that file isn't there, and then it prints the row. The third table is episode twenty-one's held-out tasks, which the comment says the new ones mustn't have cost, measured as agent eval dot py measured them. Each task runs in its own role, as it did then, with a fresh sandbox. Each set's summary gets episode twenty-one's score, read from its results file, and three wrong answers, and it's kept under episode twenty-one and the set's name. Then is that earlier score as a percentage, or a dash when there's none, so the row prints either way. Each row prints the score now next to the score then, which shows what the agent kept. Once the three tables are done, it goes back to today's sets, and prints a wrong answer from each, under the tables, so we can see what a miss looks like. And it saves it all to results, as graph agent, then the model's name, dot JSON, for the charts to read.

20:01 It runs each task through the agent, with sg serve answering the graph's queries, then last episode's questions and episode twenty-one's tasks, so it takes about half an hour. At the end, it prints a wrong answer from each of today's sets, and each goes wrong in another place. In the first, the facts came back right, and the calculator worked out nineteen sixty-four. But the math role wrote the answer is sixty-four, dropping the nineteen, and the agent copied that into its answer. In the second, keep the answer in a file is a held-out wording, and the agent answers the question, and writes no file. And in the third, the graph role copies a vole's name wrong into its query, and sg finds nothing. The sentence it hands back has the name right, so it reads as if the graph hadn't got the species, where the graph has it, with no weight.

20:52 Side by side: in the wordings it trained on, the agent does about eighty-eight percent of the new tasks right, about species that training doesn't ask about. In new wordings, about thirty-four, where the facts it needed came back about sixty-nine percent of the time. And when the graph has no weight, or no such species, it says that it can't answer, and why, about eighty-nine percent of the time.

21:17 By task, in the new wordings, the questions it hands to the graph as they're asked do best, at about eighty-three percent. The agent passes them on word for word, so the new wording is the graph role's to read. For the others, the agent maps a new wording onto a task it knows, and does that task. How much does it weigh in kg gets the weight in grams, with no division. What would two species weigh on one scale gets a subtraction, as for heavier. And keep the answer in a file gets the answer, and no file.

21:49 Then the graph role, asked last episode's four hundred questions on its own, under its role line. It gets about eighty-eight percent of the seen wordings right, against about eighty-nine for last episode's model, and about seventy-seven percent of the new ones, against about eighty. So the queries came through the move into a role nearly as they were.

22:10 And this is what the agent kept of episode twenty-one's tasks. In the wordings it trained on, it kept nearly all of it, at about ninety-seven percent for the files. Those wordings are almost half of today's training. In the wordings episode twenty-one held out, the files role went from about forty-nine percent to about eleven: asked how much three files come to altogether, it reads a file called numbers dot t x t, which isn't there. And the agent went from about twenty-three to about one. Between episode twenty-one and today, there are two fine-tunes, last episode's and today's. At step zero, last episode's model, asked as the agent, wrote a query of its own, so today's training brought the agent back on the wordings it repeats. Starting from episode twenty-one's agent instead is the run that would tell us which of the two fine-tunes cost the held-out wordings.

Asking it

23:01 Now a few tasks of our own, about birds and mammals. The king penguin's weight in kilograms takes a graph subagent for the weight, and a math one to divide it by a thousand: about twelve point one five kilograms. The two penguins together stop at the second call, as the graph has no weight for the African penguin, and the agent says so. The African penguin's family, saved to a file, takes the graph, then the agent's own write, and notes dot t x t shows up in the files. The lion against the tiger gives seven thousand grams, so the lion is the heavier. Most sources have the tiger as the heavier cat, and the agent's answer is as good as Wikidata's numbers, which is what looking it up buys us: the numbers are the source's, not the model's. And the okapi against the Baikal seal, the demo from training, fails as it did there: the graph role writes Oakapi, sg finds nothing, and the agent says that the graph has no okapi. Last episode's model, asked the okapi's weight on its own, writes Ookapi, so it's not something today's training broke.

24:05 The okapi is last episode's space in the name again. In the question, our tokenizer writes the okapi as three tokens: space O K, then A P, then I, with the word's space at the start of its first token. Inside the query's quotes, there's no space, so the first token has to be O K without it, which is a different token. No name in today's training queries for the graph role starts with that token, so the model hasn't learned to write it there. It writes an O, then guesses at the rest, A K, O K or T, and copies A P and I. And as we saw, last episode's model does it too, so it's not something today's training broke.

In the chat app

24:46 Last, the agent in episode twenty-one's chat app, which we start with the new model, and the SMOLLERGRAPH variable set, so its graph role can find sg serve. We type the demo's task, how much heavier the king penguin is than the great white pelican. Each subagent shows as a step of its own as it runs: the graph for each weight, then math for the difference, and the agent's answer under them. Opening the king penguin's step shows the graph role's own call, the Cypher query and sg's answer, then the sentence it handed back, and the size of its context.

25:19 And the docs get a page on the agent asking the graph: the role and what it hands back, the tasks and their held-out sets, the fine-tuning, and the three tables. It goes at the end of the navigation, after last episode's page on smollerGraph, and the README gets the commands.

Wrap-up

25:35 Now, let's go over what's real here, and what's scaled down. Splitting the work is how Anthropic's research system from episode twenty-one works: an agent hands a part of a task to a subagent with the tools for it, and gets back an answer, not the subagent's whole context. And the facts come from a real database, through queries the model writes, with the sums done by a calculator, so the numbers in the answer are the source's. The tasks are scaled down: they come from templates, in a few wordings each, about weights and families. And the agent asks the graph in one fixed wording, which keeps the graph role on wordings it was trained on. As we saw, fine-tuned on templates, our model follows them closely, and a new wording is where it slips.

26:20 So, today our agent got a fourth role, graph, which writes a Cypher query for smollerGraph in a context of its own, and hands its sentence back to the agent. We generated tasks that need a fact or two from the graph, with a sum for those about weights, along with the agent's old tasks. After thirty minutes of fine-tuning from last episode's model, it does about eighty-eight percent of the new tasks right in the training's wordings, about species that training doesn't ask about, and says so when a fact is missing. In new wordings, it does about thirty-four percent, as it maps them onto a task it knows. And on episode twenty-one's tasks, it kept the wordings it trained on, and not the ones it held out.

27:02 If there's a question you'd ask our agent about mammals and birds, with a sum in it, let me know in the comments, and I'll try it. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.