@mastra/client-js 1.7.0 → 1.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/docs/SKILL.md +44 -0
- package/dist/docs/assets/SOURCE_MAP.json +6 -0
- package/dist/docs/references/docs-server-auth-auth0.md +220 -0
- package/dist/docs/references/docs-server-auth-clerk.md +132 -0
- package/dist/docs/references/docs-server-auth-firebase.md +272 -0
- package/dist/docs/references/docs-server-auth-jwt.md +110 -0
- package/dist/docs/references/docs-server-auth-supabase.md +117 -0
- package/dist/docs/references/docs-server-auth-workos.md +186 -0
- package/dist/docs/references/docs-server-mastra-client.md +243 -0
- package/dist/docs/references/reference-ai-sdk-to-ai-sdk-stream.md +231 -0
- package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v4-messages.md +79 -0
- package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v5-messages.md +76 -0
- package/dist/docs/references/reference-client-js-agents.md +437 -0
- package/dist/docs/references/reference-client-js-error-handling.md +16 -0
- package/dist/docs/references/reference-client-js-logs.md +24 -0
- package/dist/docs/references/reference-client-js-mastra-client.md +63 -0
- package/dist/docs/references/reference-client-js-memory.md +221 -0
- package/dist/docs/references/reference-client-js-observability.md +72 -0
- package/dist/docs/references/reference-client-js-telemetry.md +20 -0
- package/dist/docs/references/reference-client-js-tools.md +44 -0
- package/dist/docs/references/reference-client-js-vectors.md +79 -0
- package/dist/docs/references/reference-client-js-workflows.md +199 -0
- package/package.json +7 -7
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
# Mastra Client SDK
|
|
2
|
+
|
|
3
|
+
The Mastra Client SDK provides a simple and type-safe interface for interacting with your [Mastra Server](https://mastra.ai/docs/server/mastra-server) from your client environment.
|
|
4
|
+
|
|
5
|
+
## Prerequisites
|
|
6
|
+
|
|
7
|
+
To ensure smooth local development, make sure you have:
|
|
8
|
+
|
|
9
|
+
- Node.js `v22.13.0` or later
|
|
10
|
+
- TypeScript `v4.7` or higher (if using TypeScript)
|
|
11
|
+
- Your local Mastra server running (typically on port `4111`)
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
The Mastra Client SDK is designed for browser environments and uses the native `fetch` API for making HTTP requests to your Mastra server.
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
To use the Mastra Client SDK, install the required dependencies:
|
|
20
|
+
|
|
21
|
+
**npm**:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @mastra/client-js@latest
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
**pnpm**:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pnpm add @mastra/client-js@latest
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
**Yarn**:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
yarn add @mastra/client-js@latest
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
**Bun**:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
bun add @mastra/client-js@latest
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Initialize the `MastraClient`
|
|
46
|
+
|
|
47
|
+
Once initialized with a `baseUrl`, `MastraClient` exposes a type-safe interface for calling agents, tools, and workflows.
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
import { MastraClient } from '@mastra/client-js'
|
|
51
|
+
|
|
52
|
+
export const mastraClient = new MastraClient({
|
|
53
|
+
baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
|
|
54
|
+
})
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Core APIs
|
|
58
|
+
|
|
59
|
+
The Mastra Client SDK exposes all resources served by the Mastra Server
|
|
60
|
+
|
|
61
|
+
- **[Agents](https://mastra.ai/reference/client-js/agents)**: Generate responses and stream conversations.
|
|
62
|
+
- **[Memory](https://mastra.ai/reference/client-js/memory)**: Manage conversation threads and message history.
|
|
63
|
+
- **[Tools](https://mastra.ai/reference/client-js/tools)**: Executed and managed tools.
|
|
64
|
+
- **[Workflows](https://mastra.ai/reference/client-js/workflows)**: Trigger workflows and track their execution.
|
|
65
|
+
- **[Vectors](https://mastra.ai/reference/client-js/vectors)**: Use vector embeddings for semantic search.
|
|
66
|
+
- **[Logs](https://mastra.ai/reference/client-js/logs)**: View logs and debug system behavior.
|
|
67
|
+
- **[Telemetry](https://mastra.ai/reference/client-js/telemetry)**: Monitor app performance and trace activity.
|
|
68
|
+
|
|
69
|
+
## Generating responses
|
|
70
|
+
|
|
71
|
+
Call `.generate()` with a string prompt:
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
import { mastraClient } from 'lib/mastra-client'
|
|
75
|
+
|
|
76
|
+
const testAgent = async () => {
|
|
77
|
+
try {
|
|
78
|
+
const agent = mastraClient.getAgent('testAgent')
|
|
79
|
+
|
|
80
|
+
const response = await agent.generate('Hello')
|
|
81
|
+
|
|
82
|
+
console.log(response.text)
|
|
83
|
+
} catch (error) {
|
|
84
|
+
return 'Error occurred while generating response'
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
> **Info:** You can also call `.generate()` with an array of message objects that include `role` and `content`. Visit the [.generate() reference](https://mastra.ai/reference/client-js/agents) for more information.
|
|
90
|
+
|
|
91
|
+
## Streaming responses
|
|
92
|
+
|
|
93
|
+
Use `.stream()` for real-time responses with a string prompt:
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
import { mastraClient } from 'lib/mastra-client'
|
|
97
|
+
|
|
98
|
+
const testAgent = async () => {
|
|
99
|
+
try {
|
|
100
|
+
const agent = mastraClient.getAgent('testAgent')
|
|
101
|
+
|
|
102
|
+
const stream = await agent.stream('Hello')
|
|
103
|
+
|
|
104
|
+
stream.processDataStream({
|
|
105
|
+
onTextPart: text => {
|
|
106
|
+
console.log(text)
|
|
107
|
+
},
|
|
108
|
+
})
|
|
109
|
+
} catch (error) {
|
|
110
|
+
return 'Error occurred while generating response'
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
> **Info:** You can also call `.stream()` with an array of message objects that include `role` and `content`. Visit the [.stream() reference](https://mastra.ai/reference/client-js/agents) for more information.
|
|
116
|
+
|
|
117
|
+
## Configuration options
|
|
118
|
+
|
|
119
|
+
`MastraClient` accepts optional parameters like `retries`, `backoffMs`, and `headers` to control request behavior. These parameters are useful for controlling retry behavior and including diagnostic metadata.
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
import { MastraClient } from '@mastra/client-js'
|
|
123
|
+
|
|
124
|
+
export const mastraClient = new MastraClient({
|
|
125
|
+
retries: 3,
|
|
126
|
+
backoffMs: 300,
|
|
127
|
+
maxBackoffMs: 5000,
|
|
128
|
+
headers: {
|
|
129
|
+
'X-Development': 'true',
|
|
130
|
+
},
|
|
131
|
+
})
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
> **Info:** Visit [MastraClient](https://mastra.ai/reference/client-js/mastra-client) for more configuration options.
|
|
135
|
+
|
|
136
|
+
## Adding request cancelling
|
|
137
|
+
|
|
138
|
+
`MastraClient` supports request cancellation using the standard Node.js `AbortSignal` API. Useful for canceling in-flight requests, such as when users abort an operation or to clean up stale network calls.
|
|
139
|
+
|
|
140
|
+
Pass an `AbortSignal` to the client constructor to enable cancellation across all requests.
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
import { MastraClient } from '@mastra/client-js'
|
|
144
|
+
|
|
145
|
+
export const controller = new AbortController()
|
|
146
|
+
|
|
147
|
+
export const mastraClient = new MastraClient({
|
|
148
|
+
baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
|
|
149
|
+
abortSignal: controller.signal,
|
|
150
|
+
})
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Using the `AbortController`
|
|
154
|
+
|
|
155
|
+
Calling `.abort()` will cancel any ongoing requests tied to that signal.
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import { mastraClient, controller } from 'lib/mastra-client'
|
|
159
|
+
|
|
160
|
+
const handleAbort = () => {
|
|
161
|
+
controller.abort()
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Client tools
|
|
166
|
+
|
|
167
|
+
Define tools directly in client-side applications using the `createTool()` function. Pass them to agents via the `clientTools` parameter in `.generate()` or `.stream()` calls.
|
|
168
|
+
|
|
169
|
+
This lets agents trigger browser-side functionality such as DOM manipulation, local storage access, or other Web APIs, enabling tool execution in the user's environment rather than on the server.
|
|
170
|
+
|
|
171
|
+
```typescript
|
|
172
|
+
import { createTool } from '@mastra/client-js'
|
|
173
|
+
import { z } from 'zod'
|
|
174
|
+
|
|
175
|
+
const handleClientTool = async () => {
|
|
176
|
+
try {
|
|
177
|
+
const agent = mastraClient.getAgent('colorAgent')
|
|
178
|
+
|
|
179
|
+
const colorChangeTool = createTool({
|
|
180
|
+
id: 'color-change-tool',
|
|
181
|
+
description: 'Changes the HTML background color',
|
|
182
|
+
inputSchema: z.object({
|
|
183
|
+
color: z.string(),
|
|
184
|
+
}),
|
|
185
|
+
outputSchema: z.object({
|
|
186
|
+
success: z.boolean(),
|
|
187
|
+
}),
|
|
188
|
+
execute: async inputData => {
|
|
189
|
+
const { color } = inputData
|
|
190
|
+
|
|
191
|
+
document.body.style.backgroundColor = color
|
|
192
|
+
return { success: true }
|
|
193
|
+
},
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
const response = await agent.generate('Change the background to blue', {
|
|
197
|
+
clientTools: { colorChangeTool },
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
console.log(response)
|
|
201
|
+
} catch (error) {
|
|
202
|
+
console.error(error)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Client tool's agent
|
|
208
|
+
|
|
209
|
+
This is a standard Mastra [agent](https://mastra.ai/docs/agents/overview) configured to return hex color codes, intended to work with the browser-based client tool defined above.
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
import { Agent } from '@mastra/core/agent'
|
|
213
|
+
|
|
214
|
+
export const colorAgent = new Agent({
|
|
215
|
+
id: 'color-agent',
|
|
216
|
+
name: 'Color Agent',
|
|
217
|
+
instructions: `You are a helpful CSS assistant.
|
|
218
|
+
You can change the background color of web pages.
|
|
219
|
+
Respond with a hex reference for the color requested by the user`,
|
|
220
|
+
model: 'openai/gpt-5.1',
|
|
221
|
+
})
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
## Server-side environments
|
|
225
|
+
|
|
226
|
+
You can also use `MastraClient` in server-side environments such as API routes, serverless functions or actions. The usage will broadly remain the same but you may need to recreate the response to your client:
|
|
227
|
+
|
|
228
|
+
```typescript
|
|
229
|
+
export async function action() {
|
|
230
|
+
const agent = mastraClient.getAgent('testAgent')
|
|
231
|
+
|
|
232
|
+
const stream = await agent.stream('Hello')
|
|
233
|
+
|
|
234
|
+
return new Response(stream.body)
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## Best practices
|
|
239
|
+
|
|
240
|
+
1. **Error Handling**: Implement proper [error handling](https://mastra.ai/reference/client-js/error-handling) for development scenarios.
|
|
241
|
+
2. **Environment Variables**: Use environment variables for configuration.
|
|
242
|
+
3. **Debugging**: Enable detailed [logging](https://mastra.ai/reference/client-js/logs) when needed.
|
|
243
|
+
4. **Performance**: Monitor application performance, [telemetry](https://mastra.ai/reference/client-js/telemetry) and traces.
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# toAISdkStream()
|
|
2
|
+
|
|
3
|
+
Converts Mastra streams (agent, network, or workflow) to AI SDK-compatible streams. Use this function when you need to manually transform Mastra streams for use with AI SDK's `createUIMessageStream()` and `createUIMessageStreamResponse()`.
|
|
4
|
+
|
|
5
|
+
This is useful when building custom streaming endpoints outside Mastra's provided route helpers such as [`chatRoute()`](https://mastra.ai/reference/ai-sdk/chat-route) or [`workflowRoute()`](https://mastra.ai/reference/ai-sdk/workflow-route).
|
|
6
|
+
|
|
7
|
+
## Usage example
|
|
8
|
+
|
|
9
|
+
Next.js App Router example:
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
import { mastra } from '../../mastra'
|
|
13
|
+
import { createUIMessageStream, createUIMessageStreamResponse } from 'ai'
|
|
14
|
+
import { toAISdkStream } from '@mastra/ai-sdk'
|
|
15
|
+
|
|
16
|
+
export async function POST(req: Request) {
|
|
17
|
+
const { messages } = await req.json()
|
|
18
|
+
const myAgent = mastra.getAgent('weatherAgent')
|
|
19
|
+
const stream = await myAgent.stream(messages)
|
|
20
|
+
|
|
21
|
+
const uiMessageStream = createUIMessageStream({
|
|
22
|
+
originalMessages: messages,
|
|
23
|
+
execute: async ({ writer }) => {
|
|
24
|
+
for await (const part of toAISdkStream(stream, { from: 'agent' })) {
|
|
25
|
+
await writer.write(part)
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
return createUIMessageStreamResponse({
|
|
31
|
+
stream: uiMessageStream,
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
> **Tip:** Pass `messages` to `originalMessages` in `createUIMessageStream()` to avoid duplicated assistant messages in the UI. See [Troubleshooting: Repeated Assistant Messages](https://ai-sdk.dev/docs/troubleshooting/repeated-assistant-messages) for details.
|
|
37
|
+
|
|
38
|
+
## Parameters
|
|
39
|
+
|
|
40
|
+
The first parameter is the Mastra stream to convert. It can be one of:
|
|
41
|
+
|
|
42
|
+
- `MastraModelOutput` - An agent stream from `agent.stream()`
|
|
43
|
+
- `MastraAgentNetworkStream` - A network stream from `agent.network()`
|
|
44
|
+
- `MastraWorkflowStream` or `WorkflowRunOutput` - A workflow stream
|
|
45
|
+
|
|
46
|
+
The second parameter is an options object:
|
|
47
|
+
|
|
48
|
+
**from:** (`'agent' | 'network' | 'workflow'`): The type of Mastra stream being converted. (Default: `'agent'`)
|
|
49
|
+
|
|
50
|
+
**lastMessageId?:** (`string`): (Agent only) The ID of the last message in the conversation.
|
|
51
|
+
|
|
52
|
+
**sendStart?:** (`boolean`): (Agent only) Whether to send start events in the stream. (Default: `true`)
|
|
53
|
+
|
|
54
|
+
**sendFinish?:** (`boolean`): (Agent only) Whether to send finish events in the stream. (Default: `true`)
|
|
55
|
+
|
|
56
|
+
**sendReasoning?:** (`boolean`): (Agent only) Whether to include reasoning-delta chunks in the stream. Set to true to stream reasoning content from models that support extended thinking. (Default: `false`)
|
|
57
|
+
|
|
58
|
+
**sendSources?:** (`boolean`): (Agent only) Whether to include source citations in the output. (Default: `false`)
|
|
59
|
+
|
|
60
|
+
**includeTextStreamParts?:** (`boolean`): (Workflow only) Whether to include text stream parts in the output. (Default: `true`)
|
|
61
|
+
|
|
62
|
+
**messageMetadata?:** (`(options: { part: UIMessageStreamPart }) => Record<string, unknown> | undefined`): (Agent only) A function that receives the current stream part and returns metadata to attach to start and finish chunks.
|
|
63
|
+
|
|
64
|
+
**onError?:** (`(error: unknown) => string`): (Agent only) A function to handle errors during stream conversion. Receives the error and should return a string representation.
|
|
65
|
+
|
|
66
|
+
## Examples
|
|
67
|
+
|
|
68
|
+
### Converting a workflow stream
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
import { mastra } from '../../mastra'
|
|
72
|
+
import { createUIMessageStream, createUIMessageStreamResponse } from 'ai'
|
|
73
|
+
import { toAISdkStream } from '@mastra/ai-sdk'
|
|
74
|
+
|
|
75
|
+
export async function POST(req: Request) {
|
|
76
|
+
const { input } = await req.json()
|
|
77
|
+
const workflow = mastra.getWorkflow('myWorkflow')
|
|
78
|
+
const run = workflow.createRun()
|
|
79
|
+
const stream = await run.stream({ inputData: input })
|
|
80
|
+
|
|
81
|
+
const uiMessageStream = createUIMessageStream({
|
|
82
|
+
execute: async ({ writer }) => {
|
|
83
|
+
for await (const part of toAISdkStream(stream, { from: 'workflow' })) {
|
|
84
|
+
await writer.write(part)
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
return createUIMessageStreamResponse({
|
|
90
|
+
stream: uiMessageStream,
|
|
91
|
+
})
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Converting a network stream
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
import { mastra } from '../../mastra'
|
|
99
|
+
import { createUIMessageStream, createUIMessageStreamResponse } from 'ai'
|
|
100
|
+
import { toAISdkStream } from '@mastra/ai-sdk'
|
|
101
|
+
|
|
102
|
+
export async function POST(req: Request) {
|
|
103
|
+
const { messages } = await req.json()
|
|
104
|
+
const routingAgent = mastra.getAgent('routingAgent')
|
|
105
|
+
const stream = await routingAgent.network(messages)
|
|
106
|
+
|
|
107
|
+
const uiMessageStream = createUIMessageStream({
|
|
108
|
+
execute: async ({ writer }) => {
|
|
109
|
+
for await (const part of toAISdkStream(stream, { from: 'network' })) {
|
|
110
|
+
await writer.write(part)
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
return createUIMessageStreamResponse({
|
|
116
|
+
stream: uiMessageStream,
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Converting an agent stream with reasoning enabled
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
import { mastra } from '../../mastra'
|
|
125
|
+
import { createUIMessageStream, createUIMessageStreamResponse } from 'ai'
|
|
126
|
+
import { toAISdkStream } from '@mastra/ai-sdk'
|
|
127
|
+
|
|
128
|
+
export async function POST(req: Request) {
|
|
129
|
+
const { messages } = await req.json()
|
|
130
|
+
const reasoningAgent = mastra.getAgent('reasoningAgent')
|
|
131
|
+
const stream = await reasoningAgent.stream(messages, {
|
|
132
|
+
providerOptions: {
|
|
133
|
+
openai: { reasoningEffort: 'high' },
|
|
134
|
+
},
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
const uiMessageStream = createUIMessageStream({
|
|
138
|
+
originalMessages: messages,
|
|
139
|
+
execute: async ({ writer }) => {
|
|
140
|
+
for await (const part of toAISdkStream(stream, {
|
|
141
|
+
from: 'agent',
|
|
142
|
+
sendReasoning: true,
|
|
143
|
+
})) {
|
|
144
|
+
await writer.write(part)
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
return createUIMessageStreamResponse({
|
|
150
|
+
stream: uiMessageStream,
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### Using messageMetadata
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import { mastra } from '../../mastra'
|
|
159
|
+
import { createUIMessageStream, createUIMessageStreamResponse } from 'ai'
|
|
160
|
+
import { toAISdkStream } from '@mastra/ai-sdk'
|
|
161
|
+
|
|
162
|
+
export async function POST(req: Request) {
|
|
163
|
+
const { messages } = await req.json()
|
|
164
|
+
const myAgent = mastra.getAgent('weatherAgent')
|
|
165
|
+
const stream = await myAgent.stream(messages)
|
|
166
|
+
|
|
167
|
+
const uiMessageStream = createUIMessageStream({
|
|
168
|
+
originalMessages: messages,
|
|
169
|
+
execute: async ({ writer }) => {
|
|
170
|
+
for await (const part of toAISdkStream(stream, {
|
|
171
|
+
from: 'agent',
|
|
172
|
+
messageMetadata: ({ part }) => ({
|
|
173
|
+
timestamp: Date.now(),
|
|
174
|
+
partType: part.type,
|
|
175
|
+
}),
|
|
176
|
+
})) {
|
|
177
|
+
await writer.write(part)
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
return createUIMessageStreamResponse({
|
|
183
|
+
stream: uiMessageStream,
|
|
184
|
+
})
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
### Client-side stream transformation
|
|
189
|
+
|
|
190
|
+
If you're using the Mastra client SDK (`@mastra/client-js`) on the client side and want to convert streams to AI SDK format:
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
import { MastraClient } from '@mastra/client-js'
|
|
194
|
+
import { createUIMessageStream } from 'ai'
|
|
195
|
+
import { toAISdkStream } from '@mastra/ai-sdk'
|
|
196
|
+
import type { ChunkType, MastraModelOutput } from '@mastra/core/stream'
|
|
197
|
+
|
|
198
|
+
const client = new MastraClient({
|
|
199
|
+
baseUrl: 'http://localhost:4111',
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
const agent = client.getAgent('weatherAgent')
|
|
203
|
+
const response = await agent.stream('What is the weather in Tokyo?')
|
|
204
|
+
|
|
205
|
+
// Convert the client SDK stream to a ReadableStream<ChunkType>
|
|
206
|
+
const chunkStream = new ReadableStream<ChunkType>({
|
|
207
|
+
async start(controller) {
|
|
208
|
+
await response.processDataStream({
|
|
209
|
+
onChunk: async chunk => {
|
|
210
|
+
controller.enqueue(chunk)
|
|
211
|
+
},
|
|
212
|
+
})
|
|
213
|
+
controller.close()
|
|
214
|
+
},
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
// Transform to AI SDK format
|
|
218
|
+
const uiMessageStream = createUIMessageStream({
|
|
219
|
+
execute: async ({ writer }) => {
|
|
220
|
+
for await (const part of toAISdkStream(chunkStream as unknown as MastraModelOutput, {
|
|
221
|
+
from: 'agent',
|
|
222
|
+
})) {
|
|
223
|
+
await writer.write(part)
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
})
|
|
227
|
+
|
|
228
|
+
for await (const part of uiMessageStream) {
|
|
229
|
+
console.log(part)
|
|
230
|
+
}
|
|
231
|
+
```
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# toAISdkV4Messages()
|
|
2
|
+
|
|
3
|
+
Converts messages from various input formats to AI SDK V4 UI message format. This function accepts messages in multiple formats (strings, AI SDK V4/V5 messages, Mastra DB messages, etc.) and normalizes them to the AI SDK V4 `UIMessage` format, which is suitable for use with AI SDK UI components like `useChat()`.
|
|
4
|
+
|
|
5
|
+
## Usage example
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
import { toAISdkV4Messages } from '@mastra/ai-sdk'
|
|
9
|
+
import { useChat } from 'ai/react' // AI SDK V4
|
|
10
|
+
|
|
11
|
+
// Stored messages from your database, memory or API
|
|
12
|
+
const storedMessages = [
|
|
13
|
+
{ id: '1', role: 'user', parts: [{ type: 'text', text: 'Hello' }] },
|
|
14
|
+
{ id: '2', role: 'assistant', parts: [{ type: 'text', text: 'Hi there!' }] },
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
export default function Chat() {
|
|
18
|
+
const { messages } = useChat({
|
|
19
|
+
initialMessages: toAISdkV4Messages(storedMessages),
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
return (
|
|
23
|
+
<div>
|
|
24
|
+
{messages.map(message => (
|
|
25
|
+
<div key={message.id}>
|
|
26
|
+
{message.role}: {message.content}
|
|
27
|
+
</div>
|
|
28
|
+
))}
|
|
29
|
+
</div>
|
|
30
|
+
)
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Parameters
|
|
35
|
+
|
|
36
|
+
**messages:** (`MessageListInput`): Messages to convert. Can be a string, array of strings, a single message object, or an array of message objects in any supported format.
|
|
37
|
+
|
|
38
|
+
## Returns
|
|
39
|
+
|
|
40
|
+
Returns an array of AI SDK V4 `UIMessage` objects with the following structure:
|
|
41
|
+
|
|
42
|
+
**id:** (`string`): Unique message identifier.
|
|
43
|
+
|
|
44
|
+
**role:** (`'user' | 'assistant' | 'system'`): The role of the message sender.
|
|
45
|
+
|
|
46
|
+
**content:** (`string`): Text content of the message.
|
|
47
|
+
|
|
48
|
+
**parts:** (`UIMessagePart[]`): Array of UI parts including text, tool-invocation, file, reasoning, source, and step markers.
|
|
49
|
+
|
|
50
|
+
**createdAt:** (`Date`): Message creation timestamp.
|
|
51
|
+
|
|
52
|
+
**toolInvocations?:** (`ToolInvocation[]`): Array of tool invocations for assistant messages.
|
|
53
|
+
|
|
54
|
+
**experimental\_attachments?:** (`Attachment[]`): File attachments on the message.
|
|
55
|
+
|
|
56
|
+
**metadata?:** (`Record<string, unknown>`): Custom metadata attached to the message.
|
|
57
|
+
|
|
58
|
+
## Examples
|
|
59
|
+
|
|
60
|
+
### Converting simple text messages
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
import { toAISdkV4Messages } from '@mastra/ai-sdk'
|
|
64
|
+
|
|
65
|
+
const messages = toAISdkV4Messages(['Hello', 'How can I help you today?'])
|
|
66
|
+
// Returns array of UIMessage objects with user role and content string
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Loading messages with Mastra client
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import { MastraClient } from '@mastra/client-js'
|
|
73
|
+
import { toAISdkV4Messages } from '@mastra/ai-sdk'
|
|
74
|
+
|
|
75
|
+
const client = new MastraClient()
|
|
76
|
+
|
|
77
|
+
const { messages } = await client.listThreadMessages('thread-id', { agentId: 'myAgent' })
|
|
78
|
+
const uiMessages = toAISdkV4Messages(messages)
|
|
79
|
+
```
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# toAISdkV5Messages()
|
|
2
|
+
|
|
3
|
+
Converts messages from various input formats to AI SDK V5 (and later) UI message format. This function accepts messages in multiple formats (strings, AI SDK V4/V5 messages, Mastra DB messages, etc.) and normalizes them to the AI SDK V5+ `UIMessage` format, which is suitable for use with AI SDK UI components like `useChat()`.
|
|
4
|
+
|
|
5
|
+
## Usage example
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
import { toAISdkV5Messages } from '@mastra/ai-sdk/ui'
|
|
9
|
+
import { useChat } from 'ai/react'
|
|
10
|
+
|
|
11
|
+
// Stored messages from your database, memory or API
|
|
12
|
+
const storedMessages = [
|
|
13
|
+
{ id: '1', role: 'user', content: 'Hello', parts: [{ type: 'text', text: 'Hello' }] },
|
|
14
|
+
{
|
|
15
|
+
id: '2',
|
|
16
|
+
role: 'assistant',
|
|
17
|
+
content: 'Hi there!',
|
|
18
|
+
parts: [{ type: 'text', text: 'Hi there!' }],
|
|
19
|
+
},
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
export default function Chat() {
|
|
23
|
+
const { messages } = useChat({
|
|
24
|
+
initialMessages: toAISdkV5Messages(storedMessages),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
return (
|
|
28
|
+
<div>
|
|
29
|
+
{messages.map(message => (
|
|
30
|
+
<div key={message.id}>
|
|
31
|
+
{message.role}: {message.parts.map(part => (part.type === 'text' ? part.text : null))}
|
|
32
|
+
</div>
|
|
33
|
+
))}
|
|
34
|
+
</div>
|
|
35
|
+
)
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Parameters
|
|
40
|
+
|
|
41
|
+
**messages:** (`MessageListInput`): Messages to convert. Can be a string, array of strings, a single message object, or an array of message objects in any supported format.
|
|
42
|
+
|
|
43
|
+
## Returns
|
|
44
|
+
|
|
45
|
+
Returns an array of AI SDK V5+ `UIMessage` objects with the following structure:
|
|
46
|
+
|
|
47
|
+
**id:** (`string`): Unique message identifier.
|
|
48
|
+
|
|
49
|
+
**role:** (`'user' | 'assistant' | 'system'`): The role of the message sender.
|
|
50
|
+
|
|
51
|
+
**parts:** (`UIMessagePart[]`): Array of UI parts including text, tool results, files, reasoning, sources, and step markers.
|
|
52
|
+
|
|
53
|
+
**metadata?:** (`Record<string, unknown>`): Optional metadata including createdAt, threadId, resourceId, and custom fields.
|
|
54
|
+
|
|
55
|
+
## Examples
|
|
56
|
+
|
|
57
|
+
### Converting simple text messages
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import { toAISdkV5Messages } from '@mastra/ai-sdk/ui'
|
|
61
|
+
|
|
62
|
+
const messages = toAISdkV5Messages(['Hello', 'How can I help you today?'])
|
|
63
|
+
// Returns array of UIMessage objects with user role
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Loading messages with Mastra client
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
import { MastraClient } from '@mastra/client-js'
|
|
70
|
+
import { toAISdkV5Messages } from '@mastra/ai-sdk/ui'
|
|
71
|
+
|
|
72
|
+
const client = new MastraClient()
|
|
73
|
+
|
|
74
|
+
const { messages } = await client.listThreadMessages('thread-id', { agentId: 'myAgent' })
|
|
75
|
+
const uiMessages = toAISdkV5Messages(messages)
|
|
76
|
+
```
|