Skip to main content

Add security to a Squid AI Agent

Secure a Squid AI agent using Auth0 authentication and backend authorization.

With Squid AI, you can create rich AI agent experiences built on the context that you provide. You can also secure your AI agents in just a few lines of code using Squid's robust backend functionality. Rules can be as basic or as customized as you need to fit your unique use case. By using the @secureAiAgent decorator, you can turn a TypeScript function into an endlessly customizable AI agent security solution. And since security functions are written in TypeScript, writing, interpreting, and updating security rules is as straightforward as updating any other function.

This tutorial goes thoroughly into the "what" and "why" of the steps to take to create and secure an AI agent so that by the end, you can feel confident in your understanding of Squid AI Agents.

What you'll build

  • A custom AI agent configured with authentication and authorization to limit chat access
  • A React frontend application in which to run the Squid AI Agent

What you'll learn

  • How to create a Squid AI agent
  • How context to your AI agent
  • How to incorporate your Squid AI agent into a frontend
  • How to create a Squid Service that adds security to your AI agent

What you'll need

Environment setup

  1. In the Squid Console, switch to the dev environment.

switch environment

  1. Download the ai-tutorial-secure-chat code sample using the following command. Replace the placeholders with the values from your Squid application as shown in the console.
  2. npx @squidcloud/cli init-sample ai-tutorial-secure-chat --template ai-tutorial-secure-chat --appId YOUR_SQUID_APP_ID --apiKey YOUR_SQUID_API_KEY --environmentId dev --squidDeveloperId YOUR_SQUID_DEVELOPER_ID --region YOUR_REGION
  1. Open the project in the IDE of your choice.
  2. Start the app locally by runnning the following command in the project folder:
npm run start
  1. To view the app, navigate to localhost:PORT where PORT is logged in the terminal. The address will likely be http://localhost:5173.

Add the Squid AI Agent

  1. In the Squid Console, ensure you are in the dev environment. If you are in the prod environment, click the prod button at the top of the window and select dev from the dropdown.
  2. Select the AI Agents tab.
  3. Click Add agent to create a new agent. Name the agent squid-facts-chatbot. Toggle Set agent to public to off.
  4. Select GPT-4.0 from the Model name dropdown menu.
  5. Click Add. You have now create a new AI agent!

Note: You can have multiple agents with different purposes. Notice agents have two components: Instructions and Context.

  • Instructions are the rule set for how the AI agent responds and answers questions. They can be about tone or purpose. For example, "You are a pirate. Only answer questions like a pirate would", or "You are a helpful customer support expert that understands camping products and can answer questions in detail”.
  • Context is the body of knowledge the agent uses when responding to questions. Adding context allows the agent to provide relevant answers on specific topics that aren't part of the underlying AI model. Context can be text, URL, or file upload.
  1. Click the + next to Instructions to add a new instruction. Enter the following text as the instruction, and then press Add instruction:
You're a friendly AI who shares random facts about squids and answers user questions about squids.

Use only language that is appropriate for children.

Important: Only answer based on the provided context.
  1. Click the + next to Context to add context. Name the context Squid Wikipedia. Change the Context type to URL, and then enter the following URL:
https://en.wikipedia.org/wiki/Squid

Yes, this is just a link to the Wikipedia page on squids, but it's for demonstration purposes. ChatGPT likely already knows this information. In your own applications, you will provide context that is relevant to your use case. The URLs or text you provide most often come from your own sources on which ChatGPT was not trained.

Add the Auth0 integration

  1. If you haven't yet made an Auth0 API, set up an Auth0 account and create a single-page application configured to use React and an audience using an Auth0 API. Use 'squid-ai' as the API audience. When adding the callback and logout URLs, use http://localhost:5173.
  2. In the Squid Console in the dev environment, select the Integrations tab.
  3. Click the Available integrations tab to view all integrations.
  4. Scroll to the Auth0 integration and click Add integration.
  5. Enter auth0 for the Integration ID.
  6. Enter the client ID and audience for your Auth0 app. These can be found in the Auth0 console.
  7. Click Add integration.

Add Auth0 credentials

  1. Navigate to squid-facts/src/main.tsx. Notice there is an Auth0Provider component, that requires configuration:
src/main.tsx
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<Auth0Provider
domain="AUTH0_DOMAIN"
clientId="AUTH0_CLIENT_ID"
authorizationParams={{
redirect_uri: window.location.origin,
audience: 'squid-ai',
}}
>
<SquidContextProvider
options={{
appId: import.meta.env.VITE_SQUID_APP_ID,
region: import.meta.env.VITE_SQUID_REGION,
environmentId: import.meta.env.VITE_SQUID_ENVIRONMENT_ID,
squidDeveloperId: import.meta.env.VITE_SQUID_DEVELOPER_ID,
}}
>
<App />
</SquidContextProvider>
</Auth0Provider>
);
  1. Replace the placeholders in the Auth0Provider component with the domain and client ID from your Auth0 application.

  2. Open the App.tsx file and add the following imports:

src/App.tsx
import { useAuth0 } from '@auth0/auth0-react';
import { useSquid } from '@squidcloud/react';

This imports the Auth0 and Squid React libraries.

  1. Add the following code to the App function:
// Get Auth0 authentication state.
const { user, isLoading, getAccessTokenSilently } = useAuth0();
const { setAuthProvider } = useSquid();

useEffect(() => {
setAuthProvider({
integrationId: 'auth0_INTEGRATION_ID',
getToken: () => user && getAccessTokenSilently(),
});
if (isLoading) return;
if (!user) {
setLoginMessage('You are logged out!');
setToastOpen(true);
} else {
setLoginMessage('You are logged in!');
setToastOpen(true);
}
}, [user, isLoading, getAccessTokenSilently, setAuthProvider]);

if (isLoading) {
return <span>Loading...</span>;
}

This code sets the auth provider to Squid, passing the Access token from Auth0. This sends the token to the Squid backend for configuring authorization.

  1. In the return statement, change the value of the isAuthenticated prop from false to !!user:
src/App.tsx
<NavBar isAuthenticated={!!user} />

This informs the NavBar of which button to display: a login button or a logout button.

Checkpoint

At this point, you have added all the code that will be in App.tsx. Here's a look at the final file:

src/App.tsx
import SquidFactsAI from './components/squid-facts-ai';
import './App.css';
import NavBar from './components/nav-bar';
import { useEffect, useState } from 'react';
import { useAuth0 } from '@auth0/auth0-react';
import { useSquid } from '@squidcloud/react';
import { Snackbar, Alert } from '@mui/material';

function App() {
// Set state of toast message
const [toastOpen, setToastOpen] = useState(false);
const [loginMessage, setLoginMessage] = useState('');

// Get Auth0 authentication state
const { user, isLoading, getAccessTokenSilently } = useAuth0();
const { setAuthProvider } = useSquid();

useEffect(() => {
setAuthProvider({
integrationId: 'auth0_INTEGRATION_ID',
getToken: () => user && getAccessTokenSilently();
});
if (isLoading) return;
if (!user) {
setLoginMessage('You are logged out!');
setToastOpen(true);
} else {
setLoginMessage('You are logged in!');
setToastOpen(true);
}
}, [user, isLoading, getAccessTokenSilently, setAuthProvider]);


if (isLoading) {
return <span>Loading...</span>;
}

const handleToClose = () => {
setToastOpen(false);
};

return (
<>
<NavBar isAuthenticated={!!user} />
<img src="https://upload.wikimedia.org/wikipedia/commons/e/e1/Sepioteuthis_sepioidea_%28Caribbean_Reef_Squid%29.jpg" />
<SquidFactsAI />
<Snackbar
open={toastOpen}
onClose={handleToClose}
autoHideDuration={6000}
>
<Alert severity="success">{loginMessage}</Alert>
</Snackbar>
</>
);
}

export default App;

Add Squid AI Agent functionality

  1. In the src/components folder, open the squid-facts-ai.tsx file. Scroll down to the return statement and notice that there is a TextField component and a Button component. This is where the user asks questions to the AI agent. There is also an empty div component where the chat history will be displayed. Add the following imports:
src/components/squid-facts-ai.tsx
import Messages from './messages';
import { useAiChatbot } from '@squidcloud/react';

The useAiChatbot function lets the client use Squid AI to chat.

  1. Add the following to the SquidFactsAI function:
src/components/squid-facts-ai.tsx
const { history, chat, complete, error } = useAiChatbot(
'ai_agents',
'squid-facts-chatbot'
);
  1. Right now the askQuestion function just sets the value of question to an empty string, but it doesn't actually ask the question. Add thechat function to askQuestion to ask questions to the AI agent:
src/components/squid-facts-ai.tsx
function askQuestion() {
chat(question);
setQuestion('');
}
  1. Add the Messages component to the empty div:
src/components/squid-facts-ai.tsx
<div className="scrolling">
<Messages messages={history} />
</div>

This passes the conversation history to a prop in the Messages component, which then displays it.

  1. Update the Button so that it is disabled until a chat response is complete, and then add a div that displays the error message if an error occurs when using the AI agent:
src/components/squid-facts-ai.tsx
...
return (
...

<Button variant="contained" disabled={!complete} onClick={askQuestion}>
Ask question
</Button>
{ error && <div>{error.toString()}</div>}

...
)

Checkpoint

You have now completed the code for this component. Here is all the code for the squid-facts-ai.tsx file:

src/components/squid-facts-ai.tsx
import { ChangeEvent, useState } from 'react';
import { TextField, Button } from '@mui/material';
import Messages from './messages';
import { useAiChatbot } from '@squidcloud/react';

const SquidFactsAI = () => {
const [question, setQuestion] = useState('');
const { history, chat, complete, error } = useAiChatbot(
'ai_agents',
'squid-facts-chatbot'
);

function askQuestion() {
chat(question);
setQuestion('');
}

function questionChanged(e: ChangeEvent) {
setQuestion((e.target as HTMLInputElement).value);
}

function checkKey(ele: React.KeyboardEvent<HTMLDivElement>) {
if (ele.key === 'Enter') {
askQuestion();
}
}

return (
<>
<div className="scrolling">
<Messages messages={history} />
</div>
<div className="question">
<TextField
fullWidth
id="outlined-basic"
label="Enter your question"
variant="outlined"
onChange={questionChanged}
onKeyDown={(event) => checkKey(event)}
value={question}
/>
<Button variant="contained" disabled={!complete} onClick={askQuestion}>
Ask question
</Button>
{error && <div>{error.toString()}</div>}
</div>
</>
);
};

export default SquidFactsAI;

Set up the Messages component

Open the messages.tsx file and replace the contents of the file with the following code:

src/components/squid-facts-ai.tsx
import { useEffect, useRef } from 'react';
import { ChatMessage } from '@squidcloud/react';

interface ChatHistoryProps {
messages: ChatMessage[];
}

const Messages: React.FC<ChatHistoryProps> = ({ messages }) => {
const messagesEndRef = useRef<HTMLDivElement>(null);

const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};

useEffect(() => {
scrollToBottom();
}, [messages]);

return (
<div className="messages">
{messages.map(({ id, message, type }) => (
<div key={id}>
<span key={id}>
<b>{type}:</b> {message}
</span>
</div>
))}
<div ref={messagesEndRef} />
</div>
);
};

export default Messages;

This code displays the chat messages. The type of a ChatMessage is the author of the message. It is either the user or AI.

Secure the AI agent on the Squid backend

Navigate to the backend folder. This contains any Squid backend logic. Open the src/service/ai-security-service.ts file. Add the following code to the file:

backend/src/service/ai-security-service.ts
import { secureAiAgent, SquidService } from '@squidcloud/backend';

export class AiSecurityService extends SquidService {
@secureAiAgent('chat', 'squid-facts-chatbot')
allowChat(): boolean {
// or add custom authorization here
return this.isAuthenticated();
}
}

This creates a Squid Service that allows the client to chat with the AI agent if they are authenticated. The setAuthProvider function we called on the frontend informed the backend of the user's authentication status. The @secureAiChatbot decorator is used to set security rules. While this example only verifies that the user is authenticated, you can add customized authorization rules. For example, you could query a database to check if the user is part of a permitted list of users.

Check out the documentation to learn more about security and authentication.

Try out the app

  1. To run the backend locally, run the following command in the backend directory:
backend
squid start
  1. In a separate terminal window, run the following command from the frontend directory:
frontend
npm run dev

You now have two terminal windows: one running the backend and the other running the frontend.

  1. To view the app, navigate to localhost:PORT where PORT is logged in the terminal. The address will likely be http://localhost:5173.

  2. Ask a question about squids to the AI agent. Notice you do not get a response. Instead, an unauthorized message appears.

  3. Log into the app and ask a question again. Now the AI agent will chat with you!

Feel free to keep asking questions and to see what happens when you log out and in. With the Squid Service on the backend handling authorization, you can rest easy knowing only authenticated users will have access to the service.

Here are some questions to try:

  • Do squids have arms or tentacles?
  • What should I do if I encounter a squid?
  • What's your favorite fact about squids?
  • Tell me about the Onykia ingens.

Share your favorite squid questions and answers with the Squid Squad on Discord or X.

Conclusion

Congratulations! You just added a customized AI agent to an app, and then secured it using the Squid Backend SDK. Feel free to keep asking questions to see just how much this AI agent knows about squids!

Next steps

Now that you know how to limit AI agent access to authenticated users, here are some other things to try:

  • Add a new AI agent based on your use case. For example, Squid AI agents can support a different persona for each part of your user engagement: sales, support, product experts and more.
  • Connect your database to your frontend using Squid middle tier to enable data access capabilities through the Squid Client SDK.
  • Think of other properties on which you might secure your Squid AI Agent. For example, you might want users to sign a consent form first. You can log consent status in your database, and then verify on the backend that the user is logged in and has signed the consent form.

Clean up

To prevent further billing, delete the Squid app in the Squid Console by selecting the Overview tab for the app and scrolling down to Delete Application.