Skip to content

Continue a conversation

View as Markdown

To continue a conversation, pass the previous run’s transcript with weft.Messages and the new question with weft.Prompt. The agent keeps no history: the conversation is the messages you pass, so you store them between requests and send them back.

Two turns, from conversations/main.go:

conversations/main.go
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
// The next turn: the transcript so far, then the new question.
res2, err := agt.Generate(ctx, weft.Messages(res.Messages...), weft.Prompt("And order 5678?"))
if err != nil {
return err
}

conversations/main.go on GitHub

res.Messages is the full transcript, the input messages included. The second run sends the model three messages: the first question, the first answer and the new question. Its own res2.Messages holds four, ready for the turn after.

weft.Messages adds existing messages to the run’s input; weft.Prompt adds one user message after them. Options apply in order, so put Messages before Prompt. The package example ExampleAgent_conversation is the same two turns.

An agent is an immutable value whose runs share no state. One agent can serve every conversation at once; which conversation a run continues depends only on the messages it is given. The system prompt is not part of the transcript, since there is no system role: each turn uses the agent’s weft.Instructions, or a per-run override (Change an agent’s configuration for one run).

The same pattern resumes a parked run: pass res.Messages back with weft.Approve or weft.Deny (Require human approval for a tool). After a failed run, the partial transcript is on the error’s Result field (*weft.RunError), so you can continue from what the run got done.

A weft.Message is a role plus typed parts, and its JSON encoding is a versioned wire format (weft.SchemaVersion). Marshal the transcript after each run and unmarshal it before the next:

conversations/main.go
// store keeps each conversation's transcript as JSON between requests:
// a database row, a cache entry or a file in a real program.
type store map[string][]byte
func (s store) save(id string, msgs []weft.Message) error {
b, err := json.Marshal(msgs)
if err != nil {
return err
}
s[id] = b
return nil
}
func (s store) load(id string) ([]weft.Message, error) {
var msgs []weft.Message
if b, ok := s[id]; ok {
if err := json.Unmarshal(b, &msgs); err != nil {
return nil, err
}
}
return msgs, nil
}
// reply answers one request of conversation id.
func reply(ctx context.Context, agt *weft.Agent, s store, id, prompt string) (string, error) {
history, err := s.load(id)
if err != nil {
return "", err
}
res, err := agt.Generate(ctx, weft.Messages(history...), weft.Prompt(prompt))
if err != nil {
return "", err
}
return res.Text(), s.save(id, res.Messages)
}

conversations/main.go on GitHub

Each part carries a type discriminator, so the messages decode back into the same typed parts, provider reasoning signatures included. An unknown part type is a decode error, never a silent drop. The complete example prints the first stored message: {"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]}. The messages concept page has the whole format.

To persist a long run step by step instead of at its end, register the weft.OnMessages observer: it receives each batch of messages as it joins the transcript. For durable conversations with a writer lease, queued sends, branches and compaction, use sessions (weft/thread), which store the transcript for you.

The loop repairs the input of every run with the same rule as weft.Repair: every tool call gets a result, and a result with no call is dropped. The one exception is a resume: the calls the earlier run left pending, which this run decides with weft.Approve or weft.Deny, are left for the run to resolve itself. A call whose result never arrived, as a crashed process can leave one, gets a visible error result. The model receives no result recorded: the call was interrupted, and the repaired message is part of the new run’s transcript. The complete example feeds back such a transcript.

conversations/main.go runs the three cases against scripted models:

conversations/main.go
// Command conversations runs the examples of the guide "Continue a
// conversation": go run ./conversations. Every model is scripted with
// wefttest, so it runs offline; swap in a provider adapter for a real one.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"github.com/weftgo/weft"
"github.com/weftgo/weft/wefttest"
)
// continueConversation runs two turns of one conversation.
func continueConversation(ctx context.Context, w io.Writer) error {
model := wefttest.Script(
wefttest.Say("Order 1234 shipped yesterday."),
wefttest.Say("Order 5678 is still pending."),
)
agt := weft.New(model, weft.Instructions("You are a support agent."))
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
// The next turn: the transcript so far, then the new question.
res2, err := agt.Generate(ctx, weft.Messages(res.Messages...), weft.Prompt("And order 5678?"))
if err != nil {
return err
}
fmt.Fprintln(w, "turn 1:", res.Text())
fmt.Fprintln(w, "turn 2:", res2.Text())
fmt.Fprintf(w, "turn 2 sent %d messages; its transcript holds %d\n",
len(model.LastRequest().Messages), len(res2.Messages))
return nil
}
// store keeps each conversation's transcript as JSON between requests:
// a database row, a cache entry or a file in a real program.
type store map[string][]byte
func (s store) save(id string, msgs []weft.Message) error {
b, err := json.Marshal(msgs)
if err != nil {
return err
}
s[id] = b
return nil
}
func (s store) load(id string) ([]weft.Message, error) {
var msgs []weft.Message
if b, ok := s[id]; ok {
if err := json.Unmarshal(b, &msgs); err != nil {
return nil, err
}
}
return msgs, nil
}
// reply answers one request of conversation id.
func reply(ctx context.Context, agt *weft.Agent, s store, id, prompt string) (string, error) {
history, err := s.load(id)
if err != nil {
return "", err
}
res, err := agt.Generate(ctx, weft.Messages(history...), weft.Prompt(prompt))
if err != nil {
return "", err
}
return res.Text(), s.save(id, res.Messages)
}
// stored answers two HTTP-style requests through the store.
func stored(ctx context.Context, w io.Writer) error {
model := wefttest.Script(
wefttest.Say("Order 1234 shipped yesterday."),
wefttest.Say("Order 5678 is still pending."),
)
agt := weft.New(model)
s := store{}
for _, prompt := range []string{"Where is order 1234?", "And order 5678?"} {
text, err := reply(ctx, agt, s, "conv-1", prompt)
if err != nil {
return err
}
fmt.Fprintln(w, "reply:", text)
}
msgs, err := s.load("conv-1")
if err != nil {
return err
}
first, err := json.Marshal(msgs[0])
if err != nil {
return err
}
fmt.Fprintf(w, "stored %d messages; the first is %s\n", len(msgs), first)
return nil
}
// repaired feeds back a transcript whose last tool call never got its
// result, as a crashed process leaves it.
func repaired(ctx context.Context, w io.Writer) error {
model := wefttest.Script(wefttest.Say("The lookup was interrupted; let me try again."))
agt := weft.New(model)
interrupted := []weft.Message{
weft.User("Where is order 1234?"),
{Role: weft.RoleAssistant, Content: []weft.Part{
weft.ToolCallPart{ID: "call_1", Name: "lookup", Args: json.RawMessage(`{"order_id":"1234"}`)},
}},
}
if _, err := agt.Generate(ctx, weft.Messages(interrupted...), weft.Prompt("Hello?")); err != nil {
return err
}
for _, m := range model.LastRequest().Messages {
for _, p := range m.Content {
if r, ok := p.(weft.ToolResultPart); ok {
fmt.Fprintf(w, "the model received for %s: %q (error: %t)\n", r.CallID, r.Content, r.IsError)
}
}
}
return nil
}
func run(ctx context.Context, w io.Writer) error {
steps := []struct {
title string
fn func(context.Context, io.Writer) error
}{
{"continue", continueConversation},
{"store between requests", stored},
{"repair", repaired},
}
for _, s := range steps {
fmt.Fprintf(w, "== %s\n", s.title)
if err := s.fn(ctx, w); err != nil {
return fmt.Errorf("%s: %w", s.title, err)
}
}
return nil
}
func main() {
if err := run(context.Background(), os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View conversations/main.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./conversations
go test ./conversations
== continue
turn 1: Order 1234 shipped yesterday.
turn 2: Order 5678 is still pending.
turn 2 sent 3 messages; its transcript holds 4
== store between requests
reply: Order 1234 shipped yesterday.
reply: Order 5678 is still pending.
stored 4 messages; the first is {"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]}
== repair
the model received for call_1: "no result recorded: the call was interrupted" (error: true)
  • Store res.Messages, not a rebuild from events. The transcript holds the exact parts, signatures and block boundaries; events are a lossy view of them. (Source: weft/core/run.go:551-574, OnMessages godoc)
  • Send the history back every turn. A run with no Messages starts a new conversation; the agent remembers nothing between runs. (Source: ExampleAgent_conversation, TestAgentHoldsNoHistory)
  • Do not edit stored transcripts by hand to fix them. The loop repairs what it is given, and the repair is visible to the model. (Source: weft/core/repair.go:5-16, AGENTS.md rule 2)
  • Bound what you send, not what you store. A long history costs tokens on every call; trim the request with PrepareStep and keep the full transcript. (Source: weft/core/agent.go:154-175)

Symbols used: weft.Messages · weft.Prompt · RunResult.Messages · RunResult.Text · weft.Message · weft.SchemaVersion · weft.Repair · weft.RunError · weft.Instructions · weft.OnMessages · Agent.Generate · weft.ToolCallPart · weft.ToolResultPart · wefttest.Script · ExampleAgent_conversation