Skip to content

Commit 74e6767

Browse files
authored
feat: update quickstart snippets for latest auth0-ai sdks (#158)
* feat: update quickstart snippets for latest auth0-ai sdks * feat: update highlights
1 parent e047bb3 commit 74e6767

File tree

8 files changed

+252
-169
lines changed

8 files changed

+252
-169
lines changed

auth4genai/snippets/get-started/langchain-fastapi-py/async-auth.mdx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,9 @@ with_async_authorization = auth0_ai.with_async_authorization(
9494
# could crash or timeout before the user approves the request.
9595
on_authorization_request="block",
9696

97+
# Note: Setting a requested expiry greater than 300 (seconds) will force email verification
98+
# instead of using the push notification flow.
99+
# requested_expiry=301,
97100
)
98101
```
99102

auth4genai/snippets/get-started/langchain-next-js/async-auth.mdx

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ In the root directory of your project, install the following dependencies:
2323
- `langgraph-nextjs-api-passthrough`: API passthrough for LangGraph.
2424

2525
```bash wrap lines
26-
npm install @auth0/ai-langchain@4 @langchain/[email protected] @langchain/[email protected].4 @langchain/[email protected] [email protected].12 [email protected]
26+
npm install @auth0/ai-langchain@4 @langchain/[email protected] @langchain/[email protected].9 @langchain/[email protected] [email protected].33 [email protected]
2727
```
2828
### Update the environment file
2929

@@ -56,16 +56,34 @@ export const withAsyncAuthorization = auth0AI.withAsyncAuthorization({
5656
audience: process.env["SHOP_API_AUDIENCE"]!,
5757

5858
/**
59+
* Note: setting a requestedExpiry to >= 301 will currently ensure email is used. Otherwise,
60+
* the default is to use push notification if available.
61+
*/
62+
// requestedExpiry: 301,
63+
64+
/**
65+
* The behavior when the authorization request is made.
66+
*
67+
* - `block`: The tool execution is blocked until the user completes the authorization.
68+
* - `interrupt`: The tool execution is interrupted until the user completes the authorization.
69+
* - a callback: Same as "block" but give access to the auth request and executing logic.
70+
*
71+
* Defaults to `interrupt`.
72+
*
5973
* When this flag is set to `block`, the execution of the tool awaits
6074
* until the user approves or rejects the request.
61-
*
6275
* Given the asynchronous nature of the CIBA flow, this mode
6376
* is only useful during development.
6477
*
6578
* In practice, the process that is awaiting the user confirmation
6679
* could crash or timeout before the user approves the request.
6780
*/
68-
onAuthorizationRequest: "block",
81+
onAuthorizationRequest: async (authReq, creds) => {
82+
console.log(`An authorization request was sent to your mobile device or your email.`);
83+
await creds;
84+
console.log(`Thanks for approving the order.`);
85+
},
86+
6987
onUnauthorized: async (e: Error) => {
7088
if (e instanceof AccessDeniedInterrupt) {
7189
return "The user has denied the request";

auth4genai/snippets/get-started/vercel-ai-next-js/async-auth.mdx

Lines changed: 36 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ In the root directory of your project, install the following dependencies:
2222
- `zod`: TypeScript-first schema validation library.
2323

2424
```bash wrap lines
25-
npm install @auth0/ai-vercel@4 ai@4 @ai-sdk/openai@1 @ai-sdk/react@1 zod@3
25+
npm install @auth0/ai-vercel@4 ai@5.0.33 @ai-sdk/openai@2.0.24 @ai-sdk/react@2.0.33 zod@3.25.76
2626
```
2727

2828
### Update the environment file
@@ -59,16 +59,34 @@ export const withAsyncAuthorization = auth0AI.withAsyncAuthorization({
5959
audience: process.env["SHOP_API_AUDIENCE"]!,
6060

6161
/**
62+
* Note: Setting a requested expiry greater than 300 (seconds) will force email verification
63+
* instead of using the push notification flow.
64+
*/
65+
// requestedExpiry: 301,
66+
67+
/**
68+
* The behavior when the authorization request is made.
69+
*
70+
* - `block`: The tool execution is blocked until the user completes the authorization.
71+
* - `interrupt`: The tool execution is interrupted until the user completes the authorization.
72+
* - a callback: Same as "block" but give access to the auth request and executing logic.
73+
*
74+
* Defaults to `interrupt`.
75+
*
6276
* When this flag is set to `block`, the execution of the tool awaits
6377
* until the user approves or rejects the request.
64-
*
6578
* Given the asynchronous nature of the CIBA flow, this mode
6679
* is only useful during development.
6780
*
6881
* In practice, the process that is awaiting the user confirmation
6982
* could crash or timeout before the user approves the request.
7083
*/
71-
onAuthorizationRequest: "block",
84+
onAuthorizationRequest: async (authReq, creds) => {
85+
console.log(`An authorization request was sent to your mobile device or your email.`);
86+
await creds;
87+
console.log(`Thanks for approving the order.`);
88+
},
89+
7290
onUnauthorized: async (e: Error) => {
7391
if (e instanceof AccessDeniedInterrupt) {
7492
return "The user has denied the request";
@@ -185,42 +203,37 @@ SHOP_API_AUDIENCE=sample-shop-api
185203

186204
Call the tool from your AI app to make purchases. Update the `src/app/api/chat/route.ts` file with the following code:
187205

188-
```ts src/app/api/chat/route.ts wrap lines highlight={2,3,11,14}
206+
```ts src/app/api/chat/route.ts wrap lines highlight={2,3,11,13}
189207
//...
190208
import { setAIContext } from "@auth0/ai-vercel";
191209
import { shopOnlineTool } from "@/lib/tools/shop-online";
192210

193211
//...
194212
export async function POST(req: NextRequest) {
195-
const request = await req.json();
196-
197-
const messages = sanitizeMessages(request.messages);
213+
const { id, messages }: { id: string; messages: Array<UIMessage> } = await req.json();
198214

199-
setAIContext({ threadID: request.id });
215+
const tools = { shopOnlineTool };
200216

201-
const tools = {
202-
shopOnlineTool,
203-
};
217+
setAIContext({ threadID: id });
204218

205-
return createDataStreamResponse({
206-
execute: async (dataStream: DataStreamWriter) => {
219+
const stream = createUIMessageStream({
220+
async execute({ writer }) {
207221
const result = streamText({
208-
model: openai("gpt-4o-mini"),
222+
model: openai.chat('gpt-4o-mini'),
209223
system: AGENT_SYSTEM_TEMPLATE,
210-
messages,
211-
maxSteps: 5,
224+
messages: convertToModelMessages(messages),
212225
tools,
213226
});
214227

215-
result.mergeIntoDataStream(dataStream, {
216-
sendReasoning: true,
217-
});
218-
},
219-
onError: (err: any) => {
220-
console.log(err);
221-
return `An error occurred! ${err.message}`;
228+
writer.merge(
229+
result.toUIMessageStream({
230+
sendReasoning: true,
231+
}),
232+
);
222233
},
223234
});
235+
236+
return createUIMessageStreamResponse({ stream });
224237
}
225238
//...
226239
```

auth4genai/snippets/get-started/vercel-ai-next-js/auth-for-rag.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ In the root directory of your project, install the following dependencies:
2222
- `zod`: TypeScript-first schema validation library.
2323

2424
```bash wrap lines
25-
npm install @auth0/ai-vercel@4 ai@4 @ai-sdk/openai@1 @ai-sdk/react@1 zod@3
25+
npm install @auth0/ai-vercel@4 ai@5.0.33 @ai-sdk/openai@2.0.24 @ai-sdk/react@2.0.33 zod@3.25.76
2626
```
2727

2828
### Update the environment file

auth4genai/snippets/get-started/vercel-ai-next-js/call-others-api.mdx

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ In the root directory of your project, install the following packages:
8181
- `googleapis`: Node.js client for Google APIs that supports authentication and authorization with OAuth 2.0.
8282

8383
```bash wrap lines
84-
npm install @auth0/ai-vercel@4 ai@4 @ai-sdk/openai@1 @ai-sdk/react@1 zod@3 googleapis@148
84+
npm install @auth0/ai-vercel@4 ai@5.0.33 @ai-sdk/openai@2.0.24 @ai-sdk/react@2.0.33 zod@3.25.76 googleapis@161
8585
```
8686

8787
### Update your environment file
@@ -177,7 +177,7 @@ import { getAccessToken, withGoogleConnection } from '../auth0-ai';
177177
export const getCalendarEventsTool = withGoogleConnection(
178178
tool({
179179
description: `Get calendar events for a given date from the user's Google Calendar`,
180-
parameters: z.object({
180+
inputSchema: z.object({
181181
date: z.coerce.date(),
182182
}),
183183
execute: async ({ date }) => {
@@ -342,7 +342,7 @@ Now when step-up authorization is required, the user will see a prompt in the ch
342342

343343
Handle the interrupts from the AI agent and call the tool from your AI app to get calendar events. Update your chat route, typically at `/src/app/api/chat/route.ts`, as shown in the following example:
344344

345-
```ts src/app/api/chat/route.ts wrap lines highlight={2-7,14,17,21,35-38,40-43}
345+
```ts src/app/api/chat/route.ts wrap lines
346346
//...
347347
import { setAIContext } from "@auth0/ai-vercel";
348348
import {
@@ -362,31 +362,53 @@ export async function POST(req: NextRequest) {
362362
getCalendarEventsTool,
363363
};
364364

365-
return createDataStreamResponse({
365+
const modelMessages = convertToModelMessages(messages);
366+
367+
const stream = createUIMessageStream({
368+
originalMessages: messages,
366369
execute: withInterruptions(
367-
async (dataStream: DataStreamWriter) => {
370+
async ({ writer }) => {
368371
const result = streamText({
369-
model: openai("gpt-4o-mini"),
372+
model: openai('gpt-4o-mini'),
370373
system: AGENT_SYSTEM_TEMPLATE,
371-
messages,
372-
maxSteps: 5,
374+
messages: modelMessages,
373375
tools,
374-
});
375376

376-
result.mergeIntoDataStream(dataStream, {
377-
sendReasoning: true,
377+
onFinish: (output) => {
378+
if (output.finishReason === 'tool-calls') {
379+
const lastMessage = output.content[output.content.length - 1];
380+
if (lastMessage?.type === 'tool-error') {
381+
const { toolName, toolCallId, error, input } = lastMessage;
382+
const serializableError = {
383+
cause: error,
384+
toolCallId: toolCallId,
385+
toolName: toolName,
386+
toolArgs: input,
387+
};
388+
389+
throw serializableError;
390+
}
391+
}
392+
},
378393
});
394+
writer.merge(
395+
result.toUIMessageStream({
396+
sendReasoning: true,
397+
}),
398+
);
379399
},
380400
{
381-
messages,
401+
messages: messages,
382402
tools,
383-
}
403+
},
384404
),
385-
onError: errorSerializer((err: any) => {
386-
console.log(err);
387-
return `An error occurred! ${err.message}`;
405+
onError: errorSerializer((err) => {
406+
console.error('ai-sdk route: stream error', err);
407+
return 'Oops, an error occured!';
388408
}),
389409
});
410+
411+
return createUIMessageStreamResponse({ stream });
390412
}
391413
```
392414

auth4genai/snippets/get-started/vercel-ai-next-js/call-your-api.mdx

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ In the root directory of your project, install the following dependencies:
2121
- `zod`: TypeScript-first schema validation library.
2222

2323
```bash wrap lines
24-
npm install ai@4 @ai-sdk/openai@1 @ai-sdk/react@1 zod@3
24+
npm install ai@5.0.33 @ai-sdk/openai@2.0.24 @ai-sdk/react@2.0.33 zod@3.25.76
2525
```
2626

2727
### Update the environment file
@@ -42,7 +42,7 @@ import { auth0 } from "../auth0";
4242

4343
export const getUserInfoTool = tool({
4444
description: "Get information about the current logged in user.",
45-
parameters: z.object({}),
45+
inputSchema: z.object({}),
4646
execute: async () => {
4747
const session = await auth0.getSession();
4848
if (!session) {
@@ -71,39 +71,45 @@ export const getUserInfoTool = tool({
7171

7272
The AI agent processes and runs the user's request through the AI pipeline, including the tool call. Vercel AI simplifies this task with the `streamText()` method. Update the `/src/app/api/chat/route.ts` file with the following code:
7373

74-
```ts src/app/api/chat/route.ts wrap lines highlight={2,11}
74+
```ts src/app/api/chat/route.ts wrap lines highlight={2,11-13,23}
7575
//...
7676
import { getUserInfoTool } from "@/lib/tools/user-info";
7777

7878
//... existing code
7979

8080
export async function POST(req: NextRequest) {
81-
const request = await req.json();
82-
const messages = sanitizeMessages(request.messages);
81+
const { id, messages }: { id: string; messages: Array<UIMessage> } = await req.json();
82+
83+
setAIContext({ threadID: id });
8384

8485
const tools = {
8586
getUserInfoTool,
8687
};
8788

88-
return createDataStreamResponse({
89-
execute: async (dataStream: DataStreamWriter) => {
89+
const stream = createUIMessageStream({
90+
originalMessages: messages,
91+
execute: async ({ writer }) => {
9092
const result = streamText({
91-
model: openai("gpt-4o-mini"),
93+
model: openai('gpt-4o-mini'),
9294
system: AGENT_SYSTEM_TEMPLATE,
93-
messages,
94-
maxSteps: 5,
95+
messages: convertToModelMessages(messages),
96+
stopWhen: stepCountIs(5),
9597
tools,
9698
});
9799

98-
result.mergeIntoDataStream(dataStream, {
99-
sendReasoning: true,
100-
});
100+
writer.merge(
101+
result.toUIMessageStream({
102+
sendReasoning: true,
103+
})
104+
);
101105
},
102106
onError: (err: any) => {
103107
console.log(err);
104108
return `An error occurred! ${err.message}`;
105109
},
106110
});
111+
112+
return createUIMessageStreamResponse({ stream });
107113
}
108114
//... existing code
109115
```

0 commit comments

Comments
 (0)