Squid AI Agent にセキュリティを追加する
Auth0 認証とバックエンドの承認を使用して Squid AI agent のセキュリティを確保する。
Squid AI を使用すると、提供するユニークなコンテキストとツールに基づいたリッチな AI agent エクスペリエンスを作成できます。わずか数行のコードで、Squid's robust backend functionality を使用して AI agent のセキュリティを実現することができます。
ルールは、ユースケースに合わせて基本的なものからカスタマイズされたものまで自由に設定できます。@secureAiAgent
デコレーターを使用することで、TypeScript の関数を無限にカスタマイズ可能な AI agent セキュリティソリューションへと変換することが可能です。そして、セキュリティ関数は TypeScript で記述されているため、セキュリティルールの作成、解釈、更新は他の関数を更新するのと同じくらい直感的に行えます。
このチュートリアルでは、AI agent を作成してセキュリティを確保するための「何を」および「なぜ」について詳しく解説します。最後まで進めることで、Squid AI Agents の仕組みに自信が持てるようになるでしょう。
作成するもの
- 認証と承認を設定してチャットアクセスを制限するカスタム AI agent
- Squid AI Agent を実行するための React フロントエンドアプリケーション
学べること
- Squid AI agent の作成方法
- AI agent にコンテキストを提供する方法
- フロントエンドに Squid AI agent を組み込む方法
- AI agent にセキュリティを追加する Squid Service の作成方法
必要なもの
- The Squid CLI
- Squid Console のアカウント
- React 用に設定された single-page application の Auth0 アカウント を持つ Auth0 アカウント
Environment setup
- In the Squid Console, switch to the
dev
environment.
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.
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
You can find your environment variables under: 'Application' -> 'Show env vars' as seen below:
- Open the project in the IDE of your choice.
- Start the app locally by running the following command in the project folder:
npm run start
- 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
- Squid Console で Agent Studio タブを選択します
- Create New Agent をクリックしてエージェントを追加します。以下の詳細を入力し、Create をクリックします:
- Agent ID:
squid-facts-chatbot
- Description:
This is an agent for Squid AI's secure chat tutorial
.
- AI agent の Overview ページで、Instructions セクションに移動します。以下の指示を追加してください:
You're a friendly AI who shares random facts about squids and answers user questions about squids.
Important: Only answer based on the provided context.
- agent のナレッジベースに squid に関する情報を追加するには、Wikipedia article on squids に移動し、ページを HTML または PDF ファイルとして保存してください。次に、Agent Overview ページで Add Abilities をクリックします。Knowledge Base の下にある File ability を選択し、ファイルをアップロードしてください。この ability により、エージェントは質問に回答する際、コンテキストを利用することができます。
LLM models は既にこの squid 情報を知っている可能性があります。ご自身のアプリケーションでは、ユースケースに関連するコンテキストを提供してください。
Add the Auth0 connector
-
まだ Auth0 アプリケーションを作成していない場合は、まず Auth0 アカウント を設定してください。
次に、Auth0 Dashboard に移動し、React 用に設定された single-page application を作成します。アプリケーションの設定内で、Allowed Callback URLs、Allowed Logout URLs、Allowed Web Origins に
http://localhost:5173
を追加してください。最後に、Applications サイドバー項目内にある Auth0 API を、API audience として
squid-ai
を使用して作成してください。 -
Squid Console の
dev
環境で、Connectors タブを選択します。 -
Available connectors タブをクリックし、Auth0 connector を追加します
- Connector ID:
auth0
- Auth0 Domain: この値は、Auth0 アプリケーションの設定で確認できます
- Audience:
squid-ai
、または Auth0 API 作成時に入力した値
- Add connector をクリックします。
Add Auth0 credentials
squid-facts/frontend/src/main.tsx
に移動します。Auth0Provider
コンポーネントがあり、設定が必要なことに注意してください。Auth0Provider
コンポーネント内のプレースホルダーを、Auth0 アプリケーションから取得した domain と client ID に置き換えてください:
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>
);
App.tsx
ファイルを開き、以下のインポートを追加してください:
import { useAuth0 } from '@auth0/auth0-react';
import { useSquid } from '@squidcloud/react';
import { useEffect, useState } from 'react';
これにより、Auth0 と Squid React のライブラリ、および標準の React 機能がインポートされます。
App
関数に次のコードを追加してください:
// Get Auth0 authentication state.
const { user, isLoading, getAccessTokenSilently } = useAuth0();
const { setAuthProvider } = useSquid();
useEffect(() => {
setAuthProvider({
integrationId: 'auth0',
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>;
}
このコードは、Squid アプリケーションにおいて Auth0 からの Access token をバックエンドに渡すために認証プロバイダーを設定します。
- return 文内で、
isAuthenticated
プロパティの値をfalse
から!!user
に変更してください:
<NavBar isAuthenticated={!!user} />
これにより、NavBar がログインボタンまたはログアウトボタンのどちらを表示するかを判断します。
Checkpoint
この時点で、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',
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
src/components
フォルダ内のsquid-facts-ai.tsx
ファイルを開きます。return 文にスクロールして、TextField
コンポーネントとButton
コンポーネントがあることに気づいてください。ここがユーザーが AI agent に質問を送る場所です。また、チャット履歴が表示される空のdiv
コンポーネントもあります。以下のインポートを追加してください:
import Messages from './messages';
import { useAiChatbot } from '@squidcloud/react';
useAiChatbot
関数により、クライアントは Squid AI を使用してチャットできます。
SquidFactsAI
関数内に、次のコードを追加してください:
const { history, chat, complete, error } = useAiChatbot(
'ai_agents',
'squid-facts-chatbot'
);
- 現在、
askQuestion
関数は単にquestion
の値を空文字にするだけですが、実際には質問を送信しません。askQuestion
にchat
関数を追加して、AI agent に質問できるようにしてください:
function askQuestion() {
chat(question);
setQuestion('');
}
- 空の
div
にMessages
コンポーネントを追加してください:
<div className="scrolling">
<Messages messages={history} />
</div>
これにより、会話履歴が Messages
コンポーネントの prop として渡され、表示されます。
Button
を更新して、チャットの応答が完了するまで無効にし、エラーが発生した場合はそのエラーメッセージを表示するdiv
を追加してください:
...
return (
...
<Button variant="contained" disabled={!complete} onClick={askQuestion}>
Ask question
</Button>
{ error && <div>{error.toString()}</div>}
...
)
Checkpoint
これで、このコンポーネントのコードが完成しました。以下は 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
messages.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;
このコードはチャットメッセージを表示します。ChatMessage
の type
はメッセージの送信者で、user
または AI
のどちらかです。
Secure the AI agent on the Squid backend
backend フォルダに移動します。ここには Squid のバックエンドロジックが含まれています。src/service/ai-security-service.ts
ファイルを開き、以下のコードを追加してください:
import { secureAiAgent, SquidService } from '@squidcloud/backend';
export class AiSecurityService extends SquidService {
@secureAiAgent('squid-facts-chatbot')
allowChat(): boolean {
// or add custom authorization here
return this.isAuthenticated();
}
}
これにより、ユーザーが認証されている場合にのみ AI agent とのチャットを許可する Squid Service が作成されます。フロントエンドで呼び出した setAuthProvider
関数は、バックエンド側にユーザーの認証状態を知らせています。@secureAiAgent
デコレーターはセキュリティルールを設定するために使用されます。この例では、ユーザーが認証されていることのみを確認していますが、カスタマイズされた承認ルールを追加することも可能です。たとえば、データベースをクエリして、ユーザーが許可されたリストに含まれているかどうかを確認することができます。
より詳しくは、security および authentication のドキュメントを参照してください。
Try out the app
- バックエンドをローカルで実行するには、
backend
ディレクトリで次のコマンドを実行してください:
squid start
- 別のターミナルウィンドウで、
frontend
ディレクトリから次のコマンドを実行してください:
npm run dev
これで、バックエンドを実行しているターミナルウィンドウと、フロントエンドを実行しているターミナルウィンドウの 2 つが立ち上がります。
-
アプリを表示するには、ターミナルにログされている PORT 番号の localhost:PORT に移動してください。アドレスはおそらく
http://localhost:5173
です。 -
AI agent に squid に関する質問をしてください。応答が得られず、代わりに未承認のメッセージが表示されます。
-
アプリにログインし、再度質問してください。これで AI agent がチャットを開始します!
ログアウトとログインを繰り返しながら、質問を続けてどのような動作をするか試してみてください。バックエンドの Squid Service が承認を処理するため、認証されたユーザーだけがサービスにアクセスできることが保証されます。
以下の質問例を試してみてください:
- 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.
お気に入りの squid に関する質問と回答を Discord や X の Squid Squad と共有してください。
Conclusion
おめでとうございます!カスタマイズされた AI agent をアプリに追加し、Squid Backend SDK を使用してそれにセキュリティを実装しました。引き続き質問をして、この AI agent が squid についてどれほどの知識を持っているか確認してみてください!
Next steps
認証されたユーザーにのみ AI agent へのアクセスを限定する方法を学んだので、次のことにも挑戦してみてください:
- ご自身のユースケースに基づいて新しい AI agent を追加する。たとえば、Squid AI agent は、セールス、サポート、プロダクトエキスパートなど、ユーザーエンゲージメントの各部分で異なるペルソナをサポートすることが可能です。
- Squid Client SDK を通じてデータアクセス機能を有効にするために、Squid middle tier を使用してデータベースをフロントエンドに接続する。
- Squid AI Agent のセキュリティを確保するための他のプロパティを考えてみてください。例えば、ユーザーが最初に同意フォームに署名する必要がある場合、同意状況をデータベースに記録し、バックエンドでユーザーがログインしており、かつ同意フォームに署名しているかを検証することができます。
Clean up
さらなる課金を防ぐために、Squid Console の対象アプリの Overview タブに移動し、下部の Delete Application を選択して Squid アプリを削除してください。