bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 16쪽 중 5쪽
Link up the chat bot with AI endpoint to create a AI-driven Chatbot.
### Technology Stack
* JavaScript
## How it Works
Before we get into the actual development, lets first run down through the function requirement
* We want to interact with the bot using slash comments.
* The command should include a `prompt` parameter for the bot.
* The new chat should take place in a private thread.
* All chats should only be visible to the caller user.
There will be three sections we will cover in this tutorial
* Setup Discord bot from discord developer portal
* Setup your RAG bot from AI Co-Creation platform
* Create a Discord bot with Discord.js
* Test and run the Discord bot from local environment.
### **Creating Your Bot on Discord**
* Go to Discord's [Developer Portal](https://discord.com/developers/applications) and log in with your Discord account.
* Click on the "New Application" button and give it a name, which will also be the name of your bot.
* On this page, you will find the **APPLICATION ID** and **PUBLIC KEY**.
* In the left-hand side menu, click on the "Bot" tab. Here, you will find your **bot token**.
* Remember, the bot token is sensitive and should never be shared. You will use this token to log your bot in.
### AI Co-Creation Setup
To create a bot from AI Co-Creation platform
* First visit <https://beta.flock.io>
* Click on the **Create my Model**
* Follow the requirement, and fill in all the details.
### Bot Creation
#### **Step 1: Setting Up Your Project**
```bash
mkdir flock-io
cd flock-io
npm init -y
```
These lines helps us to create directory, change to the created directory and setup `package.json`
#### Step 2. Install package
```bash
npm install discordjs dotenv axios
```
This help us to install all the required package
* `discordjs`
* `dotenv`
* `axios`
#### Step 3. Build the bot
> Our tutorial is based on [DiscordJS guide](https://discordjs.guide/#before-you-begin)
Refer to our previous requirements, we want this bot to achieve:
* Allow a `chatbot` slash command
* React to slash command with prompt
Create an `index.js` file, where we will write our bots’s code. Then, set up your Client as follow:
```jsx
import { Client } from "discord.js";
const client = new Client({
intents: ["Guilds", "GuildMessages", "GuildMembers", "MessageContent"],
});
client.on("ready", () => {
console.log(`${client.user.tag} has logged in.`);
});
client.login(process.env.DISCORD_TOKEN);
```
Then we add the slash command
#### Step 4. Adding a Slash Command
To interact with the Discord API and create slash commands, you'll need to use Discord's application commands API. Here, I'll show you how to register a **`chatbot`** command and respond to it.
1. **Register the Command**: Commands can be registered globally or to a specific guild for testing. For simplicity, we'll register a global command, which might take up to an hour to propagate.
2. **Responding to Commands**: Modify your bot to listen for interactions and respond to the **`chatbot`** command.
Further explanation to command variable
* `setName` - set the name for this command
* `setDescription` - set the description for this command
* `addStringOption` - add an option that accepts string input, in our case we want to gather the prompt text from user.
```jsx
const commands = [
new SlashCommandBuilder()
.setName("chatbot")
.setDescription("Chat with the bot")
.addStringOption((option) =>
option
.setName("prompt")
.setDescription("Prompt for the chatbot")
.setRequired(true)
)
.toJSON(),
];
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
(async () => {
try {
console.log(
`Started refreshing ${commands.length} application (/) commands.`
);
const data = await rest.put(
Routes.applicationGuildCommands(process.env.APP_ID, process.env.GUILD_ID),
{ body: commands }
);
console.log(
`Successfully reloaded ${data.length} application (/) commands.`
);
} catch (error) {
console.error(error);
}
})();
```
#### Step 5. Handle the command
Within `Discordjs` , they provided a status called `interactionCreate` where we sets up an event listener that waits for an interaction to occur.
```jsx
client.on("interactionCreate", async (interaction) => {
// Code to handle the interaction goes here
});
```
Next we check few conditions
* Has user inputed command
* If user inputed command, is the command name equal to chatbot.
```jsx
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === "chatbot") {
// Proceed to handle the `chatbot` command
}
```
Recapping on the requirement
* Create a thread upon user’s command.
But in Discord there is an issue if we set the reply as ephemeral(private) the API will not be able to pick it up.
Therefore our execution flow should be: User interact → Discord sends out a helper text(Public) → use this helper text as the thread starting node → Create a private thread
#### **Step 6. Sending a Preliminary Reply**
* Inside the command check, it first sends a reply to the interaction with a message indicating that a personal thread is being prepared: **`const message = await interaction.reply({ ... });`**.
* **`fetchReply: true`** tells Discord to return the sent message as a **`Message`** object.
* **`ephemeral: false`** specifies that the message should be visible to everyone, not just the user who invoked the command. This is necessary because the bot intends to start a thread based on this message.
```jsx
const message = await interaction.reply({
content: "Preparing your personal thread...",
fetchReply: true,
ephemeral: false
});
```
#### **Step 7. Starting a Thread**
* Then we start a thread from the reply message: **`const thread = await message.startThread({ ... });`**. Adding `PrivateThread` to ensure thread is only visible to command caller.
```jsx
// Starting a thread from the bot's message
const thread = await message.startThread({
name: prompt,
autoArchiveDuration: 60,
type: ChannelType.PrivateThread,
reason: "Needed a separate thread for User Prompt",
});
```
#### **Step 8. Sending a Message to the Thread**
* After creating the thread, the bot gets ready to send a message to it. There are discussions about sending a basic greeting message directly or using a function called **`main(prompt)`** you can check the [Model API guide](/flock-products/ai-marketplace/quickstart/model-api-guide), to generate a response based on the user's prompt and then send that response to the thread.
```jsx
// Send a message to the thread using the flock-api.js file
const response = await main(prompt);
thread.send(response.answer);
// Option
await interaction.followUp({
content: `Your personal thread ${prompt} is ready!`,
ephemeral: true,
});
```
```jsx
client.on("interactionCreate", async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === "chatbot") {
// Reply with a non-ephemeral message
const message = await interaction.reply({
content: "Preparing your personal thread...",
fetchReply: true,
ephemeral: false, // This message needs to be non-ephemeral to start a thread
});
// Get the prompt from the user
const prompt = interaction.options.getString("prompt");
const user = interaction.user;
console.log(user);
// Starting a thread from the bot's message
const thread = await message.startThread({
name: prompt,
autoArchiveDuration: 60,
type: ChannelType.PrivateThread,
reason: "Needed a separate thread for User Prompt",
});
// Send a message to the thread using the flock-api.js file
const response = await main(prompt);
thread.send(response.answer);
// Option
await interaction.followUp({
content: `Your personal thread ${prompt} is ready!`,
ephemeral: true,
});
}
});
```
#### Step 9: Deployment and Testing in a Local Environment
To deploy the application locally:
1. **Update the `package.json` File**: Insert the following code snippet into your `package.json` file under the `scripts` section:
```json
"scripts": {
"start": "node index.js"
}
```
2. **Launch the Application**: Execute the command below in your terminal:
```bash
npm run start
```
3. **Verify the Output**: Upon successful execution, you should observe an output similar to the following:
```
> discord-flock@1.0.0 start
> node index.js
Started refreshing 1 application (/) commands.
Successfully reloaded 1 application (/) commands.
FLockbot_tim_test#6051 has logged in.
```
These log messages indicate that your bot is now operational and running in your local environment.
Next we need to add the bot to a server.
* You can add the bot using this URL
```
<https://discord.com/api/oauth2/authorize?client_id=><**APPLICATION ID**>&permissions=0&scope=bot%20applications.commands
```
* In your server you can type in following command
# Farcaster Frames with Model API
## **Video Tutorial**
{% embed url="<https://youtu.be/UWe_XoYEi5g>" %}
Welcome to this tutorial where we will walk you through the process of creating a Farcaster Frame and communicating with a FLock.io RAG API. This is a comprehensive guide that will give you the confidence to create, modify, and enhance your Farcaster Frames with FLock API.
What you will learn:
* How to create a Farcaster Frame
* Communicate with FLock RAG API.
## Technology Stack
* TypeScript
* Frog framework
## What is Frame?
A Frame is a tool for creating interactive, authenticated apps on Farcaster, allowing features like polls, live feeds, or galleries within Warpcast and other FC clients. Frames enhance the OpenGraph standard, transforming static embeds into interactive experiences.
## What is Frog framework?
Frog is a framework built on top of Hono for building Farcaster Frames.
The documentation: [Getting started](https://frog.fm/getting-started)
## How it Works
### Setup
* Install Frog Framework
```jsx
npm install frog hono
yarn add frog hono
```
* Create a Bot from the AI Co-Creation platform, where you can follow the guide.
* Install the API related package.
```jsx
# init frog framework
npm init frog
# install relavent packages
npm install axios dotenv @types/node
```
<figure><img src="https://742781353-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1RpcbvTSHzzPwOSUvgKU%2Fuploads%2FcNnjUdKoQtczJHMB1kvB%2FScreenshot_2024-05-09_at_10.04.50_AM.png?alt=media&token=75994ded-b5d6-4366-aa73-003327d6488a" alt=""><figcaption><p>Frog init</p></figcaption></figure>
* We will be using the `default` template, feel free to export other ones in the future.
### File structure
```jsx
📦flock-far-frog
┣ 📂public
┃ ┗ 📜icon.png
┣ 📂src
┃ ┣ 📂api
┃ ┃ ┗ 📜flock-api.ts
┃ ┗ 📜index.tsx
┣ 📜.env
┣ 📜.gitignore
┣ 📜README.md
┣ 📜package-lock.json
┣ 📜package.json
┗ 📜tsconfig.json
```
* Pages will stay in our router
* FLock API will stay in the utils
### Logic flow
We will have one page
* Default page - react on user’s input
This is a very simple and general approach of how we can use frame with FLock Chat Bot.
### API
Now create a folder under `src` called `api` within the `utils` folder create a file called `flock-api.ts` this is the place where your api will sit. And here is the code you can use directly.
```jsx
import axios from "axios";
import * as dotenv from "dotenv";
// Load environment variables from .env file
dotenv.config(); // Make sure the path is correct
async function chatFLockBot(prompt: string, modelId: string) {
console.log("Prompt:", prompt);
try {
// Construct the request payload
const payload = {
question: prompt,
chat_history: [],
knowledge_source_id: modelId, // replace with your model id
};
// Set the headers
const headers = {
"x-api-key": process.env.FLOCK_BOT_API_KEY, // Ensure API key is set in .env
};
// Send POST request using axios
const response = await axios.post(
`${process.env.FLOCK_BOT_ENDPOINT}/chat/conversational_rag_chat`,
payload,
{
headers,
}
);
// Output the response data
console.log(response.data);
return response.data;
} catch (error) {
console.error("Error:", error);
}
}
export default chatFLockBot;
```
Next create a `.env` file in the root directory of the project, and add following
```
FLOCK_BOT_API_KEY= "<your api key>"
FLOCK_BOT_ENDPOINT="<endpoint>"
FLOCK_BOT_ID="<your bot id>"
```
### Useful tools for OG image
> I personally think that the Vercel OG image playground is a convenient tool to quickly check up on your OG image. So, do utilise it!
[Vercel OG Image Playground](https://og-playground.vercel.app/)
### Page Structure
```jsx
app.frame('/', (c) => {
const { buttonValue, inputText, status } = c
const fruit = inputText || buttonValue
return c.res({
image: (
),
intents: [
],
})
})
```
Before diving in, let's first understand the structure of a ‘frame’. A frame consists of two components: the image and the intents.
* The **image** is where your visuals are displayed
* The **intents** handle interactions, including text input, button reactions, and the new transaction operations.
#### **Image**
```jsx
image: (
<div
style={{
alignItems: 'center',
background: 'black',
backgroundSize: '100% 100%',
display: 'flex',
flexDirection: 'column',
flexWrap: 'nowrap',
height: '100%',
justifyContent: 'center',
textAlign: 'center',
width: '100%',
}}
>
<div
style={{
color: 'white',
fontSize: 24,
fontStyle: 'normal',
letterSpacing: '-0.025em',
lineHeight: 1.4,
marginTop: 30,
padding: '0 120px',
whiteSpace: 'pre-wrap',
}}
>
{status === 'response' && `Your question is: ${prompt}`}
</div>
<div
style={{
color: 'white',
fontSize: status === 'response' ? 16 : 60,
fontStyle: 'normal',
letterSpacing: '-0.025em',
lineHeight: 1.4,
marginTop: 30,
padding: '0 120px',
whiteSpace: 'pre-wrap',
}}
>
{status === 'response' ? response.answer : "Lets chat about FLock!"}
</div>
</div>
)
```
Here we use status condition to show the content, if status is response, we will show the question and answer. Otherwise, the user will only see “Lets chat about FLock”
#### **Intent**
```jsx
intents: [
<TextInput placeholder="Enter Prompt about FLock" />,
<Button value={process.env.FLOCK_BOT_ID}>Lets Chat!</Button>,
status === 'response' && <Button.Reset>Reset</Button.Reset>,
],
```
Here we have created three intents
* `TextInput` - for questions to be asked to the bot
* `Button` - for the interaction
* `Button` - for reset after receiving the response
#### Main logic flow
```tsx
import chatFLockBot from './api/flock-api'
app.frame('/', async (c) => {
const { buttonValue, inputText, status } = c
const prompt = inputText
const modelId = buttonValue
let response;
if (prompt == undefined || modelId == undefined) {
response = "Detail not satisfied, please insert prompt";
} else {
try {
response = await chatFLockBot(prompt, modelId);
} catch (e) {
response = "There is somthing wrong with the process, please try again"
}
}
return c.res({
image: (
...
),
intents: [
...
],
})
})
```
In this section, we establish the logic to respond to both user input and an API call.
Initially, we extract values from the object **`c`** (representing context), which provides the current state or frame:
* **`buttonValue`** - the value assigned to a button,
* **`inputText`** - the text entered by the user,
* **`status`** - the status of the context within its lifecycle.
Next, we initialise two constants, **`prompt`** and **`modelId`**, using the extracted **`inputText`** and **`buttonValue`** respectively. This sets up the parameters we need for the subsequent API call.
We then employ an **`if`** statement to check whether either **`prompt`** or **`modelId`** is undefined. This validation is crucial as it ensures that we have the necessary data before proceeding.
Finally, we use a **`try-catch`** structure to manage the asynchronous function **`chatFlockBot`**. This function is called with **`prompt`** and **`modelId`** as arguments. The **`try`** block executes the function, and should any errors occur during the API call, the **`catch`** block captures these exceptions and sets an error message.
## Run the test
Now you have completed the setup of the frame. Let’s test it in the local environment.
```
# run this command in your terminal
npm run dev
# you will see followings
> dev
> frog dev
(!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling.
[running] frog@v0.9.0
➜ Local: http://localhost:5173/
➜ Inspect: http://localhost:5173/dev
➜ Network: use --host to expose
```
Go to `http://localhost:5137/dev`
You will see the following page
<figure><img src="https://742781353-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1RpcbvTSHzzPwOSUvgKU%2Fuploads%2FPS4yPGmTmYWn6sgc48Wy%2Ffrog_test.png?alt=media&token=f854025d-8d0e-4357-a989-b65c29db4302" alt=""><figcaption></figcaption></figure>
1. The history of access
2. URL tab - similar to web browser URL tab
3. Metadata of current frame
4. Live frame interact
5. Request/Context/Metadata information
6. Request/Context/Metadata information
Now you can start typing the questions and chat with the frame!
## Deploy your frame
I recommend deploying your project using [Vercel](https://vercel.com/). You can easily deploy it by connecting your GitHub account and pushing your project to a repository.
Next, all you need to do is copy your deployed link and post it in any Farcaster Client.
Please tag us when you post the cast! “/flock-io”
**Lastly here is the GitHub Repository!**
<https://github.com/FLock-io/FLock-AI-Demo/tree/main/FLOCK-RAG-FRAME-React>
> *Reach out to us by Website:* [*https://flock.io/*](https://flock.io/) \
> *Twitter:* [*https://twitter.com/flock\_io*](https://twitter.com/flock_io) \
> *Telegram:* [*https://t.me/flock\_io\_community*](https://t.me/flock_io_community) \
> *Discord:* [*https://discord.gg/ay8MnJCg2W*](https://discord.gg/ay8MnJCg2W) \
> *Farcaster:* [*https://warpcast.com/\~/channel/flock-io*](https://warpcast.com/~/channel/flock-io)
# Participants
This section describes different participants and the roles they play in AI Marketplace.
<figure><img src="https://742781353-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1RpcbvTSHzzPwOSUvgKU%2Fuploads%2FZDEmWkxU18JRzVM69RSB%2FScreenshot%202024-01-18%20at%2010.24.03%20PM.png?alt=media&token=684291a7-856f-4a79-a573-2959707f1285" alt=""><figcaption><p>Participants & Workflow in AI Marketplace. </p></figcaption></figure>
## Model Proposer
* Conceptualise and introduce new models
* Delineate clear use cases and pinpoint relevant data sources that underpin development and efficacy
## Data Contributor
* Offer valuable datasets that help the model to learn and adapt
## End User
* Offer critical user feedback and insights that drive improvment of models
## Developer
* Act as the bridge between the model's capabilities and practical applications
* Leverage the API endpoints to integrate the model into diverse software applications, thereby expanding its functional reach and accessibility.
At the core of this ecosystem lies a sophisticated chatbot, driven by state-of-the-art LLMs. 
The chatbot is not only empowered by the computational prowess of LLMs but is also equipped with advanced search and retrieval functionalities. This enables it to extract and leverage information from a dynamically evolving database—a repository enriched by the continuous contributions of Data Contributors. 
This dual capability ensures that the chatbot remains both intelligent and informed, able to deliver nuanced and contextually relevant responses.
# Deep-dive
# Function breakdown
This system streamlines the process of creating, deploying, and utilising customised AI models.
### Function breakdown
AI Marketplace operates through various phases, incorporating model proposals and live chatting. 
**Core components프로젝트로 돌아가기