> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reygrid.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Usage

> Reference for every ReyGrid TypeScript SDK client method: chat, conversations, messages, pagination, and tool calls.

All methods return Promises and are fully typed. Types such as `ChatResponse` and `MessagesResponse` are exported from `reygrid`.

```typescript theme={"system"}
import { ReyGrid } from "reygrid";

const client = new ReyGrid({ apiKey: process.env.REYGRID_API_KEY });
```

## Health and usage

<AccordionGroup>
  <Accordion title="ping(): Promise<PingResponse>" defaultOpen>
    `GET /ping`. No API key required.

    ```typescript theme={"system"}
    const { status, service, version, metadata } = await client.ping();
    ```

    `PingResponse`: `success`, `status` (`"UP" | "DOWN"`), `service`, `version`, `metadata?` (`uptime?`, `timestamp?`).
  </Accordion>

  <Accordion title="validate(): Promise<ValidateResponse>">
    `GET /validate`.

    ```typescript theme={"system"}
    const v = await client.validate();
    console.log(v.valid, v.usage);
    ```
  </Accordion>

  <Accordion title="getUsage(): Promise<Usage>">
    Shortcut for `(await validate()).usage`.

    ```typescript theme={"system"}
    const { total, quotaLimit } = await client.getUsage();
    ```
  </Accordion>
</AccordionGroup>

## Chat

### `chat(agentId, message, opts?): Promise<ChatResponse>`

Sends a message and returns the full reply (`POST /agents/{agentId}/chat`).

<ParamField path="agentId" type="string" required>The agent ID.</ParamField>
<ParamField path="message" type="string" required>The user message.</ParamField>
<ParamField path="opts.conversationId" type="string">Existing conversation. Ignored when `userId` is set.</ParamField>
<ParamField path="opts.userId" type="string">Stable user identifier for a persistent conversation.</ParamField>
<ParamField path="opts.tools" type="Tool[]">Tool definitions. See [Tool calling](/rest-api/tool-calling).</ParamField>
<ParamField path="opts.results" type="ToolResult[] | null">Results for tool calls: `{ toolCallId, output }`.</ParamField>

```typescript theme={"system"}
const res = await client.chat("{AgentId}", "Check my current subscription", {
  userId: "user-42",
  tools: [
    {
      type: "function",
      function: {
        name: "check_subscription",
        instructions: "Opens the customer's current plan, renewal date, and payment status.",
        parameters: {
          type: "object",
          properties: { userId: { type: "string", description: "The customer user id" } },
          required: ["userId"],
        },
      },
    },
  ],
});

console.log(res.output.reply.content);
console.log(res.output.finish_reason, res.messageId, res.conversationId);
console.log(res.usage.credits);
```

**Returns** `ChatResponse`: `success`, `messageId`, `output` (`reply.id`, `reply.content`, `finish_reason`), `usage.credits`, and optional `conversationId`, `userId`.

<Note>
  For streaming use [`streamChat()`](/integrations/typescript/streaming) rather than passing `stream: true` to `chat()`.
</Note>

### Sending tool results

```typescript theme={"system"}
const res = await client.chat("{AgentId}", "What is the status of my account?", {
  userId: "user-42",
  tools: [checkSubscriptionTool],
  results: [
    {
      toolCallId: "call_xyz",
      output: JSON.stringify({ plan: "pro", status: "active" }),
    },
  ],
});
```

## Conversations

### `listConversations(agentId, { page?, size? }): Promise<ConversationsResponse>`

```typescript theme={"system"}
const res = await client.listConversations("{AgentId}", { page: 1, size: 20 });
for (const c of res.conversations) {
  console.log(c.conversationId, c.userId, c.messagesCount, c.createdAt);
}
console.log(res.pagination.hasNextPage, res.pagination.totalConversations);
```

### `deleteConversation(agentId, conversationRef): Promise<DeleteMessagesResponse>`

`conversationRef` is a conversation ID or a persistent user ID.

```typescript theme={"system"}
const res = await client.deleteConversation("{AgentId}", "user-42");
console.log(res.deletedMessages.count);
```

## Messages

### `listMessages(agentId, conversationRef, { page?, size? }): Promise<MessagesResponse>`

```typescript theme={"system"}
const res = await client.listMessages("{AgentId}", "user-42", { page: 1, size: 50 });
for (const m of res.messages) {
  console.log(m.role, m.content);
  for (const call of m.tool_calls ?? []) {
    console.log("  tool call:", call.id, call.function.name, call.status);
  }
}
```

### `deleteMessage(agentId, conversationRef, messageId, cascade = false): Promise<DeleteMessagesResponse>`

With `cascade = true` the message immediately following is deleted too.

```typescript theme={"system"}
const res = await client.deleteMessage("{AgentId}", "user-42", "MESSAGE_ID", true);
console.log(res.deletedMessages.count);
```

## Tool calls

### `cancelToolCall(agentId, conversationRef, toolCallId): Promise<CancelToolResponse>`

```typescript theme={"system"}
const { canceled } = await client.cancelToolCall("{AgentId}", "user-42", "call_xyz");
```

A `404` throws `ReyGridNotFoundError`; a `409` (cannot be canceled) throws `ReyGridConflictError`.

## Agents

### `listAgents(): Promise<AgentsResponse>` · `getAgent(agentId)` · `updateAgent(agentId, update)`

```typescript theme={"system"}
const { agents } = await client.listAgents(); // the agents this key can use
const { agent } = await client.getAgent("{AgentId}");
console.log(agent.sources, agent.storage); // { text, qa, file, website }, { used, limit }

await client.updateAgent("{AgentId}", { instructions: "Answer in a friendly tone." });
```

## Knowledge

```typescript theme={"system"}
import { openAsBlob } from "node:fs";

await client.addTextSource("{AgentId}", { title: "Refund policy", content: "…" });
await client.addQaSource("{AgentId}", { question: "Do you ship abroad?", answer: "…" });
await client.uploadFile("{AgentId}", await openAsBlob("handbook.pdf"), "handbook.pdf");
const { pagesCrawled } = await client.crawlWebsite("{AgentId}", "https://docs.example.com");

const { sources } = await client.listSources("{AgentId}", { type: "text", search: "refund" });
await client.deleteSource("{AgentId}", sources[0].id);
```

`uploadFile` accepts a `Blob`, `ArrayBuffer` or `Uint8Array`. Uploads and crawls wait for indexing, so they use a 10-minute timeout by default (`{ timeoutMs }` to change it). See [Knowledge & search](/rest-api/knowledge).

## Search, feedback, models and usage

```typescript theme={"system"}
const { results } = await client.search("{AgentId}", "How do I get a refund?", { limit: 3 });

await client.rateMessage("{AgentId}", "user-42", "msg_abc123", { rating: "up" });

const { models } = await client.listModels();
const report = await client.getUsageReport({ days: 7 }); // balance, totals, daily, agents
```

`getUsageReport()` is the account report from `GET /usage`; `getUsage()` still returns this key's usage from `/validate`.

## Pagination helpers

`paginateConversations(agentId, size = 20)` and `paginateMessages(agentId, conversationRef, size = 20)` return a `Paginator<T>` (page size is clamped to 1–100).

| Method | Description |
| - | - |
| `pages()` | Async generator of `PaginatedResult<T>` (`data`, `pagination`) |
| `next()` | Next page, or `null` when exhausted |
| `all()` | Collect every item into one array |
| `reset()` | Go back to the first page |

```typescript theme={"system"}
for await (const page of client.paginateConversations("{AgentId}", 50).pages()) {
  for (const convo of page.data) {
    console.log(convo.conversationId, convo.messagesCount);
  }
}

const allMessages = await client.paginateMessages("{AgentId}", "user-42").all();
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.