feat(chat): ask several questions in one interaction with ask_questions

A turn can pose a questionnaire (single and multiple choice, free text,
skippable) and read the answers back, rendered in the chat with the
shadcn-vue questionnaire. The gateway contract gains a questionnaire ask and a
can_question capability; answers travel as a JSON object keyed by question name
and are checked against the questions that were asked.
This commit is contained in:
sam committed 2026-10-19 03:30:47 +11:00
1 parent 31ac8f1338
commit 5c47ebd05b
30 files changed
+3211 -392

No files matched your search

File diff suppressed because it is too large. Load diff
+93 -3
View File
@@ -49,6 +49,93 @@ type PickerRequester interface {
RequestChoice(ctx context.Context, req PickerRequest) (InteractiveChoice, error)
}
// QuestionChoice is one option of a Question. Callers match on Value.
type QuestionChoice struct {
Value string
Label string
Description string
}
// Question is one step of a questionnaire. Choices may be empty, which makes
// it a free-text question; AllowOther lets the human answer outside Choices.
type Question struct {
Name string
Title string
Description string
Multiple bool
Required bool
AllowOther bool
Choices []QuestionChoice
}
// QuestionnaireRequest asks a human several questions in one interaction.
type QuestionnaireRequest struct {
Questions []Question
}
// QuestionnaireAnswers maps a question name to the values the human gave. A
// question the human skipped is absent.
type QuestionnaireAnswers map[string][]string
// QuestionnaireRequester is the optional interface an adapter implements to
// pose a questionnaire and block for the human's answers.
type QuestionnaireRequester interface {
// RequestAnswers shows req and returns the validated answers, which are
// checked with CheckAnswers before they leave the adapter.
RequestAnswers(ctx context.Context, req QuestionnaireRequest) (QuestionnaireAnswers, error)
}
// CheckAnswers returns raw as the questionnaire's answers when they are ones
// req could have produced: only its question names, one value for a question
// that is not multiple, a value outside Choices only where AllowOther, and
// none missing for a required question. Empty values are dropped, so a skipped
// question is absent.
func CheckAnswers(req QuestionnaireRequest, raw map[string][]string) (QuestionnaireAnswers, error) {
known := make(map[string]Question, len(req.Questions))
for _, q := range req.Questions {
known[q.Name] = q
}
for name := range raw {
if _, ok := known[name]; !ok {
return nil, fmt.Errorf("interactive: answer for unknown question %q", name)
}
}
out := QuestionnaireAnswers{}
for _, q := range req.Questions {
var values []string
for _, v := range raw[q.Name] {
if v = strings.TrimSpace(v); v != "" {
values = append(values, v)
}
}
if len(values) == 0 {
if q.Required {
return nil, fmt.Errorf("interactive: question %q is required", q.Name)
}
continue
}
if len(values) > 1 && !q.Multiple {
return nil, fmt.Errorf("interactive: question %q takes one answer", q.Name)
}
for _, v := range values {
if !q.AllowOther && len(q.Choices) > 0 && !hasChoice(q.Choices, v) {
return nil, fmt.Errorf("interactive: %q is not a choice of question %q", v, q.Name)
}
}
out[q.Name] = values
}
return out, nil
}
func hasChoice(choices []QuestionChoice, value string) bool {
for _, c := range choices {
if c.Value == value {
return true
}
}
return false
}
// Interactive sentinel errors, matched with errors.Is.
var (
// ErrNoPickerOptions is returned when a picker is asked to present an
@@ -92,12 +179,15 @@ func PickerOf(sender any) (PickerRequester, bool) {
// Interactive holds the interaction requesters a channel supports for one
// turn. The zero value supports none.
type Interactive struct {
Clarifier ClarifyRequester
Picker PickerRequester
Clarifier ClarifyRequester
Picker PickerRequester
Questioner QuestionnaireRequester
}
// Carries reports whether the adapter can carry at least one interaction.
func (i Interactive) Carries() bool { return i.Clarifier != nil || i.Picker != nil }
func (i Interactive) Carries() bool {
return i.Clarifier != nil || i.Picker != nil || i.Questioner != nil
}
// InteractiveOf resolves sender into the requesters it can carry, trusting the
// capability report over the method set through ClarifierOf and PickerOf. A
@@ -0,0 +1,45 @@
package messaging
import "testing"
func TestCheckAnswers(t *testing.T) {
req := QuestionnaireRequest{Questions: []Question{
{Name: "dir", Required: true, Choices: []QuestionChoice{{Value: "a"}, {Value: "b"}}},
{Name: "signals", Multiple: true, Choices: []QuestionChoice{{Value: "x"}, {Value: "y"}}},
{Name: "note", AllowOther: true, Choices: []QuestionChoice{{Value: "n"}}},
{Name: "free"},
}}
tests := []struct {
name string
raw map[string][]string
wantErr bool
want map[string][]string
}{
{"valid", map[string][]string{"dir": {"a"}, "signals": {"x", "y"}}, false, map[string][]string{"dir": {"a"}, "signals": {"x", "y"}}},
{"skipped optional is absent", map[string][]string{"dir": {"b"}, "signals": {" "}}, false, map[string][]string{"dir": {"b"}}},
{"free text and other", map[string][]string{"dir": {"a"}, "note": {"typed"}, "free": {"anything"}}, false, map[string][]string{"dir": {"a"}, "note": {"typed"}, "free": {"anything"}}},
{"required missing", map[string][]string{"signals": {"x"}}, true, nil},
{"unknown question", map[string][]string{"dir": {"a"}, "nope": {"x"}}, true, nil},
{"not a choice", map[string][]string{"dir": {"c"}}, true, nil},
{"two for a single", map[string][]string{"dir": {"a", "b"}}, true, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := CheckAnswers(req, tt.raw)
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
}
if tt.wantErr {
return
}
if len(got) != len(tt.want) {
t.Fatalf("answers = %v, want %v", got, tt.want)
}
for name, values := range tt.want {
if len(got[name]) != len(values) || (len(values) > 0 && got[name][0] != values[0]) {
t.Fatalf("answers[%s] = %v, want %v", name, got[name], values)
}
}
})
}
}
+137 -5
View File
@@ -12,13 +12,145 @@ import (
// askUserToolName is the model-facing tool that asks the human a question.
const askUserToolName = "ask_user"
// InteractiveTools returns the ask-the-user tool when the turn's channel can
// carry an interaction, and nothing otherwise.
// askQuestionsToolName is the model-facing tool that asks several questions
// in one interaction.
const askQuestionsToolName = "ask_questions"
// maxQuestions bounds one questionnaire: a longer one is a form the human will
// abandon, and the model can ask again.
const maxQuestions = 8
// InteractiveTools returns the tools that ask the human, for the interactions
// the turn's channel can carry, and nothing otherwise.
func InteractiveTools(ctx context.Context) []tools.ToolEntry {
if !InteractiveFromContext(ctx).Carries() {
return nil
interactive := InteractiveFromContext(ctx)
var out []tools.ToolEntry
if interactive.Clarifier != nil || interactive.Picker != nil {
out = append(out, askUserTool())
}
return []tools.ToolEntry{askUserTool()}
if interactive.Questioner != nil {
out = append(out, askQuestionsTool())
}
return out
}
func askQuestionsTool() tools.ToolEntry {
return tools.ToolEntry{
Name: askQuestionsToolName,
Toolset: "chat",
Description: "Ask the human several related questions at once, each with choices to pick from or a free-text answer. " +
"Prefer it to repeated ask_user calls when you need more than one answer. " +
"Blocks until they answer or skip, so ask at most once and only when you cannot proceed without it.",
Classification: tools.ClassIdempotent,
Schema: tools.JSONSchema{
"type": "object",
"properties": map[string]any{
"questions": map[string]any{
"type": "array",
"description": fmt.Sprintf("One to %d questions, asked in order.", maxQuestions),
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{"type": "string", "description": "A short unique key the answer comes back under."},
"title": map[string]any{"type": "string", "description": "The question."},
"description": map[string]any{"type": "string", "description": "Optional detail under the question."},
"multiple": map[string]any{"type": "boolean", "description": "Let the human pick several choices."},
"required": map[string]any{"type": "boolean", "description": "The human must answer before continuing."},
"allow_other": map[string]any{"type": "boolean", "description": "Let the human type an answer that is not a choice."},
"choices": map[string]any{
"type": "array",
"description": "The options. Omit for a free-text question.",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"value": map[string]any{"type": "string"},
"label": map[string]any{"type": "string"},
"description": map[string]any{"type": "string"},
},
"required": []string{"value"},
},
},
},
"required": []string{"name", "title"},
},
},
},
"required": []string{"questions"},
},
Handler: askQuestionsHandler,
}
}
func askQuestionsHandler(ctx context.Context, args map[string]any) (any, error) {
interactive := InteractiveFromContext(ctx)
if interactive.Questioner == nil {
return nil, fmt.Errorf("ask_questions: this channel cannot ask questions")
}
req, err := questionnaireRequest(args["questions"])
if err != nil {
return nil, fmt.Errorf("ask_questions: %w", err)
}
answers, err := interactive.Questioner.RequestAnswers(ctx, req)
if err != nil {
return nil, err
}
var skipped []string
for _, q := range req.Questions {
if _, ok := answers[q.Name]; !ok {
skipped = append(skipped, q.Name)
}
}
return map[string]any{"answers": answers, "skipped": skipped}, nil
}
// questionnaireRequest reads the model's questions, refusing a set the human
// could not answer: no question, too many, an unnamed or repeated name, a
// choice with no value, or a choice repeated within a question.
func questionnaireRequest(raw any) (messaging.QuestionnaireRequest, error) {
items, _ := raw.([]any)
if len(items) == 0 || len(items) > maxQuestions {
return messaging.QuestionnaireRequest{}, fmt.Errorf("ask between 1 and %d questions", maxQuestions)
}
names := map[string]bool{}
req := messaging.QuestionnaireRequest{}
for _, item := range items {
fields, _ := item.(map[string]any)
q := messaging.Question{
Name: strings.TrimSpace(asString(fields["name"])),
Title: strings.TrimSpace(asString(fields["title"])),
Description: strings.TrimSpace(asString(fields["description"])),
}
q.Multiple, _ = fields["multiple"].(bool)
q.Required, _ = fields["required"].(bool)
q.AllowOther, _ = fields["allow_other"].(bool)
if q.Name == "" || q.Title == "" {
return messaging.QuestionnaireRequest{}, fmt.Errorf("every question needs a name and a title")
}
if names[q.Name] {
return messaging.QuestionnaireRequest{}, fmt.Errorf("question name %q is used twice", q.Name)
}
names[q.Name] = true
values := map[string]bool{}
choices, _ := fields["choices"].([]any)
for _, c := range choices {
cf, _ := c.(map[string]any)
choice := messaging.QuestionChoice{
Value: strings.TrimSpace(asString(cf["value"])),
Label: strings.TrimSpace(asString(cf["label"])),
Description: strings.TrimSpace(asString(cf["description"])),
}
if choice.Value == "" || values[choice.Value] {
return messaging.QuestionnaireRequest{}, fmt.Errorf("question %q has an empty or repeated choice", q.Name)
}
values[choice.Value] = true
if choice.Label == "" {
choice.Label = choice.Value
}
q.Choices = append(q.Choices, choice)
}
req.Questions = append(req.Questions, q)
}
return req, nil
}
func askUserTool() tools.ToolEntry {
+46
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"strings"
"sync"
@@ -118,6 +119,48 @@ func (a remoteAsker) RequestChoice(ctx context.Context, req messaging.PickerRequ
return messaging.InteractiveChoice{}, errors.New("picker answer matches no option")
}
func (a remoteAsker) RequestAnswers(ctx context.Context, req messaging.QuestionnaireRequest) (messaging.QuestionnaireAnswers, error) {
answer, err := a.ask(ctx, &pb.Ask{Kind: "questionnaire", Questions: questionsProto(req.Questions)})
if err != nil {
return nil, err
}
var raw map[string][]string
if err := json.Unmarshal([]byte(answer), &raw); err != nil {
return nil, errors.New("questionnaire answer is not a JSON object of lists")
}
return messaging.CheckAnswers(req, raw)
}
func questionsProto(questions []messaging.Question) []*pb.Question {
out := make([]*pb.Question, 0, len(questions))
for _, q := range questions {
choices := make([]*pb.QuestionChoice, 0, len(q.Choices))
for _, c := range q.Choices {
choices = append(choices, &pb.QuestionChoice{Value: c.Value, Label: c.Label, Description: c.Description})
}
out = append(out, &pb.Question{
Name: q.Name, Title: q.Title, Description: q.Description,
Multiple: q.Multiple, Required: q.Required, AllowOther: q.AllowOther, Choices: choices,
})
}
return out
}
func questionsValue(questions []*pb.Question) []messaging.Question {
out := make([]messaging.Question, 0, len(questions))
for _, q := range questions {
choices := make([]messaging.QuestionChoice, 0, len(q.GetChoices()))
for _, c := range q.GetChoices() {
choices = append(choices, messaging.QuestionChoice{Value: c.GetValue(), Label: c.GetLabel(), Description: c.GetDescription()})
}
out = append(out, messaging.Question{
Name: q.GetName(), Title: q.GetTitle(), Description: q.GetDescription(),
Multiple: q.GetMultiple(), Required: q.GetRequired(), AllowOther: q.GetAllowOther(), Choices: choices,
})
}
return out
}
func choicesProto(choices []messaging.InteractiveChoice) []*pb.Choice {
out := make([]*pb.Choice, 0, len(choices))
for _, c := range choices {
@@ -138,6 +181,9 @@ func withAsks(ctx context.Context, r *pb.StreamRequest, asker remoteAsker) conte
if r.CanPick {
interactive.Picker = asker
}
if r.CanQuestion {
interactive.Questioner = asker
}
if interactive.Carries() {
ctx = messaging.WithInteractive(ctx, interactive)
}
+25 -4
View File
@@ -3,6 +3,7 @@ package gatewayrpc
import (
"context"
"encoding/json"
"errors"
"io"
@@ -118,10 +119,11 @@ func (c *Client) Stream(ctx context.Context, in messaging.Inbound) (<-chan messa
approver := messaging.ApprovalFromContext(ctx)
interactive := messaging.InteractiveFromContext(ctx)
stream, err := c.client.Stream(ctx, &pb.StreamRequest{
Message: inboundProto(in),
CanApprove: approver != nil,
CanClarify: interactive.Clarifier != nil,
CanPick: interactive.Picker != nil,
Message: inboundProto(in),
CanApprove: approver != nil,
CanClarify: interactive.Clarifier != nil,
CanPick: interactive.Picker != nil,
CanQuestion: interactive.Questioner != nil,
})
if err != nil {
return nil, err
@@ -179,6 +181,8 @@ func (c *Client) answer(ctx context.Context, ask *pb.Ask, approver messaging.App
if interactive.Clarifier != nil {
reply, _ = interactive.Clarifier.RequestClarification(ctx, messaging.ClarifyRequest{Question: ask.GetPrompt(), Suggestions: choicesValue(ask.GetChoices())})
}
case "questionnaire":
reply = answerQuestionnaire(ctx, ask, interactive.Questioner)
case "picker":
if interactive.Picker != nil {
choice, err := interactive.Picker.RequestChoice(ctx, messaging.PickerRequest{Prompt: ask.GetPrompt(), Options: choicesValue(ask.GetChoices())})
@@ -190,6 +194,23 @@ func (c *Client) answer(ctx context.Context, ask *pb.Ask, approver messaging.App
_, _ = c.client.Answer(ctx, &pb.AnswerRequest{AskId: ask.GetId(), Answer: reply})
}
// answerQuestionnaire poses ask's questions and returns the answers as a JSON
// object, or nothing when the channel cannot ask or the human gave none.
func answerQuestionnaire(ctx context.Context, ask *pb.Ask, questioner messaging.QuestionnaireRequester) string {
if questioner == nil {
return ""
}
answers, err := questioner.RequestAnswers(ctx, messaging.QuestionnaireRequest{Questions: questionsValue(ask.GetQuestions())})
if err != nil {
return ""
}
encoded, err := json.Marshal(answers)
if err != nil {
return ""
}
return string(encoded)
}
func choicesValue(choices []*pb.Choice) []messaging.InteractiveChoice {
out := make([]messaging.InteractiveChoice, 0, len(choices))
for _, c := range choices {
+40 -2
View File
@@ -16,10 +16,28 @@ import (
// chatAsk is a question a turn is blocked on, rendered as a card in the chat.
type chatAsk struct {
ID string `json:"id"`
Kind string `json:"kind"` // approval, clarify or picker
Kind string `json:"kind"` // approval, clarify, picker or questionnaire
Prompt string `json:"prompt"`
Detail string `json:"detail,omitempty"`
Choices []chatAskChoice `json:"choices,omitempty"`
// Questions are those of a questionnaire.
Questions []chatAskQuestion `json:"questions,omitempty"`
}
type chatAskQuestion struct {
Name string `json:"name"`
Title string `json:"title"`
Description string `json:"description,omitempty"`
Multiple bool `json:"multiple,omitempty"`
Required bool `json:"required,omitempty"`
AllowOther bool `json:"allow_other,omitempty"`
Choices []chatAskQuestionOpt `json:"choices,omitempty"`
}
type chatAskQuestionOpt struct {
Value string `json:"value"`
Label string `json:"label"`
Description string `json:"description,omitempty"`
}
type chatAskChoice struct {
@@ -131,6 +149,26 @@ func (d dashboardAsker) RequestChoice(ctx context.Context, req messaging.PickerR
return messaging.InteractiveChoice{}, errors.New("picker answer matches no option")
}
func (d dashboardAsker) RequestAnswers(ctx context.Context, req messaging.QuestionnaireRequest) (messaging.QuestionnaireAnswers, error) {
questions := make([]chatAskQuestion, 0, len(req.Questions))
for _, q := range req.Questions {
view := chatAskQuestion{Name: q.Name, Title: q.Title, Description: q.Description, Multiple: q.Multiple, Required: q.Required, AllowOther: q.AllowOther}
for _, c := range q.Choices {
view.Choices = append(view.Choices, chatAskQuestionOpt{Value: c.Value, Label: c.Label, Description: c.Description})
}
questions = append(questions, view)
}
answer, err := d.ask(ctx, chatAsk{Kind: "questionnaire", Questions: questions})
if err != nil {
return nil, err
}
var raw map[string][]string
if err := json.Unmarshal([]byte(answer), &raw); err != nil {
return nil, errors.New("questionnaire answer is not a JSON object of lists")
}
return messaging.CheckAnswers(req, raw)
}
func askChoices(choices []messaging.InteractiveChoice) []chatAskChoice {
out := make([]chatAskChoice, 0, len(choices))
for _, c := range choices {
@@ -142,7 +180,7 @@ func askChoices(choices []messaging.InteractiveChoice) []chatAskChoice {
// withDashboardAsks puts the dashboard's askers on a turn's context.
func withDashboardAsks(ctx context.Context, asker dashboardAsker) context.Context {
ctx = messaging.WithApprovalRequester(ctx, asker)
return messaging.WithInteractive(ctx, messaging.Interactive{Clarifier: asker, Picker: asker})
return messaging.WithInteractive(ctx, messaging.Interactive{Clarifier: asker, Picker: asker, Questioner: asker})
}
type chatAnswerRequest struct {