Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

main.go

77 lines1.9 KB

1package main
2​
3import (
4 "encoding/json"
5 "io"
6 "log"
7 "net/http"
8)
9​
10func main() {
11 mux := http.NewServeMux()
12 mux.HandleFunc("/", handleChat)
13 mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
14 w.WriteHeader(http.StatusOK)
15 _, _ = w.Write([]byte("ok"))
16 })
17​
18 log.Printf("AG-UI Go server listening on http://127.0.0.1%s", listenAddr)
19 if err := http.ListenAndServe(listenAddr, mux); err != nil {
20 log.Fatal(err)
21 }
23​
24func handleChat(w http.ResponseWriter, r *http.Request) {
25 if r.Method == http.MethodOptions {
26 w.Header().Set("Access-Control-Allow-Origin", "*")
27 w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
28 w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
29 w.WriteHeader(http.StatusNoContent)
30 return
31 }
32​
33 if r.Method != http.MethodPost {
34 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
35 return
36 }
37​
38 body, err := io.ReadAll(r.Body)
39 if err != nil {
40 http.Error(w, "failed to read body", http.StatusBadRequest)
41 return
42 }
43 defer r.Body.Close()
44​
45 var input runAgentInput
46 if err := json.Unmarshal(body, &input); err != nil {
47 http.Error(w, "invalid JSON body", http.StatusBadRequest)
48 return
49 }
50​
51 if input.ThreadID == "" || input.RunID == "" {
52 http.Error(w, "threadId and runId are required", http.StatusBadRequest)
53 return
54 }
55​
56 stream, ok := beginSSE(w)
57 if !ok {
58 http.Error(w, "streaming unsupported", http.StatusInternalServerError)
59 return
60 }
61 stream.initRun(input.ThreadID, input.RunID)
62​
63 config := providerFromInput(input)
64 system, messages := toChatMessages(input.Messages)
65 if len(messages) == 0 {
66 _ = stream.finishError("no user or assistant messages to send")
67 return
68 }
69​
70 err = stream.streamText(func(emit func(string) error) error {
71 return streamCompletion(r.Context(), config, system, messages, emit)
72 })
73 if err != nil {
74 log.Printf("[go] chat error: %v", err)
75 _ = stream.finishError(err.Error())
76 }