Documentation
Conversations
One process per conversation: started when it is spoken to, publishing its events on a topic of its own, ended when idle, with its history kept outside it.
A process per conversation
A conversation is a receive loop. It loads what was said before, starts the topic its events go to, and then takes what the user says, one thing at a time. A turn can take as long as the model does; what is said meanwhile waits in the mailbox and is answered in its turn, so a conversation needs no lock and no queue of its own.
// run is the conversation's process: a receive loop, since all it takes is
// what the user says, one thing at a time. With nothing said for a while it
// returns, and the process ends; its history stays, for the next one.
func (c *conversation) run(p *grpcproc.Process[proto.Message]) (err error) {
if c.turns, err = c.history.Load(p.Context(), c.id); err != nil {
return err
}
// The topic is the conversation's: linked to it, it ends when this
// process does, and whoever follows it is told.
// The topic of the process before this one ends a moment after it, and
// has the name until then.
for {
c.events, err = pubsub.SpawnOwned[*conversationsv1.Event](p, pubsub.Config{Buffer: 1024},
grpcproc.WithName(conversationsv1.ConversationEventsTopic(c.id)))
if !errors.Is(err, grpcproc.ErrNameTaken) {
break
}
select {
case <-p.Context().Done():
return p.Context().Err()
case <-time.After(time.Millisecond):
}
}
if err != nil {
return err
}
c.replay(p)
idle := time.Now().Add(c.limits.Idle)
for {
m, err := p.ReceiveTimeout(time.Until(idle))
if errors.Is(err, context.DeadlineExceeded) {
return nil // idle: a normal end, so the supervisor leaves it at that
}
if err != nil {
return err
}
say, ok := m.Body.(*conversationsv1.Say)
if !ok { // a message of another type, or a Down: nothing here waits for one
_ = m.Reply(nil, grpcproc.ErrType)
continue
}
if say.GetText() == "" {
_ = m.Reply(nil, errors.New("conversations: nothing was said"))
continue
}
// Answered as the turn begins: the caller is told its place, and
// does not wait for the model. What is said meanwhile waits in the
// mailbox, and is answered in its turn.
idle = time.Now().Add(c.limits.Idle)
c.turn++
_ = m.Reply(&conversationsv1.Said{Turn: c.turn}, nil)
if err := c.answer(p, say.GetText()); err != nil {
return err
}
}
}Say is a call, and it is answered when its turn begins, not when the model is done: the caller learns which turn it is, and the answer goes to whoever follows the conversation. With nothing said for Limits.Idle, ReceiveTimeout returns and so does the function: the process ends, normally. A million conversations nobody is having cost nothing. A browser left open on one does count as somebody: when the process ends, it follows again, which starts the process again.
Started when spoken to
The service's supervisor has no children of its own. It has a factory: a function from a message to a child's spec, which actor.StartChildFrom calls by name, from this node or another. The child is registered under a name made from the conversation's id, so starting one that runs already fails with ErrAlreadyStarted, and two requests for one conversation can never start two processes. The id comes from a URL and becomes part of a registered name, so the factory takes only letters, digits, - and _.
// tree is the service's supervision tree: a supervisor with no children of
// its own, and a factory for the one kind it is asked for. A conversation is
// Transient: started again if it crashes, which loads its history back, and
// left alone once it ends for being idle.
func tree(cfg platform.Config, history History, limits Limits, scope *groups.Scope) actor.ChildSpec {
return actor.ChildSupervisor(conversationsv1.Service, actor.Spec{
Factories: map[string]actor.Factory{
conversationsv1.Factory: actor.ChildFactory(func(open *conversationsv1.Open) (actor.ChildSpec, error) {
if !conversationsv1.ValidID(open.Id) {
return actor.ChildSpec{}, fmt.Errorf("conversations: %q cannot name a conversation", open.Id)
}
c := &conversation{
id: open.Id, node: cfg.Node, history: history, limits: limits, scope: scope,
tools: toolsv1.RunnerAt(cfg.Where(toolsv1.Service)),
}
inspect := grpcproc.WithInspect(func() map[string]string {
return map[string]string{"turns": strconv.FormatUint(c.turn, 10), "said": strconv.Itoa(len(c.turns))}
})
name := conversationsv1.ConversationProcess(open.Id)
return actor.ChildFunc(name, c.run, inspect, grpcproc.WithLabel("conversation")).WithRestart(actor.Transient), nil
}),
},
})
}The contract's address hides this. Say opens the conversation and then calls it, so its callers never ask whether a process runs. A process may end for being idle between the two; the call then fails with ErrNoProc, and the conversation is opened once more.
// open starts the conversation's process, unless it runs already. A
// conversation that has been idle ends its process; opening it again starts
// one, with what was said before.
func (c Conversation) open(ctx context.Context, from grpcproc.Caller) error {
sup := grpcproc.Name{Node: c.node, Name: Service}
_, _, err := actor.StartChildFrom(ctx, from, sup, Factory, &Open{Id: c.id})
if errors.Is(err, actor.ErrAlreadyStarted) {
return nil
}
return err
}
// Say tells the conversation what the user said, and returns once its turn
// has begun: after the turns before it. The answer is published to whoever
// follows the conversation. A process that was idle may end between its
// opening and the call: it is then opened again, once.
func (c Conversation) Say(ctx context.Context, from grpcproc.Caller, text string) (said *Said, err error) {
for range 2 {
if err = c.open(ctx, from); err != nil {
return nil, err
}
if said, err = c.ConversationAddr.Say(ctx, from, &Say{Text: text}); !errors.Is(err, grpcproc.ErrNoProc) {
break
}
}
return said, err
}A conversation is Transient: its supervisor starts it again if it crashes, and leaves it alone when it ends for being idle. WithInspect gives grpcprocctl inspect something to show for it: how many turns it has had.
State outside the process
What was said lives in a History, not in the process. Each turn is appended as it is said, and a process that starts loads it and publishes it to its new topic, for whoever follows. So a conversation that was idle comes back knowing what was said, and so does one that crashed: the turn it was in is lost, the turns before it are not. The history is an interface the container serves; the tutorial's keeps it in memory, and a database would be built, started and stopped the same way.
// History keeps what was said in each conversation, outside the process
// that holds it. The guide keeps it in memory; a real History is a database,
// which the container builds, starts and stops the same way.
type History interface {
Load(ctx context.Context, id string) ([]*modelsv1.Turn, error)
Append(ctx context.Context, id string, turn *modelsv1.Turn) error
}A turn
A turn is a loop: the model answers, and for as long as it asks for a tool, the tool is run and the model answers again. The models and the tools belong to other services, perhaps on other nodes; the conversation calls them through the methods of their addresses, as its process p, under a deadline.
// answer is one turn: the model answers, and for as long as it asks for a
// tool, the tool is run and the model answers again. A turn that cannot be
// finished is published as failed, and the conversation goes on; an error is
// the history's, and ends the process.
func (c *conversation) answer(p *grpcproc.Process[proto.Message], text string) error {
if err := c.said(p, &modelsv1.Turn{Role: modelsv1.Role_ROLE_USER, Text: text}); err != nil {
return err
}
_ = c.publish(p, &conversationsv1.Event{Kind: &conversationsv1.Event_Said{Said: text}})
for range 4 { // a model that keeps asking for tools is stopped
out, err := c.generate(p)
if err != nil {
_ = c.publish(p, &conversationsv1.Event{Kind: &conversationsv1.Event_Failed{Failed: err.Error()}})
return nil
}
if err := c.said(p, &modelsv1.Turn{Role: modelsv1.Role_ROLE_ASSISTANT, Text: out.Text, Tool: out.Tool}); err != nil {
return err
}
if out.Tool == nil {
_ = c.publish(p, &conversationsv1.Event{Kind: &conversationsv1.Event_Done{Done: true}})
return nil
}
ran := c.call(p, out.Tool)
result := ran.Output
if ran.Failed != "" {
result = modelsv1.ToolFailed + ran.Failed
}
if err := c.said(p, &modelsv1.Turn{Role: modelsv1.Role_ROLE_TOOL, Text: result}); err != nil {
return err
}
}
_ = c.publish(p, &conversationsv1.Event{Kind: &conversationsv1.Event_Failed{Failed: "the model asked for too many tools"}})
return nil
}A turn that cannot be finished is published as failed and the conversation goes on. An error from the history ends the process, and the supervisor starts one that loads what the history has.
A topic of its own
Each conversation owns a pub/sub topic, started with pubsub.SpawnOwned: it is linked to the conversation and ends when it does, which its subscribers learn from a Down. The conversation publishes what the user said, the tools it calls and the end of each turn; the tokens are published by the process generating them, on the GPU node, straight to the topic. The topic keeps the last 1024 events, and a new subscriber receives those first, so a browser that connects in the middle of an answer is sent the answer so far. A process that starts with a history publishes it to its new topic first, as the events it was, so the same holds after the conversation was idle; of one longer than the topic keeps, a follower is sent the end.
Follow asks the conversation nothing: in the middle of a turn it would not be answered until the turn is over. It opens the conversation and subscribes to the topic by name. StartChildFrom returns once the process is started, which is a moment before it has made its topic, so for that moment Follow subscribes again.
// Follow subscribes p to the conversation's events: what the user says,
// every token of its answers, the tools it calls, and the end of each turn,
// from the last it keeps on. The Down with the subscription's Ref means no
// more come: the conversation's process has ended.
//
// A process that has just started has not made its topic yet, and one that
// is in a turn answers nothing until the turn is over. So Follow asks the
// conversation nothing: it subscribes, and again for a moment while there is
// no topic.
func (c Conversation) Follow(ctx context.Context, p *grpcproc.Process[*Event]) (pubsub.Subscription, error) {
if err := c.open(ctx, p); err != nil {
return pubsub.Subscription{}, err
}
topic := ConversationEventsAt(c.node, c.id)
for range 100 {
sub, err := topic.Subscribe(ctx, p)
if !errors.Is(err, grpcproc.ErrNoProc) {
return sub, err
}
select {
case <-ctx.Done():
return pubsub.Subscription{}, ctx.Err()
case <-time.After(10 * time.Millisecond):
}
}
return pubsub.Subscription{}, grpcproc.ErrNoProc
}The HTTP front
The web front is not a process. To say something, a handler calls the conversation through the node, as any code outside a process does: the node is the sender it passes to Say. A failure becomes a 503, and what went wrong between the nodes goes to the log, not to the client.
// say is POST /conversations/{id}: the body is what the user says. It
// answers once the turn has begun; the answer itself goes to whoever follows
// the conversation.
func (f *front) say(w http.ResponseWriter, r *http.Request) {
c, ok := f.conversation(w, r)
if !ok {
return
}
text, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 16<<10))
if err != nil || len(text) == 0 || !utf8.Valid(text) {
http.Error(w, "say something, as UTF-8, in at most 16 KiB", http.StatusBadRequest)
return
}
said, err := c.Say(r.Context(), f.node, string(text))
if err != nil {
// What went wrong between the nodes is for the log, not the client.
f.log.Error("say failed", "conversation", r.PathValue("id"), "err", err)
http.Error(w, "the assistant cannot be reached right now", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_ = json.MarshalWrite(w, map[string]uint64{"turn": said.Turn})
}To follow a conversation, a handler does need a process, since a topic's subscriber is one. It spawns a follower for as long as the browser listens: the follower subscribes and hands each event to the handler's goroutine, which writes it as a server-sent event. When the browser goes away the handler tells the follower to exit, and the topic forgets a subscriber that has. When the conversation ends, the follower receives the topic's Down and the stream closes; the browser asks again, which opens the conversation again.
// follow is GET /conversations/{id}/events: the conversation's events, as
// server-sent events, from the last the topic keeps on. It ends when the
// browser goes away, or the conversation's process does: the browser then
// asks again, which opens the conversation again.
func (f *front) follow(w http.ResponseWriter, r *http.Request) {
c, ok := f.conversation(w, r)
if !ok {
return
}
// The handler's goroutine writes to the browser, and a process of its
// own takes the events and hands them over: a subscriber is a process.
events := make(chan *conversationsv1.Event)
following := make(chan error, 1)
// Until the browser goes away, or the server shuts down.
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
defer context.AfterFunc(f.closing, cancel)()
follower, err := f.node.Spawn(func(p *grpcproc.Process[*conversationsv1.Event]) error {
defer close(events)
sub, err := c.Follow(ctx, p)
following <- err
if err != nil {
return nil // the handler says so
}
var attempt uint64 // the latest try at an answer it has heard of
for {
m, err := p.Receive()
if err != nil {
return err
}
if m.Down != nil && m.Down.Ref == sub.Ref {
return nil // the topic ended, with its conversation
}
if m.Body == nil {
continue
}
if _, token := m.Body.Kind.(*conversationsv1.Event_Token); token && m.Body.Attempt != 0 && m.Body.Attempt < attempt {
continue // of a try that was given up
}
attempt = max(attempt, m.Body.Attempt)
select {
case events <- m.Body:
case <-p.Context().Done():
}
}
}, grpcproc.WithLabel("follower"))
if err == nil {
defer func() { _ = f.node.Exit(context.Background(), follower.PID(), grpcproc.ReasonNormal) }()
err = <-following
}
if ctx.Err() != nil {
return // nobody is there to tell
}
if err != nil {
f.log.Error("follow failed", "conversation", r.PathValue("id"), "err", err)
http.Error(w, "the assistant cannot be reached right now", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
out := http.NewResponseController(w)
_ = out.Flush() // the browser's stream is open, whenever the first event comes
for {
select {
case <-ctx.Done():
return
case e, open := <-events:
if !open {
return
}
// A browser that stopped reading is let go: the follower's
// mailbox would otherwise keep every event meant for it.
_ = out.SetWriteDeadline(time.Now().Add(10 * time.Second))
_, _ = io.WriteString(w, "data: ")
_ = json.MarshalWrite(w, describe(e))
_, _ = io.WriteString(w, "\n\n")
if out.Flush() != nil {
return
}
}
}
}The server is run by dihttp.Serve: it listens when the program starts, serves once the whole start has succeeded, and drains before anything else stops, so what is said meanwhile still finds its conversation. A browser that follows would keep its request open, and the drain waiting; the server's shutdown ends closing, and every such handler returns.