Go
Requer Go 1.18 ou superior; usa somente a biblioteca padrão. Configure as três variáveis dos primeiros passos.
// Go: HTTP direto com biblioteca padrão. Execute: go run examples/chat.gopackage main
import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "strings" "time")
func required(name string) string { v := os.Getenv(name) if v == "" { fmt.Fprintln(os.Stderr, "Configure", name) os.Exit(1) } return v}
func main() { baseURL := strings.TrimRight(required("NEXVRA_BASE_URL"), "/") key := required("NEXVRA_API_KEY") model := required("NEXVRA_MODEL") body, err := json.Marshal(map[string]any{ "model": model, "messages": []map[string]string{{"role": "user", "content": "Olá! Responda em uma frase."}}, "max_tokens": 128, }) if err != nil { panic(err) } req, err := http.NewRequest(http.MethodPost, baseURL+"/chat/completions", bytes.NewReader(body)) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer "+key) req.Header.Set("Content-Type", "application/json") client := &http.Client{Timeout: 60 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} res, err := client.Do(req) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer res.Body.Close() if res.StatusCode != http.StatusOK { fmt.Fprintf(os.Stderr, "HTTP %d; request-id=%s\n", res.StatusCode, res.Header.Get("x-nexvra-request-id")) _, _ = io.Copy(os.Stderr, io.LimitReader(res.Body, 1<<20)) os.Exit(1) } var result struct { Choices []struct { Message struct { Content string `json:"content"` } `json:"message"` } `json:"choices"` } if err := json.NewDecoder(res.Body).Decode(&result); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if len(result.Choices) == 0 { fmt.Fprintln(os.Stderr, "Resposta sem choices") os.Exit(1) } fmt.Println(result.Choices[0].Message.Content)}Execute com go run chat.go. Em uma aplicação, reutilize seu http.Client entre
chamadas e propague o contexto da requisição para cancelamento.
Não repita automaticamente um POST após uma falha de transporte.