> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://developers.meshapi.ai/llms.txt.
> For full documentation content, see https://developers.meshapi.ai/llms-full.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://developers.meshapi.ai/_mcp/server.

# Chat Completions

> Generate chat completions using the Node.js SDK.

# Chat Completions

```ts
import { MeshAPI } from "meshapi-node-sdk";

const client = new MeshAPI({
  baseUrl: "https://api.yourdomain.com",
  token: "rsk_01JXXXXXXXXXXXXXXXXXXXXXXXXX",
});

const response = await client.chat.completions.create({
  model: "openai/gpt-4o-mini",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "What is the capital of France?" },
  ],
  temperature: 0.7,
  max_tokens: 256,
});

console.log(response.choices[0]?.message.content);
// → "The capital of France is Paris."

console.log(`Tokens used: ${response.usage?.total_tokens}`);
```

## Streaming

```ts
const stream = client.chat.completions.create({
  model: "openai/gpt-4o-mini",
  messages: [{ role: "user", content: "Write a haiku about TypeScript." }],
  stream: true,
});

let fullText = "";

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

console.log("\n--- Full response:", fullText);
```

### Streaming with tool calls

```ts
const stream = client.chat.completions.create({
  model: "openai/gpt-4o",
  messages: [{ role: "user", content: "What's the weather in Paris?" }],
  tools: [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get current weather for a city",
        parameters: {
          type: "object",
          properties: {
            city: { type: "string" },
          },
          required: ["city"],
        },
      },
    },
  ],
  tool_choice: "auto",
  stream: true,
});

for await (const chunk of stream) {
  // handle delta content or tool_calls
  console.log(JSON.stringify(chunk.choices[0]?.delta));
}
```

### Cancelling a stream

```ts
const controller = new AbortController();

// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5_000);

const stream = client.chat.completions.create(
  { model: "openai/gpt-4o-mini", messages: [...], stream: true },
  { signal: controller.signal },
);

try {
  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta.content ?? "");
  }
} catch (err) {
  if ((err as Error).name === "AbortError") {
    console.log("Stream cancelled.");
  }
}
```