기존에 맡았던 오픈AI로 챌린지 문제 만들기는 문법 만드는 것과 로직이 같아 한 사람이 해도 될 것 같아, 역할 재분배를 받았다. 나는 오픈AI로 언어수업을 통해 받은 텍스트를 사용자의 언어로 코칭해주는 기능을 맡게 되었다.
어제 API 키 발급과 충전까지는 해놓은지라 호출 및 프롬프팅을 하면 되겠다고 생각했다.
yarn add --dev @types/openai 명령어(타입 검사를 할 수 있도록 타입 정의를 설치하는 명령어)를 입력했더니, 이런 에러가 뜸.
warning ../../../package.json: No license field
[1/4] 🔍 Resolving packages...
error Error: https://registry.yarnpkg.com/@types%2fopenai: Not found
⇒ OpenAI API 라이브러리에 대한 공식 타입 정의는 제공되지 않음.
// src/@types/openai.d.ts
declare module 'openai' {
export class Configuration {
constructor(options: { apiKey: string });
}
export interface Message {
role: string;
content: string;
}
export interface Choice {
index: number;
message: Message;
finish_reason: string;
}
export interface CreateChatCompletionResponse {
id: string;
object: string;
created: number;
choices: Choice[];
usage: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
}
export class OpenAIApi {
constructor(configuration: Configuration);
createChatCompletion(params: {
model: string;
messages: Message[];
max_tokens?: number;
}): Promise<CreateChatCompletionResponse>;
}
}
서버의 API 라우트를 작성해 사용자가 말한 텍스트를 OpenAI API에 보내 개선된 표현을 추천받습니다.
// app/api/getSuggestion/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { Configuration, OpenAIApi } from 'openai';
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
export async function POST(req: NextRequest) {
const { text } = await req.json();
try {
const response = await openai.createChatCompletion({
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "You are a helpful assistant that improves phrasing for spoken English to make it sound more natural." },
{ role: "user", content: `Here's what was spoken: "${text}". How could this be phrased more naturally?` },
],
max_tokens: 100,
});
const suggestion = response.choices[0].message?.content;
return NextResponse.json({ suggestion });
} catch (error) {
console.error(error);
return NextResponse.json({ message: 'Error generating suggestion' }, { status: 500 });
}
}
//app/(mobile)/chat/page.tsx
import OpenAI from "openai";
import React from "react";
const openai = new OpenAI({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY
});
const Page = async () => {
const text = "me here airport";
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{
role: "system",
content:
"You are a useful tutor who will help you improve your spoken language so that it sounds more natural. If the user says something in Korean, please give me advice so that I can change it to more natural expression in Korean, and if I say something in English, I say English."
},
{
role: "user",
content: `${text}`
}
]
});
const result = completion.choices[0].message.content;
// console.log(completion.choices[0].message); // 객체
return <>{result}</>;
};
export default Page;

user: 한국인 / 배우고 싶은언어: 영어
영어로 “me here airport”라고 말하면,
AI는 “자연스러운 표현으로는 "I’m in the airport." 라고 할 수 있습니다.” 라고 코칭해줘야함.
system content 수정 필요
content: 당신은 음성 언어의 표현을 개선하여 더 자연스럽게 표현할 수 있도록 도와주는 유용한 튜터입니다. 사용자가 한국어로 말하면 고칠 표현은 한국어로 조언은 영어로, 영어로 말하면 고칠 표현은 영어로, 조언은 한국어로 코칭해줘.

결과 : “”안에만 표현한 언어로 말하고, 조언은 그 반대 언어로 말해야하는데 약간 어설픔.
content: 당신은 음성 언어의 표현을 개선하여 더 자연스럽게 표현할 수 있도록 도와주는 유용한 한국어와 영어 튜터입니다. 사용자가 한국어로 말하면 고칠 표현은 한국어로 ""안에 넣어주고, 조언은 영어로 해줘. 만약 사용자가 영어로 말하면 고칠 표현은 영어로 ""안에 넣어주고, 조언은 한국어로 해줘.

결과: 문법까지 고려해서 잘 말해줌.
text = "나 갈게 너집안으로”
content: a랑 동일하게

결과: 어색한 표현을 어떻게 표현하면 좋을지 고쳐줌.