11---
22title : Genkit SDK
33description : Auth0 for AI Agents Genkit SDK makes it easy for developers to integrate with and secure AI agent workflows using Genkit.
4- sidebarTitle : Genkit
4+ sidebarTitle : Genkit SDK
55---
66
77### [ Auth0 AI for Genkit] ( https://github.com/auth0-lab/auth0-ai-js/tree/main/packages/ai-genkit )
@@ -15,52 +15,190 @@ This SDK provides building blocks for using Auth0 for AI Agents with [Genkit](ht
1515npm install @auth0/ai-genkit
1616```
1717
18- ## Sample applications
19-
20- Checkout our sample applications for Genkit.
21-
22- <Columns cols = { 2 } >
23- <Card
24- title = " AI Samples"
25- href = " https://github.com/auth0-samples/auth0-ai-samples"
26- >
27- Explore our repository of standalone sample applications that showcase
28- Auth0's authentication and authorization capabilities in generative AI
29- applications. Each sample demonstrates a specific Auth0 for AI Agents feature.
30- </Card >
31- <Card
32- title = " Auth0 AI SDK Samples"
33- href = " https://github.com/auth0-lab/auth0-ai-js/tree/main/examples"
34- >
35- Explore example applications that accompany Auth0's JavaScript AI SDKs.
36- These demonstrate recommended implementation patterns for the SDKs.
37- </Card >
38- </Columns >
39-
40- ## Guides & Tutorials
41-
42- Checkout our guides for Genkit in TypeScript.
43-
44- <Columns cols = { 2 } >
45- <Card
46- title = " Check Google Calendar Availability"
47- href = " /how-tos/check-google-calendar-availability"
48- icon = " google"
49- iconType = " solid"
50- horizontal
51- />
52- <Card
53- title = " List GitHub Repositories"
54- href = " /how-tos/list-github-repositories"
55- icon = " github"
56- iconType = " solid"
57- horizontal
58- />
59- <Card
60- title = " List Slack Channels"
61- href = " /how-tos/list-slack-channels"
62- icon = " slack"
63- iconType = " solid"
64- horizontal
65- />
66- </Columns >
18+ Below are examples that demonstrate how to integrate Auth0’s token vault and authorization flows with AI tools. You’ll see how to:
19+
20+ - Use a token vault to call third-party APIs on behalf of the user
21+ - Use Client-Initiated Backchannel Authentication (CIBA) for consent flows
22+ - Apply Okta FGA authorization in Retrieval-Augmented Generation (RAG) scenarios
23+
24+ For more examples, click [ here] ( https://github.com/auth0/auth0-ai-js/tree/main/packages/ai-langchain ) .
25+
26+ <AccordionGroup >
27+ <Accordion title = " Calling 3rd Party APIs" >
28+ Token Vault allows you to exchange refresh tokens for access tokens for third-party APIs. This is useful when you want to use a token vault (like Google, Facebook, etc.) to authenticate users and then use the access token to call the API on behalf of the user.
29+
30+ First initialize the Token Vault Authorizer as follows:
31+
32+ ``` javascript lines
33+ const withGoogleAccess = auth0AI .withTokenVault ({
34+ // this is the defaults:
35+ refreshToken: async (params ) => {
36+ return context .refreshToken ;
37+ },
38+ // The connection name:
39+ connection: " google-oauth2" ,
40+ // The scopes to request:
41+ scopes: [" https://www.googleapis.com/auth/calendar.freebusy" ],
42+ });
43+ ```
44+
45+ Then use the ` withGoogleAccess ` to wrap the tool and use ` getAccessTokenFromTokenVault ` from the SDK to get the access token.
46+
47+ ``` javascript lines focus={1,2,19,27-34} expandable
48+ import { getAccessTokenFromTokenVault } from " @auth0/ai-genkit" ;
49+ import { TokenVaultError } from " @auth0/ai/interrupts" ;
50+ import { addHours } from " date-fns" ;
51+ import { z } from " zod" ;
52+
53+ export const checkCalendarTool = ai .defineTool (
54+ ... withGoogleAccess ({
55+ name: " check_user_calendar" ,
56+ description:
57+ " Check user availability on a given date time on their calendar" ,
58+ inputSchema: z .object ({
59+ date: z .coerce .date (),
60+ }),
61+ outputSchema: z .object ({
62+ available: z .boolean (),
63+ }),
64+ },
65+ async ({ date }) => {
66+ const accessToken = getAccessTokenFromTokenVault ();
67+ const body = JSON .stringify ({
68+ timeMin: date,
69+ timeMax: addHours (date, 1 ),
70+ timeZone: " UTC" ,
71+ items: [{ id: " primary" }],
72+ });
73+
74+ const response = await fetch (url, {
75+ method: " POST" ,
76+ headers: {
77+ Authorization: ` Bearer ${ accessToken} ` ,
78+ " Content-Type" : " application/json" ,
79+ },
80+ body,
81+ });
82+
83+ if (! response .ok ) {
84+ if (response .status === 401 ) {
85+ throw new TokenVaultError (
86+ ` Authorization required to access the Token Vault`
87+ );
88+ }
89+ throw new Error (
90+ ` Invalid response from Google Calendar API: ${
91+ response .status
92+ } - ${ await response .text ()} `
93+ );
94+ }
95+ const busyResp = await response .json ();
96+ return { available: busyResp .calendars .primary .busy .length === 0 };
97+ }
98+ ));
99+ ```
100+ </Accordion >
101+ <Accordion title = " Using Client-Initiated Backchannel Authentication" >
102+ CIBA (Client-Initiated Backchannel Authentication) enables secure, user-in-the-loop authentication for sensitive operations. This flow allows you to request user authorization asynchronously and resume execution once authorization is granted.
103+
104+ ``` javascript lines
105+ const buyStockAuthorizer = auth0AI .withAsyncAuthorization ({
106+ // A callback to retrieve the userID from tool context.
107+ userID : (_params , config ) => {
108+ return config .configurable ? .user_id ;
109+ },
110+ // The message the user will see on the notification
111+ bindingMessage: async ({ qty , ticker }) => {
112+ return ` Confirm the purchase of ${ qty} ${ ticker} ` ;
113+ },
114+ // Expiration for this request in seconds (default=300s)
115+ requestedExpiry: 300 ,
116+ // The scopes and audience to request
117+ audience: process .env [" AUDIENCE" ],
118+ scopes: [" stock:trade" ]
119+ });
120+ ` ` `
121+
122+ Then wrap the tool as follows:
123+
124+ ` ` ` javascript lines expandable
125+ import { z } from " zod" ;
126+ import { getAsyncAuthorizationCredentials } from " @auth0/ai-genkit" ;
127+
128+ export const buyTool = ai .defineTool (
129+ ... buyStockAuthorizer ({
130+ name: " buy_stock" ,
131+ description: " Execute a stock purchase given stock ticker and quantity" ,
132+ inputSchema: z .object ({
133+ tradeID: z
134+ .string ()
135+ .uuid ()
136+ .describe (" The unique identifier for the trade provided by the user" ),
137+ userID: z
138+ .string ()
139+ .describe (" The user ID of the user who created the conditional trade" ),
140+ ticker: z .string ().describe (" The stock ticker to trade" ),
141+ qty: z
142+ .number ()
143+ .int ()
144+ .positive ()
145+ .describe (" The quantity of shares to trade" ),
146+ }),
147+ outputSchema: z .string (),
148+ },
149+ async ({ ticker, qty }) => {
150+ const { accessToken } = getAsyncAuthorizationCredentials ();
151+ fetch (" http://yourapi.com/buy" , {
152+ method: " POST" ,
153+ headers: {
154+ " Content-Type" : " application/json" ,
155+ Authorization: ` Bearer ${ accessToken} ` ,
156+ },
157+ body: JSON .stringify ({ ticker, qty }),
158+ });
159+ return ` Purchased ${ qty} shares of ${ ticker} ` ;
160+ })
161+ );
162+ ` ` `
163+ </Accordion>
164+ <Accordion title="Using Authorization for RAG">
165+ Auth0AI can leverage OpenFGA to authorize RAG applications. The FGARetriever can be used to filter documents based on access control checks defined in Okta FGA. This retriever performs batch checks on retrieved documents, returning only the ones that pass the specified access criteria.
166+
167+ Create a Retriever instance using the ` FGARetriever .create ` method.
168+
169+ ` ` ` javascript lines focus= {1 ,14 - 20 ,25 - 27 }
170+ import { FGARetriever } from " @auth0/ai-genkit/RAG" ;
171+ import { MemoryStore , RetrievalChain } from " ./helpers/memory-store" ;
172+ import { readDocuments } from " ./helpers/read-documents" ;
173+
174+ async function main () {
175+ // UserID
176+ const user = " user1" ;
177+ const documents = await readDocuments ();
178+ // 1. Call helper function to load LangChain MemoryStore
179+ const vectorStore = await MemoryStore .fromDocuments (documents);
180+ // 2. Call helper function to create a LangChain retrieval chain.
181+ const retrievalChain = await RetrievalChain .create ({
182+ // 3. Decorate the retriever with the FGARetriever to check permissions.
183+ retriever: FGARetriever .create ({
184+ retriever: vectorStore .asRetriever (),
185+ buildQuery : (doc ) => ({
186+ user: ` user:${ user} ` ,
187+ object: ` doc:${ doc .metadata .id } ` ,
188+ relation: " viewer" ,
189+ }),
190+ }),
191+ });
192+
193+ // 4. Execute the query
194+ const { answer } = await retrievalChain .query ({
195+ query: " Show me forecast for ZEKO?" ,
196+ });
197+
198+ console .log (answer);
199+ }
200+
201+ main ().catch (console .error );
202+ ` ` `
203+ </Accordion>
204+ </AccordionGroup>
0 commit comments