|
| 1 | +// A very, very basic chat client for `docker agent serve chat`. |
| 2 | +// |
| 3 | +// PR #2510 (`feat: add docker agent serve chat command`) exposes any |
| 4 | +// docker-agent agent through an OpenAI-compatible HTTP server. The whole |
| 5 | +// point of that feature is that any tool already speaking OpenAI's |
| 6 | +// /v1/chat/completions protocol can drive a docker-agent agent without |
| 7 | +// custom integration. This example demonstrates exactly that: it uses the |
| 8 | +// official github.com/openai/openai-go SDK, only repointed at the local |
| 9 | +// chat server, to run an interactive REPL against an agent. |
| 10 | +// |
| 11 | +// Prerequisites: |
| 12 | +// |
| 13 | +// # Start an agent in chat mode (in another terminal): |
| 14 | +// ./bin/docker-agent serve chat ./examples/42.yaml |
| 15 | +// # It listens on http://127.0.0.1:8083 by default. |
| 16 | +// |
| 17 | +// Then run this client: |
| 18 | +// |
| 19 | +// go run ./examples/chat |
| 20 | +// # or, to pin a specific agent in a multi-agent team: |
| 21 | +// go run ./examples/chat -model root |
| 22 | +// # or, to point at a different server: |
| 23 | +// go run ./examples/chat -base http://127.0.0.1:9090/v1 |
| 24 | +// |
| 25 | +// Type a message and press <Enter>. Type "exit" (or send EOF with ^D) to |
| 26 | +// quit. |
| 27 | +package main |
| 28 | + |
| 29 | +import ( |
| 30 | + "bufio" |
| 31 | + "context" |
| 32 | + "errors" |
| 33 | + "flag" |
| 34 | + "fmt" |
| 35 | + "io" |
| 36 | + "log" |
| 37 | + "os" |
| 38 | + "os/signal" |
| 39 | + "strings" |
| 40 | + "syscall" |
| 41 | + |
| 42 | + "github.com/openai/openai-go/v3" |
| 43 | + "github.com/openai/openai-go/v3/option" |
| 44 | +) |
| 45 | + |
| 46 | +func main() { |
| 47 | + baseURL := flag.String("base", "http://127.0.0.1:8083/v1", "Base URL of the docker-agent chat server") |
| 48 | + model := flag.String("model", "", "Agent name to talk to (defaults to the team's default agent)") |
| 49 | + stream := flag.Bool("stream", true, "Stream the agent's response token-by-token") |
| 50 | + flag.Parse() |
| 51 | + |
| 52 | + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) |
| 53 | + err := run(ctx, *baseURL, *model, *stream) |
| 54 | + cancel() |
| 55 | + if err != nil && !errors.Is(err, context.Canceled) { |
| 56 | + log.Fatal(err) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +func run(ctx context.Context, baseURL, model string, stream bool) error { |
| 61 | + // The chat server doesn't validate API keys, but the OpenAI SDK |
| 62 | + // requires *some* string to be passed. |
| 63 | + client := openai.NewClient( |
| 64 | + option.WithBaseURL(baseURL), |
| 65 | + option.WithAPIKey("not-needed"), |
| 66 | + ) |
| 67 | + |
| 68 | + // Ask the server which agents are exposed and pick a default model |
| 69 | + // when the user didn't pin one. This also doubles as a connectivity |
| 70 | + // check. |
| 71 | + if model == "" { |
| 72 | + picked, err := pickDefaultModel(ctx, &client) |
| 73 | + if err != nil { |
| 74 | + return fmt.Errorf("listing models: %w", err) |
| 75 | + } |
| 76 | + model = picked |
| 77 | + } |
| 78 | + fmt.Printf("Connected to %s — chatting with %q. Type \"exit\" to quit.\n", baseURL, model) |
| 79 | + |
| 80 | + // History keeps the conversation going across turns. The chat server |
| 81 | + // is stateless: it builds a fresh session per request from whatever |
| 82 | + // messages the client sends, so it's the client's job to remember. |
| 83 | + var history []openai.ChatCompletionMessageParamUnion |
| 84 | + |
| 85 | + in := bufio.NewScanner(os.Stdin) |
| 86 | + in.Buffer(make([]byte, 0, 64*1024), 1024*1024) |
| 87 | + for { |
| 88 | + fmt.Print("\n> ") |
| 89 | + if !in.Scan() { |
| 90 | + if err := in.Err(); err != nil { |
| 91 | + return err |
| 92 | + } |
| 93 | + fmt.Println() |
| 94 | + return nil // EOF |
| 95 | + } |
| 96 | + userInput := strings.TrimSpace(in.Text()) |
| 97 | + if userInput == "" { |
| 98 | + continue |
| 99 | + } |
| 100 | + if userInput == "exit" || userInput == "quit" { |
| 101 | + return nil |
| 102 | + } |
| 103 | + |
| 104 | + history = append(history, openai.UserMessage(userInput)) |
| 105 | + |
| 106 | + reply, err := chat(ctx, &client, model, history, stream) |
| 107 | + if err != nil { |
| 108 | + return err |
| 109 | + } |
| 110 | + history = append(history, openai.AssistantMessage(reply)) |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +// pickDefaultModel queries /v1/models and returns the first agent name |
| 115 | +// the server advertises. |
| 116 | +func pickDefaultModel(ctx context.Context, client *openai.Client) (string, error) { |
| 117 | + page, err := client.Models.List(ctx) |
| 118 | + if err != nil { |
| 119 | + return "", err |
| 120 | + } |
| 121 | + if len(page.Data) == 0 { |
| 122 | + return "", errors.New("server exposes no models") |
| 123 | + } |
| 124 | + return page.Data[0].ID, nil |
| 125 | +} |
| 126 | + |
| 127 | +// chat sends the conversation to the server, prints the assistant's reply |
| 128 | +// to stdout (streaming if requested) and returns the final assembled |
| 129 | +// content so the caller can append it to the history. |
| 130 | +func chat( |
| 131 | + ctx context.Context, |
| 132 | + client *openai.Client, |
| 133 | + model string, |
| 134 | + history []openai.ChatCompletionMessageParamUnion, |
| 135 | + stream bool, |
| 136 | +) (string, error) { |
| 137 | + params := openai.ChatCompletionNewParams{ |
| 138 | + Model: model, |
| 139 | + Messages: history, |
| 140 | + } |
| 141 | + |
| 142 | + if !stream { |
| 143 | + resp, err := client.Chat.Completions.New(ctx, params) |
| 144 | + if err != nil { |
| 145 | + return "", err |
| 146 | + } |
| 147 | + if len(resp.Choices) == 0 { |
| 148 | + return "", errors.New("server returned no choices") |
| 149 | + } |
| 150 | + content := resp.Choices[0].Message.Content |
| 151 | + fmt.Println(content) |
| 152 | + return content, nil |
| 153 | + } |
| 154 | + |
| 155 | + s := client.Chat.Completions.NewStreaming(ctx, params) |
| 156 | + var b strings.Builder |
| 157 | + for s.Next() { |
| 158 | + chunk := s.Current() |
| 159 | + if len(chunk.Choices) == 0 { |
| 160 | + continue |
| 161 | + } |
| 162 | + delta := chunk.Choices[0].Delta.Content |
| 163 | + if delta == "" { |
| 164 | + continue |
| 165 | + } |
| 166 | + fmt.Print(delta) |
| 167 | + b.WriteString(delta) |
| 168 | + } |
| 169 | + if err := s.Err(); err != nil && !errors.Is(err, io.EOF) { |
| 170 | + return "", err |
| 171 | + } |
| 172 | + fmt.Println() |
| 173 | + return b.String(), nil |
| 174 | +} |
0 commit comments