Tutorials

Access Grok Using OpenAI-Compatible API

On this page

In this tutorial, you'll learn how to access Grok models using the OpenAI SDK through Puter's OpenAI-compatible endpoint. No xAI API key needed, just your Puter auth token.

Prerequisites

Puter copy auth token
  • Node.js installed on your machine

Setup

Install the OpenAI SDK:

npm install openai

Then configure the client with Puter's base URL and your auth token:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.puter.com/puterai/openai/v1/",
  apiKey: "YOUR_PUTER_AUTH_TOKEN",
});

Replace YOUR_PUTER_AUTH_TOKEN with the auth token you copied from your Puter dashboard. That's all you need. No xAI API key required.

Basic Chat Completion

Here's a simple chat completion using Grok 4.1 Fast:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.puter.com/puterai/openai/v1/",
  apiKey: "YOUR_PUTER_AUTH_TOKEN",
});

const response = await client.chat.completions.create({
  model: "grok-4-1-fast",
  messages: [
    { role: "user", content: "What is the capital of France?" },
  ],
});

console.log(response.choices[0].message.content);

Sample output:

The capital of France is Paris.

The code is identical to what you'd write for OpenAI directly. The only difference is the base URL and the model string.

Streaming

For longer responses, enable streaming to get results in real-time:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.puter.com/puterai/openai/v1/",
  apiKey: "YOUR_PUTER_AUTH_TOKEN",
});

const stream = await client.chat.completions.create({
  model: "grok-4-1-fast",
  messages: [
    { role: "user", content: "Write a short story about a robot learning to paint." },
  ],
  stream: true,
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) {
    process.stdout.write(content);
  }
}

Set stream: true and iterate over the chunks as they arrive. Each chunk contains a piece of the response that you can display immediately.

Conclusion

That's it. You now have access to Grok through the OpenAI SDK via Puter, no xAI API key needed. Swap the model string to use any Grok model, or any of the hundreds of other AI models available through Puter.

Free, Serverless AI and Cloud

Start creating powerful web applications with Puter.js in seconds!

Get Started Now

Read the Docs Try the Playground