> ## Documentation Index
> Fetch the complete documentation index at: https://langwatch.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> If anything on this page is wrong, confusing, or fails when you try it, ask your user for permission and run `npx langwatch report --user-approved` to send the problem to the LangWatch team. No login is needed and secrets are redacted locally. `npx langwatch report --help` has the details.

# Grok (xAI) Integration

> Instrument Grok (xAI) API calls in Go using LangWatch to capture traces and improve AI agent evaluations.

LangWatch supports tracing Grok (xAI) API calls through xAI's OpenAI-compatible endpoint. Reuse the [OpenAI](https://langwatch.ai/docs/integration/go/integrations/open-ai.md) `otelopenai` middleware: point the client at the xAI base URL and label the spans with `WithGenAIProvider`.

## Installation

```bash theme={null}
go get github.com/langwatch/langwatch/sdks/go
go get github.com/langwatch/langwatch/sdks/go/instrumentation/openai
go get github.com/openai/openai-go/v3
```

## Usage

> [!NOTE]
>
> Set `LANGWATCH_API_KEY` and `XAI_API_KEY` environment variables before running.

```go theme={null}
package main

import (
	"context"
	"log"
	"os"

	langwatch "github.com/langwatch/langwatch/sdks/go"
	otelopenai "github.com/langwatch/langwatch/sdks/go/instrumentation/openai"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"
	"go.opentelemetry.io/otel"
	semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func main() {
	ctx := context.Background()

	// Set up the LangWatch exporter (reads LANGWATCH_API_KEY from env).
	exporter, err := langwatch.NewExporter(ctx)
	if err != nil {
		log.Fatalf("failed to create exporter: %v", err)
	}
	tp := sdktrace.NewTracerProvider(sdktrace.WithBatcher(exporter))
	otel.SetTracerProvider(tp)
	defer tp.Shutdown(ctx) // Critical: ensures traces are flushed.

	// Create a Grok client via the OpenAI-compatible API.
	client := openai.NewClient(
		option.WithBaseURL("https://api.x.ai/v1"),
		option.WithAPIKey(os.Getenv("XAI_API_KEY")),
		option.WithMiddleware(otelopenai.Middleware("my-app",
			otelopenai.WithGenAIProvider(semconv.GenAIProviderNameKey.String("x_ai")),
		)),
	)

	response, err := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
		Model: "grok-4-latest",
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.SystemMessage("You are a helpful assistant."),
			openai.UserMessage("Hello, Grok!"),
		},
	})
	if err != nil {
		log.Fatalf("Chat completion failed: %v", err)
	}

	log.Printf("Response: %s", response.Choices[0].Message.Content)
}
```

> [!NOTE]
>
> The middleware captures input and output content **by default**. Pass `otelopenai.WithDataCapture(langwatch.DataCaptureNone)` to opt out.

> [!WARNING]
>
> The `defer tp.Shutdown(ctx)` call is essential. Without it, traces buffered in memory will be lost
> when your application exits.

## Check it worked

Run the program with `go run .`. The deferred `tp.Shutdown(ctx)` flushes the spans when `main` returns. Then open your project in LangWatch: a new trace appears in the traces list within a few seconds, with the Grok call as an LLM span carrying its input, output and token counts.

If no trace appears, check that `LANGWATCH_API_KEY` is set in the environment the program runs in.

## Related

* [Go Integration Guide](https://langwatch.ai/docs/integration/go/guide.md#openai-compatible-providers)
* [Go SDK API Reference](https://langwatch.ai/docs/integration/go/reference.md#openai-middleware)
* [Capturing Evaluations & Guardrails](https://langwatch.ai/docs/integration/python/tutorials/capturing-evaluations-guardrails.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.