Skip to main content

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

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

switch environment

  1. 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.
  2. 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
  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, select the AI Agents tab.

  2. 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.

  3. 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.
  1. Select GPT-4.0 from the Model name dropdown menu.

  2. Click Add. You have now created a Squid AI agent!

  3. 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.

Now that you have a Squid project with an AI agent, you're ready to add functionality to an app!

Deploy the backend

  1. Back in the Squid Console, scroll to the top and switch back to the prod environment by clicking on the dev rectangle at the top of the page and selecting prod from the dropdown.

  2. To deploy your backend, scroll back down to the Backend project section and click the Deploy backend button and copy the command shown.

  3. 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.

  1. 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
  1. Install the required dependencies:
npm install
  1. Run the following command to create a .env.local file with the Squid environment configuration needed to initialize Squid:
npm run setup-env
  1. In the newly-created .env.local file, change the value of VITE_SQUID_ENVIRONMENT_ID to prod.

Add frontend code

  1. In the frontend, open the squid-facts-ai.tsx component, which is located in the components folder. The folder holds a component that's pretty empty right now:
components/squid-facts-ai.tsx
function SquidFactsAI() {
return <></>;
}

export default SquidFactsAI;
  1. Add the following import statement:
components/squid-facts-ai.tsx
import { useAiChatbot } from '@squidcloud/react';
  1. In the SquidFactsAI() function, add the following constants:
components/squid-facts-ai.tsx
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.

  1. Add the following functions after the constants:
components/squid-facts-ai.tsx
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.

  1. Replace the existing return with the following code:
components/squid-facts-ai.tsx
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.

  1. Add the relevant imports for things we've added. The imports should look like this:
components/squid-facts-ai.tsx
import { useAiChatbot } from '@squidcloud/react';
import Messages from './messages.tsx';
import { Button, TextField } from '@mui/material';
import React, { ChangeEvent, useState } from 'react';
  1. Open the messages.tsx file. Replace all of the contents of the file with the following code:
components/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>
{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

  1. 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.

  1. 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.