Mastra 에이전트는 음성 기능으로 향상시킬 수 있어, 응답을 말하고 사용자 입력을 들을 수 있습니다. 단일 음성 제공업체를 사용하거나 다양한 작업을 위해 여러 제공업체를 결합하여 에이전트를 구성할 수 있습니다.
단일 제공업체 사용하기
에이전트에 음성을 추가하는 가장 간단한 방법은 말하기와 듣기 모두에 단일 제공업체를 사용하는 것입니다:
import { createReadStream } from "fs";
import path from "path";
import { Agent } from "@mastra/core/agent";
import { OpenAIVoice } from "@mastra/voice-openai";
import { openai } from "@ai-sdk/openai";
// 기본 설정으로 음성 제공업체 초기화
const voice = new OpenAIVoice();
// 음성 기능을 가진 에이전트 생성
export const agent = new Agent({
name: "Agent",
instructions: `You are a helpful assistant with both STT and TTS capabilities.`,
model: openai("gpt-4o"),
voice,
});
// 이제 에이전트는 상호작용에 음성을 사용할 수 있습니다
const audioStream = await agent.voice.speak("안녕하세요, 저는 당신의 AI 어시스턴트입니다!", {
filetype: "m4a",
});
playAudio(audioStream!);
try {
const transcription = await agent.voice.listen(audioStream);
console.log(transcription);
} catch (error) {
console.error("오디오 전사 오류:", error);
}
여러 제공업체 사용하기
더 많은 유연성을 위해 CompositeVoice 클래스를 사용하여 말하기와 듣기에 다른 제공업체를 사용할 수 있습니다:
import { Agent } from "@mastra/core/agent";
import { CompositeVoice } from "@mastra/core/voice";
import { OpenAIVoice } from "@mastra/voice-openai";
import { PlayAIVoice } from "@mastra/voice-playai";
import { openai } from "@ai-sdk/openai";
export const agent = new Agent({
name: "Agent",
instructions: `You are a helpful assistant with both STT and TTS capabilities.`,
model: openai("gpt-4o"),
// 듣기는 OpenAI, 말하기는 PlayAI를 사용하는 복합 음성 생성
voice: new CompositeVoice({
input: new OpenAIVoice(),
output: new PlayAIVoice(),
}),
});
오디오 스트림 작업
speak()와 listen() 메소드는 Node.js 스트림과 함께 작동합니다. 오디오 파일을 저장하고 로드하는 방법은 다음과 같습니다:
음성 출력 저장
speak 메소드는 파일이나 스피커로 연결할 수 있는 스트림을 반환합니다.
import { createWriteStream } from "fs";
import path from "path";
// 음성을 생성하고 파일에 저장
const audio = await agent.voice.speak("안녕하세요, 세상!");
const filePath = path.join(process.cwd(), "agent.mp3");
const writer = createWriteStream(filePath);
audio.pipe(writer);
await new Promise<void>((resolve, reject) => {
writer.on("finish", () => resolve());
writer.on("error", reject);
});
오디오 입력 전사
listen 메소드는 마이크나 파일의 오디오 데이터 스트림을 기대합니다.
import { createReadStream } from "fs";
import path from "path";
// 오디오 파일을 읽고 전사
const audioFilePath = path.join(process.cwd(), "/agent.m4a");
const audioStream = createReadStream(audioFilePath);
try {
console.log("오디오 파일 전사 중...");
const transcription = await agent.voice.listen(audioStream, {
filetype: "m4a",
});
console.log("전사 결과:", transcription);
} catch (error) {
console.error("오디오 전사 오류:", error);
}
음성-음성 상호작용
더 동적이고 상호작용적인 음성 경험을 위해, 음성-음성 기능을 지원하는 실시간 음성 제공업체를 사용할 수 있습니다:
import { Agent } from "@mastra/core/agent";
import { getMicrophoneStream } from "@mastra/node-audio";
import { OpenAIRealtimeVoice } from "@mastra/voice-openai-realtime";
import { search, calculate } from "../tools";
// 실시간 음성 제공업체 초기화
const voice = new OpenAIRealtimeVoice({
apiKey: process.env.OPENAI_API_KEY,
model: "gpt-4o-mini-realtime",
speaker: "alloy",
});
// 음성-음성 기능을 가진 에이전트 생성
export const agent = new Agent({
name: "Agent",
instructions: `You are a helpful assistant with speech-to-speech capabilities.`,
model: openai("gpt-4o"),
tools: {
// 에이전트에 구성된 도구들이 음성 제공업체로 전달됩니다
search,
calculate,
},
voice,
});
// WebSocket 연결 설정
await agent.voice.connect();
// 대화 시작
agent.voice.speak("안녕하세요, 저는 당신의 AI 어시스턴트입니다!");
// 마이크에서 오디오 스트리밍
const microphoneStream = getMicrophoneStream();
agent.voice.send(microphoneStream);
// 대화가 끝나면
agent.voice.close();
이벤트 시스템
실시간 음성 제공업체는 수신할 수 있는 여러 이벤트를 발생시킵니다:
// 음성 제공업체에서 전송된 음성 오디오 데이터 수신
agent.voice.on("speaking", ({ audio }) => {
// audio는 ReadableStream 또는 Int16Array 오디오 데이터를 포함합니다
});
// 음성 제공업체와 사용자 모두에서 전송된 전사된 텍스트 수신
agent.voice.on("writing", ({ text, role }) => {
console.log(`${role}이(가) 말했습니다: ${text}`);
});
// 오류 수신
agent.voice.on("error", (error) => {
console.error("음성 오류:", error);
});
지원되는 음성 제공업체
Mastra는 TTS(텍스트-음성 변환) 및 STT(음성-텍스트 변환) 기능을 위한 여러 음성 제공업체를 지원합니다:
음성 기능에 대한 자세한 내용은 Voice API Reference를 참조하세요.
2025년 7월 26일 기준 번역
by dongne.lab@gmail.com