Create a fact-sharing AI agent
Squid lets you create unique user experiences using Squid AI. Follow along to create an AI agent that answers questions about squids!
What you'll build
- A custom AI agent
- A React frontend application in which to run the Squid AI Agent
What you'll learn
- How to create a Squid AI agent
- How to add a context to your AI agent
- How to incorporate your Squid AI agent into a frontend
What you'll need
- Node.js and NPM.
Environment setup
- In the Squid Console, switch to the
dev
environment.
- Download the ai-tutorial-squid-facts 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-squid-facts --template ai-tutorial-squid-facts --appId YOUR_SQUID_APP_ID --apiKey YOUR_SQUID_API_KEY --environmentId dev --squidDeveloperId YOUR_SQUID_DEVELOPER_ID --region YOUR_REGION
- Open the project in the IDE of your choice.
- Start the app locally by runnning 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
In the Squid Console, select the AI Agents tab.
Click the + next to Agents to create a new AI agent. Name the agent
squid-facts
. Toggle on Set agent to public so the agent can be accessed by anyone on the frontend. To restrict access to your AI agent, keep the agent private and set up a security service.See the documentation on securing your AI agent for more information.
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.
Select GPT-4.0 from the Model name dropdown menu.
Click Add. You have now created a Squid AI agent!
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.
- 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.
Now that you have a Squid project with an AI agent, you're ready to add functionality to an app!
Deploy the backend
Back in the Squid Console, scroll to the top and switch back to the
prod
environment by clicking on thedev
rectangle at the top of the page and selectingprod
from the dropdown.To deploy your backend, scroll back down to the Backend project section and click the Deploy backend button and copy the command shown.
Run the copied terminal command in your
backend
folder. The command format is as follows:
squid deploy --apiKey YOUR_PROD_API_KEY --environmentId prod
Configure the frontend
The following steps add configuration parameters to connect the application to Squid.
- Open a new terminal window and navigate to the project's frontend. You should now have two open terminal windows: one for the app's backend and one for the frontend.
cd frontend
- Install the required dependencies:
npm install
- Run the following command to create a
.env.local
file with the Squid environment configuration needed to initialize Squid:
npm run setup-env
- In the newly-created
.env.local
file, change the value ofVITE_SQUID_ENVIRONMENT_ID
toprod
.
Add frontend code
- In the frontend, open the
squid-facts-ai.tsx
component, which is located in thecomponents
folder. The folder holds a component that's pretty empty right now:
function SquidFactsAI() {
return <></>;
}
export default SquidFactsAI;
- Add the following import statement:
import { useAiChatbot } from '@squidcloud/react';
- In the
SquidFactsAI()
function, add the following constants:
const [question, setQuestion] = useState('');
const { history, chat, complete } = useAiChatbot(
'ai_agents',
'squid-facts'
);
The variables question
and setQuestion
use a standard useState
hook to manage the state of a question the user asks.
The useAIChatbot
hook wraps the AI agent. It takes the AI agent ID and Profile ID as parameters, and returns several results, including chat
, data
, and complete
.
To read more about useAIChatbot
, check out the React SDK documentation.
- Add the following functions after the constants:
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();
}
}
The askQuestion
function calls the Squid Client SDK's chat
function, which accepts a prompt for the AI agent in the form of a string.
The questionChanged
and checkKey
functions handle UI changes as the user asks a question.
- Replace the existing return with the following code:
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>
</div>
</>
);
This code passes the chat history to the Messages
component, which displays the conversation between the user and the AI agent. It also includes an input component where the user asks questions, and a button to trigger the askQuestion
function.
- Add the relevant imports for things we've added. The imports should look like this:
import { useAiChatbot } from '@squidcloud/react';
import Messages from './messages.tsx';
import { Button, TextField } from '@mui/material';
import React, { ChangeEvent, useState } from 'react';
- Open the
messages.tsx
file. Replace all of the contents of the file with the following code:
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>
{messages.map(({ id, message, type }) => (
<div key={id}>
<span key={id}>
{type}: {message}
</span>
</div>
))}
<div ref={messagesEndRef} />
</div>
);
};
export default Messages;
This code iterates through the array of ChatMessages and displays them.
Run the code
- In the
frontend
folder, run the following command to view the app:
npm run dev
To view the app, navigate to localhost:PORT where PORT is logged in the terminal. The address will likely be http://localhost:5173
.
Why is there a picture of a squid on the page, you ask? Of course you don't ask. It's an app about squids.
- Ask the AI agent some questions about squids. Here are some examples if you're stumped:
- 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 created a Squid AI integration and added it to a frontend app so users can access it. 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 create public Squid AI agents, here are some next steps you can take: Add a new agent based on your use case. For example, Squid AI can support a different persona for each part of your user engagement: sales, support, product experts and more. Implement a Squid Service that limits access to the Squid AI. Connect your database to your frontend using Squid middle tier to enable data access capabilities through the Squid Client SDK.
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.