LangWatch supports tracing Grok (xAI) API calls using the same otelopenai middleware used for OpenAI. Configure the client to point to the xAI endpoint.
Installation
go get github.com/langwatch/langwatch/sdk-go github.com/openai/openai-go
The LangWatch API key is configured by default via the LANGWATCH_API_KEY environment variable.
Configure the OpenAI client with Grok (xAI)‘s base URL and API key:
package main
import (
"context"
"log"
"os"
otelopenai "github.com/langwatch/langwatch/sdk-go/instrumentation/openai"
"github.com/openai/openai-go"
oaioption "github.com/openai/openai-go/option"
)
func main() {
ctx := context.Background()
client := openai.NewClient(
oaioption.WithAPIKey(os.Getenv("XAI_API_KEY")),
oaioption.WithBaseURL("https://api.grok.com/v1"),
oaioption.WithMiddleware(otelopenai.Middleware("<project_name>",
otelopenai.WithCaptureInput(),
otelopenai.WithCaptureOutput(),
)),
)
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("Chat completion: %s", response.Choices[0].Message.Content)
}
Set GROK_BASE_URL to the Grok (xAI) API endpoint and use your xAI API key.