Skip to content

xAI plugin

The OpenAI-compatible plugin (compat_oai) can be configured to access xAI (Grok) models. This provides access to the grok family of models, including grok-image for image generation.

To use this plugin, import compat_oai and specify it when you initialize Genkit.

import (
"context"
"github.com/firebase/genkit/go/genkit"
"github.com/firebase/genkit/go/plugins/compat_oai"
)
func main() {
ctx := context.Background()
g := genkit.Init(ctx,
genkit.WithPlugins(&compat_oai.OpenAICompatible{
Provider: "xai",
APIKey: "YOUR_XAI_API_KEY",
BaseURL: "https://api.x.ai/v1",
}),
genkit.WithDefaultModel("xai/grok-3"),
)
}

You must provide an API key from xAI. You can get an API key from your xAI account settings.

Configure the plugin to use your API key by doing one of the following:

  • Set the XAI_API_KEY environment variable to your API key.
  • Specify the API key when you initialize the plugin:
import (
"context"
"github.com/openai/openai-go/option"
)
ctx := context.Background()
x := &compat_oai.OpenAICompatible{
Provider: "xai",
BaseURL: "https://api.x.ai/v1",
Opts: []option.RequestOption{
option.WithAPIKey("your-api-key"),
},
}
g := genkit.Init(ctx,
genkit.WithPlugins(x),
genkit.WithDefaultModel("xai/grok-3"),
)

As always, avoid embedding API keys directly in your code.

package main
import (
"context"
"fmt"
"log"
"os"
"github.com/firebase/genkit/go/ai"
"github.com/firebase/genkit/go/genkit"
"github.com/firebase/genkit/go/plugins/compat_oai"
"github.com/openai/openai-go/option"
)
func main() {
apiKey := os.Getenv("XAI_API_KEY")
if apiKey == "" {
log.Fatal("XAI_API_KEY not provided")
}
ctx := context.Background()
x := &compat_oai.OpenAICompatible{
Provider: "xai",
BaseURL: "https://api.x.ai/v1",
Opts: []option.RequestOption{
option.WithAPIKey(apiKey),
},
}
g := genkit.Init(ctx,
genkit.WithPlugins(x),
genkit.WithDefaultModel("xai/grok-3"),
)
resp, err := genkit.Generate(ctx, g, ai.WithPrompt("Tell me a fact about Firebase Genkit"))
if err != nil {
log.Fatalf("failed to generate response: %v", err)
}
fmt.Print(resp.Text())
}