Keep the History and Send It Every Time

In the last video, the partner forgot Mei’s name one message after she said it, because each call carried only her newest message. The rough fix put every turn into one string with Member: and Partner: labels and sent that string as the input. It worked, but to the provider, that whole string was one long member message, labels included.

In this lesson, you’ll keep the conversation as a list of messages, each marked with who said it, and send the whole list with every call. You’ll also see the request each provider receives. Start with the shape those messages take.

Send the Turns as Messages With Roles

The labels only hide the problem: the provider can’t tell which lines the model wrote earlier and which ones the member typed. Both APIs have a better form for a conversation: a list of messages, each an object with a role and its content.

A message from the member has the role "user", and one of the model’s own earlier replies has the role "assistant". After Mei’s first exchange, her history looks like this:

Language: JavaScript
[
  { role: "user", content: "Hola, me llamo Mei. Es mi..." },
  { role: "assistant", content: "¡Hola, Mei! ¿Qué te..." },
]

The partner’s instructions don’t go in the list. They stay in instructions, sent with every turn and kept separate from what the member said.

One name can trip you up, though. The role argument of streamAnswer(), such as "fast", picks a model, while the role of a message says who wrote it. The two only share a word.

To accept a history, streamAnswer() gets a new argument, messages. Open model/index.js and change the start of streamAnswer() to this:

Language: JavaScript Filename: model/index.js
export function streamAnswer({
  instructions,
  messages,
  input,
  role = "capable",
  signal,
}) {
  const { adapter, model } = pickModel(role);
  const turns = messages ?? [{ role: "user", content: input }];
  const request = {
    model,
    instructions,
    messages: [...turns],
    maxOutputTokens: settings.maxOutputTokens,
    roleSettings: adapter.ROLE_SETTINGS[role],
  };

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.