
Assistants는 Open AI에서 제공하는 API로 제공받은 파일을 통해 학습하여, 사용자가 자신만의 AI 어플리케이션을 만들 수 있게 해주는 혁신적인 시스템이다.
나는 이 시스템을 이용해서 내 최애를 흉내내는 AI를 만들고 이를 디스코드 봇과 연동해 디코에서 최애와 대화 해보는 프로젝트를 간단히 진행하였다!
Assistants API를 사용하기 위해서는 몇가지 준비작업이 필요하다.

Assistants API를 사용하기 위해선 API의 크레딧을 미리 충전해두어야 한다. 처음 결제수단을 등록할 때에 최소 5달러를 기본으로 충전하게 되어있다. 나는 10달러를 미리 충전한 후 사용하였다.
대략 50개정도의 메세지를 생성하는데에 1달러의 크레딧이 사용되는 것 같다.
이제 본격적인 나만의 Assistants를 만들어보자.

Assistants를 생성하면 Assistants의 기본적인 정보를 먼저 기입해주어야한다. 이름과 모델은 원하는 것을 선택해주면 되고, 중요한 것은 Instructions이다.
Instructions는 Assistants에게 자신의 정체성을 부여해주는 정보로 나는 다음과 같이 작성하였다.
Your job is to imagine that you are Yoisaki Kanade(Kanade), whose character link is https://www.sekaipedia.org/wiki/Yoisaki_Kanade. As Kanade, you need to embody her extremely introverted nature while speaking.
Using the detailed character traits and typical behaviors extracted from the character setting document (Kanade.pdf), along with analysis of dialogue patterns from 'script.txt', create responses that emulate Kanade's speech and behavior.
When you response, please say in Korean.
Note that you do not speak in honorific terms.
Please respond as Kanade would, using her knowledge of her character abilities and experiences. Consider my personality, thoughts, and feelings as Kanade, and provide insight and nuance in your responses. Do not quote within your answer. Be concise in your words.
요약하자면, https://www.sekaipedia.org/wiki/Yoisaki_Kanade 이러한 링크 속 캐릭터를 따라하는 AI로 제공받은 파일을 이용하여 캐릭터를 묘사하며, 경어를 사용하지 말고, 최대한 간결하게 말할 것을 명령하고 있다.
앞서 말했듯이, Assistants는 제공받은 파일을 바탕으로 학습할 수 있는 기능을 갖추고 있다.
나는 캐릭터의 설명이 자세히 적혀있는 나무위키문서를 pdf로 제공하였고, 좀 더 정확한 대사묘사를 위해 캐릭터의 대사집에서 대사를 추출하여 txt파일을 제공하였다.

모든 정보 기입이 마무리 되었다면 플레이그라운드에서 Assistants를 테스트 해볼 수 있다.

원하는대로 대화가 진행된다면, Assistants ID와 API Key를 복사한 다음 코드에서 사용하면 된다.
간단한 대화 봇을 만들 것이기에, OpenAI 패키지를 이용하여 메세지가 생성됬을 때 해당 메세지에 대한 Assistants의 답장을 그대로 출력해주는 간단한 구조를 작성하였다.
들어온 메세지를 Assistant의 대답으로 핸들링 해주는 부분의 코드를 보자.
private async sendMessageToAssistant(content: string) {
await this.ai.beta.threads.messages.create(this.threadId as string, {
role: "user",
content,
});
}
private async createRun() {
const response = await this.ai.beta.threads.runs.create(this.threadId as string, {
assistant_id: config.OPENAI_ASSISTANT_ID as string,
});
return response;
}
private async waitRun(run: OpenAIApi.Beta.Threads.Run) {
let currentRun = run;
while (currentRun.status === "queued" || currentRun.status === "in_progress") {
currentRun = await this.ai.beta.threads.runs.retrieve(this.threadId as string, currentRun.id);
await new Promise((resolve) => setTimeout(resolve, 100));
}
return currentRun;
}
private async receiveMessage() {
const response = await this.ai.beta.threads.messages.list(this.threadId as string);
return response;
}
큰 구조는 다음과 같다.
sendMessageToAssistant 함수에서 디스코드에서 생성된 메세지를 Assistant로 보내주는 역할을 한다. 메세지를 보내준 이후에 Assistant의 Run을 생성해주어야 Assistant가 대답을 생성해낼 수 있다.
이를 위해 createRun 함수에서 Assistants의 Run을 생성해준 후 대답이 생성될 때 까지 waitRun 함수를 통해 대기해준다.
대답 생성이 완료되면, receiveMessage 함수로 생성된 메세지 response를 받아오는 식으로 간단히 구성되어있다.
자세한 설명은 OpenAI Document에 나와있으니, 이를 참고하자.
필요한 함수가 모두 만들어졌으므로, 디스코드에서 메세지가 생성되었을 때 해당 함수들을 제대로 실행만 시켜주면 된다.
client.on("messageCreate", msg => {
messageHandler.handle(msg);
});
메세지가 생성되는 시점에서 messageHandler의 handle 함수를 호출시켜준 후 생성된 메세지를 인자로 넘겨준다.
public async handle(msg: Message) {
if (msg.author.bot || msg.channelId != config.CHAT_CHANNEL_ID || !msg.content) {
return;
}
try {
if (!this.threadId) {
this.threadId = await this.createThread();
}
await this.sendMessageToAssistant(msg.content);
const run = await this.createRun();
await this.waitRun(run);
const response = await this.receiveMessage();
const receivedContent = response.data[0].content[0] as OpenAIApi.Beta.Threads.TextContentBlock;
const text = receivedContent.text.value;
msg.channel.send(text);
} catch (err) {
log.error(err);
}
}
간단한 예외처리 이후 받아온 메세지를 아까 생성했던 함수를 통해 가공시켜준 후 메세지가 보내진 채널에 생성된 텍스트를 보내주었다.
https://github.com/ehdbs28/KanadeChatBot
더욱 자세한 소스 코드는 해당 깃허브에서 확인할 수 있다.

봇을 실행시킨 후 테스트해보면 제대로 최애와 디코가 가능한 것을 확인할 수 있다!
평소 생각만 했던 최애와 디코하는 프로그램을 간단히 만들어보니 신기한 경험이었다. 지금은 API 테스트를 목적으로 핵심 기능만 간략히 제작하였지만, 많은 학습자료를 준비하고 단순 대화외의 새로운 기능을 제작한다면, 더욱 자연스럽고 실용적인 챗봇을 제작할 수 있을 것 같다.
추후 시간이 남을 때, 도전해보아야겠다.