grok is a Go client for the xAI (Grok) API. It implements the
github.com/goloop/ai interface, so it looks and works like every other goloop
AI provider, and exposes the native chat-completions endpoint with its full
options on top.
- Chat completions:
Generatefor a single response,Streamfor token-by-token output throughiter.Seq2. - Tool use (function calling), multimodal image input and system prompts.
- Native
ChatCompletionandChatCompletionStreamwith the full option set (response_format, seed, n, ...). - Image generation and model listing.
- Retries on 429 and 5xx with backoff; normalized, typed API errors.
- Depends only on
github.com/goloop/aiand the standard library. - Structured output:
ai.Formatmaps onto the provider'sresponse_format(JSON mode or a JSON Schema); read the reply withresp.JSON(&v). - Hosted capabilities:
ai.Request.Hostedis refused withai.ErrNoHosted, because this provider's search is not reachable from the chat endpoint.
go get github.com/goloop/grokpackage main
import (
"context"
"fmt"
"os"
"github.com/goloop/ai"
"github.com/goloop/grok"
)
func main() {
c := grok.New(os.Getenv("XAI_API_KEY"))
resp, err := c.Generate(context.Background(), &ai.Request{
Model: grok.ModelGrok4,
Messages: []ai.Message{ai.UserText("Say hello in one word.")},
})
if err != nil {
panic(err)
}
fmt.Println(resp.Text())
}for chunk, err := range c.Stream(ctx, req) {
if err != nil {
break
}
fmt.Print(chunk.Text)
if chunk.Done && chunk.Usage != nil {
fmt.Printf("\n[%d in / %d out]\n",
chunk.Usage.InputTokens, chunk.Usage.OutputTokens)
}
}Tools, images and system prompts use the same shared ai types as every other
provider (see the reference). For provider-only options such as
structured output, build a native ChatRequest:
resp, _ := c.ChatCompletion(ctx, &grok.ChatRequest{
Model: grok.ModelGrok4,
Messages: []grok.ChatMessage{{Role: "user", Content: "List two colors as JSON."}},
ResponseFormat: json.RawMessage(`{"type":"json_object"}`),
})c.Models(ctx)
c.GetModel(ctx, grok.ModelGrok4)
c.GenerateImage(ctx, &grok.ImageRequest{Model: grok.ModelGrok2Image, Prompt: "a cat"})Full reference: DOC.md (Ukrainian: DOC.UK.md).
See CONTRIBUTING.md.
MIT - see LICENSE.
Reject nil native chat and stream requests before dereferencing them.