> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs-staging.joytokens.ai/llms.txt.

# Examples

> Complete, copy-and-run client SDK examples

Every example on this page is **self-contained**: it includes imports, environment setup, and error handling so you can copy a single block and run it. Set these first:

```bash
export JOY_TOKEN_API_KEY="sk-xxx"
export JOY_TOKEN_OPENAI_BASE_URL="https://api-staging.joytokens.ai/openai/v1"
export JOY_TOKEN_ANTHROPIC_BASE_URL="https://api-staging.joytokens.ai/anthropic/v1"
```

All requests use `model: "auto"` �?there is no model environment variable. Base URLs come from [Environments](/user-guide/environments).

## Chat Completions

#### TypeScript

```ts
import { JoyTokenClient } from "@joytoken/client-sdk-ts";

const apiKey = process.env.JOY_TOKEN_API_KEY;
if (!apiKey) throw new Error("JOY_TOKEN_API_KEY is required");

const joytoken = new JoyTokenClient({
  apiKey,
  openAIBaseUrl: process.env.JOY_TOKEN_OPENAI_BASE_URL,
});

const completion = await joytoken.chat.completions.create({
  model: "auto",
  messages: [{ role: "user", content: "Say hello in one sentence." }],
});

console.log(completion.choices[0]?.message?.content);
```

#### Go

```go
package main

import (
    "context"
    "fmt"
    "os"

    joytoken "github.com/jd-opensource/joytoken-sdk-go"
)

func main() {
    ctx := context.Background()
    client := joytoken.NewClient(
        joytoken.WithAPIKey(os.Getenv("JOY_TOKEN_API_KEY")),
        joytoken.WithOpenAIBaseURL(os.Getenv("JOY_TOKEN_OPENAI_BASE_URL")),
    )

    completion, err := client.CreateChatCompletion(ctx, joytoken.ChatCompletionRequest{
        Model:    joytoken.ModelAuto,
        Messages: []joytoken.ChatMessage{{Role: "user", Content: "Say hello in one sentence."}},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(completion.Choices[0].Message.Content)
}
```

## Responses

#### TypeScript

```ts
import { JoyTokenClient } from "@joytoken/client-sdk-ts";

const apiKey = process.env.JOY_TOKEN_API_KEY;
if (!apiKey) throw new Error("JOY_TOKEN_API_KEY is required");

const joytoken = new JoyTokenClient({
  apiKey,
  openAIBaseUrl: process.env.JOY_TOKEN_OPENAI_BASE_URL,
});

const response = await joytoken.responses.create({
  model: "auto",
  input: "Say hello in one sentence.",
});

console.log(response.output?.[0]?.content?.[0]?.text);
```

#### Go

```go
client := joytoken.NewClient(
    joytoken.WithAPIKey(os.Getenv("JOY_TOKEN_API_KEY")),
    joytoken.WithOpenAIBaseURL(os.Getenv("JOY_TOKEN_OPENAI_BASE_URL")),
)

response, err := client.CreateResponse(ctx, joytoken.ResponseRequest{
    Model: joytoken.ModelAuto,
    Input: "Say hello in one sentence.",
})
if err != nil {
    return err
}
fmt.Println(response.OutputText())
```

## Anthropic Messages

#### TypeScript

```ts
import { JoyTokenClient } from "@joytoken/client-sdk-ts";

const apiKey = process.env.JOY_TOKEN_API_KEY;
if (!apiKey) throw new Error("JOY_TOKEN_API_KEY is required");

const joytoken = new JoyTokenClient({
  apiKey,
  anthropicBaseUrl: process.env.JOY_TOKEN_ANTHROPIC_BASE_URL,
});

const message = await joytoken.messages.create({
  model: "auto",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Say hello in one sentence." }],
});

console.log(message.content[0]?.text);
```

#### Go

```go
client := joytoken.NewClient(
    joytoken.WithAPIKey(os.Getenv("JOY_TOKEN_API_KEY")),
    joytoken.WithAnthropicBaseURL(os.Getenv("JOY_TOKEN_ANTHROPIC_BASE_URL")),
)

message, err := client.CreateMessage(ctx, joytoken.MessageRequest{
    Model:     "auto",
    MaxTokens: 1024,
    Messages:  []joytoken.MessageParam{{Role: "user", Content: "Say hello in one sentence."}},
})
if err != nil {
    return err
}
fmt.Println(message.Content[0].Text)
```

## Streaming

Streaming works for Chat Completions, Responses, and Anthropic Messages. The examples below stream Chat Completions.

#### TypeScript

```ts
for await (const chunk of joytoken.chat.completions.stream({
  model: "auto",
  messages: [{ role: "user", content: "Count from 1 to 5." }],
})) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
```

#### Go

```go
stream, err := client.StreamChatCompletion(ctx, joytoken.ChatCompletionRequest{
    Model:    joytoken.ModelAuto,
    Messages: []joytoken.ChatMessage{{Role: "user", Content: "Count from 1 to 5."}},
})
if err != nil {
    return err
}
defer stream.Close()

for {
    chunk, err := stream.Recv()
    if errors.Is(err, io.EOF) {
        break
    }
    if err != nil {
        return err
    }
    fmt.Print(chunk.Choices[0].Delta["content"])
}
```

## Orchestration

A `model: "auto"` request may be routed into **orchestration (multi-task planning)** mode. The gateway splits the request into subtasks, runs them, and aggregates the result. The SDK returns the raw gateway shape, so you branch on it:

* `choices[0].message.content` is a **JSON-encoded array** of per-task outputs (`{ "title", "content" }`), not a plain string �?parse it before rendering. The top-level `plan` field confirms orchestration mode.
* `metadata` is an **array** with one entry per task, including the reserved `__planner__` (`task_seq: 0`) and `__final__` (`task_seq: 4`) entries. Sum `billing.credits_used` across entries for the total cost.
* When streaming, a planning event arrives first (a chunk whose `orchestration.phase` is `planning`, carrying the ordered `plan`), followed by the `__planner__` metadata event. Then each task's full content arrives as a chunk that carries an `orchestration` field (`task_id`, `task_seq`, `task_status`, `title`), each followed by one standalone metadata event (a single object, not an array), before `[DONE]`.

See [Routing](/user-guide/routing#orchestration-multi-task-planning) for the full field reference.

#### TypeScript

```ts
type TaskOutput = { title: string; content: string };

const completion = await joytoken.chat.completions.create({
  model: "auto",
  messages: [{ role: "user", content: "Plan a one-day indoor trip in Shenzhen." }],
});

const raw = completion.choices[0]?.message?.content ?? "[]";
const metadata = (completion as any).metadata ?? [];

// Orchestration mode: content is a JSON array of task outputs.
if ((completion as any).plan && Array.isArray((completion as any).plan)) {
  const tasks: TaskOutput[] = JSON.parse(raw);
  for (const task of tasks) {
    console.log(`## ${task.title}\n${task.content}\n`);
  }

  const totalCredits = metadata.reduce(
    (sum: number, m: any) => sum + (m.billing?.credits_used ?? 0),
    0,
  );
  console.log(`Total credits: ${totalCredits}`);
} else {
  console.log(raw); // plain single-model response
}
```

#### Go

```go
type TaskOutput struct {
    Title   string `json:"title"`
    Content string `json:"content"`
}

resp, err := client.CreateChatCompletion(ctx, joytoken.ChatCompletionRequest{
    Model:    joytoken.ModelAuto,
    Messages: []joytoken.ChatMessage{{Role: "user", Content: "Plan a one-day indoor trip in Shenzhen."}},
})
if err != nil {
    return err
}

// Orchestration mode: Plan is non-empty and Content is a JSON array.
if len(resp.Plan) > 0 {
    var tasks []TaskOutput
    if err := json.Unmarshal([]byte(resp.Choices[0].Message.Content), &tasks); err != nil {
        return err
    }
    for _, task := range tasks {
        fmt.Printf("## %s\n%s\n\n", task.Title, task.Content)
    }

    var totalCredits float64
    for _, m := range resp.Metadata {
        totalCredits += m.Billing.CreditsUsed
    }
    fmt.Printf("Total credits: %v\n", totalCredits)
} else {
    fmt.Println(resp.Choices[0].Message.Content) // plain single-model response
}
```

## Model list

#### TypeScript

```ts
const models = await joytoken.models.list({ locale: "en" });

for (const model of models.data.models) {
  console.log(model.modelId);
}
```

Use `{ locale: "zh" }` for Chinese descriptions; omitting `locale` defaults to English. Catalog entries live in `models.data.models`.

#### Go

```go
models, err := client.ListModelsWithOptions(ctx, joytoken.ListModelsOptions{
    Locale: joytoken.ModelLocaleEN,
})
if err != nil {
    return err
}
for _, model := range models.Data.Models {
    fmt.Println(model.ModelID)
}
```

Use `joytoken.ModelLocaleZH` for Chinese descriptions. `ListModels(ctx)` leaves `locale` unset (API defaults to English). Catalog entries live in `models.Data.Models`.

## Error handling

#### TypeScript

```ts
import { JoyTokenAPIError, JoyTokenClient } from "@joytoken/client-sdk-ts";

const apiKey = process.env.JOY_TOKEN_API_KEY;
if (!apiKey) throw new Error("JOY_TOKEN_API_KEY is required");

const joytoken = new JoyTokenClient({ apiKey });

try {
  await joytoken.chat.completions.create({
    model: "auto",
    messages: [{ role: "user", content: "Hello" }],
  });
} catch (error) {
  if (error instanceof JoyTokenAPIError) {
    console.error(error.status, error.requestId, error.body);
  }
  throw error;
}
```

#### Go

```go
_, err := client.ListModels(ctx)
if err != nil {
    var apiErr *joytoken.APIError
    if errors.As(err, &apiErr) {
        fmt.Println(apiErr.StatusCode, apiErr.RequestID, apiErr.Body)
    }
    return err
}
```

## Run the example project

#### TypeScript

```bash
git clone https://github.com/jd-opensource/joytoken-sdk-ts.git
cd joytoken-sdk-ts
pnpm install

export JOY_TOKEN_API_KEY="sk-xxx"

cd example
pnpm live
```

#### Go

```bash
git clone https://github.com/jd-opensource/joytoken-sdk-go.git
cd joytoken-sdk-go/example
export JOY_TOKEN_API_KEY="sk-xxx"
go run ./live
```

The live example and Client SDK requests always use `model: "auto"`; there is no model environment variable.