Compare commits

..

4 Commits

Author SHA1 Message Date
raojianb
b0a98ea95e fix: text constant error 2024-07-25 16:18:43 -07:00
annie
ab85e604ef interactive avatar name change 2024-07-22 11:45:31 -07:00
annie
5d0cf3821c add avatar/voice examples, session start error handling 2024-07-01 12:13:56 -07:00
Joby
47522ddc97 fix: interrupt copy update (#2) 2024-07-01 11:17:47 +08:00
8 changed files with 259 additions and 74 deletions

View File

@@ -1,6 +1,6 @@
# HeyGen Streaming Avatar NextJS Demo
# HeyGen Interactive Avatar NextJS Demo
![HeyGen Streaming Avatar NextJS Demo Screenshot](./public/demo.png)
![HeyGen Interactive Avatar NextJS Demo Screenshot](./public/demo.png)
This is a sample project and was bootstrapped using [NextJS](https://nextjs.org/).
Feel free to play around with the existing code and please leave any feedback for the SDK [here](https://github.com/HeyGen-Official/StreamingAvatarSDK/discussions).
@@ -15,7 +15,7 @@ Feel free to play around with the existing code and please leave any feedback fo
3. Run `npm install` (assuming you have npm installed. If not, please follow these instructions: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm/)
4. Enter your HeyGen Enterprise API Token or Trial Token in the `.env` file. Replace `PLACEHOLDER-API-KEY` with your API key. This will allow the Client app to generate secure Access Tokens with which to create streaming sessions.
4. Enter your HeyGen Enterprise API Token or Trial Token in the `.env` file. Replace `PLACEHOLDER-API-KEY` with your API key. This will allow the Client app to generate secure Access Tokens with which to create interactive sessions.
You can retrieve either the API Key or Trial Token by logging in to HeyGen and navigating to this page in your settings: [https://app.heygen.com/settings?nav=API]. NOTE: use the trial token if you don't have an enterprise API token yet.
@@ -25,35 +25,35 @@ Feel free to play around with the existing code and please leave any feedback fo
### Difference between Trial Token and Enterprise API Token
The HeyGen Trial Token is available to all users, not just Enterprise users, and allows for testing of the Streaming API, as well as other HeyGen API endpoints.
The HeyGen Trial Token is available to all users, not just Enterprise users, and allows for testing of the Interactive Avatar API, as well as other HeyGen API endpoints.
Each Trial Token is limited to 3 concurrent streaming sessions. However, every streaming session you create with the Trial Token is free of charge, no matter how many tasks are sent to the avatar. Please note that streaming sessions will automatically close after 10 minutes of no tasks sent.
Each Trial Token is limited to 3 concurrent interactive sessions. However, every interactive session you create with the Trial Token is free of charge, no matter how many tasks are sent to the avatar. Please note that interactive sessions will automatically close after 10 minutes of no tasks sent.
If you do not 'close' the streaming sessions and try to open more than 3, you will encounter errors including stuttering and freezing of the Streaming Avatar. Please endeavor to only have 3 sessions open at any time while you are testing the Streaming Avatar API with your Trial Token.
If you do not 'close' the interactive sessions and try to open more than 3, you will encounter errors including stuttering and freezing of the Interactive Avatar. Please endeavor to only have 3 sessions open at any time while you are testing the Interactive Avatar API with your Trial Token.
### Starting sessions
NOTE: Make sure you have enter your token into the `.env` file and run `npm run dev`.
To start your 'session' with a Streaming Avatar, first click the 'start' button. If your HeyGen API key is entered into the Server's .env file, then you should see our demo Streaming Avatar (Monica!) appear.
To start your 'session' with a Interactive Avatar, first click the 'start' button. If your HeyGen API key is entered into the Server's .env file, then you should see our demo Interactive Avatar (Monica!) appear.
After you see Monica appear on the screen, you can enter text into the input labeled 'Repeat', and then hit Enter. The Streaming Avatar will say the text you enter.
After you see Monica appear on the screen, you can enter text into the input labeled 'Repeat', and then hit Enter. The Interactive Avatar will say the text you enter.
If you want to see a different Avatar or try a different voice, you can close the session and enter the IDs and then 'start' the session again. Please see below for information on where to retrieve different Avatar and voice IDs that you can use.
### Connecting to OpenAI
A common use case for a Streaming Avatar is to use it as the 'face' of an LLM that users can interact with. In this demo we have included functionality to showcase this by both accepting user input via voice (using OpenAI's Whisper library) and also sending that input to an OpenAI LLM model (using their Chat Completions endpoint).
A common use case for a Interactive Avatar is to use it as the 'face' of an LLM that users can interact with. In this demo we have included functionality to showcase this by both accepting user input via voice (using OpenAI's Whisper library) and also sending that input to an OpenAI LLM model (using their Chat Completions endpoint).
Both of these features of this demo require an OpenAI API Key. If you do not have a paid OpenAI account, you can learn more on their website: [https://openai.com/index/openai-api/]
Without an OpenAI API Key, this functionality will not work, and the Streaming Avatar will only be able to repeat text input that you provide, and not demonstrate being the 'face' of an LLM. Regardless, this demo is meant to demonstrate what kinds of apps and experiences you can build with our Streaming Avatar SDK, so you can code your own connection to a different LLM if you so choose.
Without an OpenAI API Key, this functionality will not work, and the Interactive Avatar will only be able to repeat text input that you provide, and not demonstrate being the 'face' of an LLM. Regardless, this demo is meant to demonstrate what kinds of apps and experiences you can build with our Interactive Avatar SDK, so you can code your own connection to a different LLM if you so choose.
To add your Open AI API Key, fill copy it to the `OPENAI_API_KEY` and `NEXT_PUBLIC_OPENAI_API_KEY` variables in the `.env` file.
### How does the integration with OpenAI / ChatGPT work?
In this demo, we are calling the Chat Completions API from OpenAI in order to come up with some response to user input. You can see the relevant code in components/StreamingAvatar.tsx.
In this demo, we are calling the Chat Completions API from OpenAI in order to come up with some response to user input. You can see the relevant code in components/InteractiveAvatar.tsx.
In the initialMessages parameter, you can replace the content of the 'system' message with whatever 'knowledge base' or context that you would like the GPT-4o model to reply to the user's input with.
@@ -61,20 +61,20 @@ You can explore this API and the different parameters and models available here:
### Which Avatars can I use with this project?
By default, there are several Public Avatars that can be used in Streaming. (AKA Streaming Avatars.) You can find the Avatar IDs for these Public Avatars by navigating to [app.heygen.com/streaming-avatar](https://app.heygen.com/streaming-avatar) and clicking 'Select Avatar' and copying the avatar id.
By default, there are several Public Avatars that can be used in Interactive Avatar. (AKA Interactive Avatars.) You can find the Avatar IDs for these Public Avatars by navigating to [app.heygen.com/interactive-avatar](https://app.heygen.com/interactive-avatar) and clicking 'Select Avatar' and copying the avatar id.
In order to use a private Avatar created under your own account in Streaming, it must be upgraded to be a Streaming Avatar. Only 1. Finetune Instant Avatars and 2. Studio Avatars are able to be upgraded to Streaming Avatars. This upgrade is a one-time fee and can be purchased by navigating to [app.heygen.com/streaming-avatar] and clicking 'Select Avatar'.
In order to use a private Avatar created under your own account in Interactive Avatar, it must be upgraded to be a Interactive Avatar. Only 1. Finetune Instant Avatars and 2. Studio Avatars are able to be upgraded to Interactive Avatars. This upgrade is a one-time fee and can be purchased by navigating to [app.heygen.com/interactive-avatar] and clicking 'Select Avatar'.
Please note that Photo Avatars are not compatible with Streaming and cannot be used.
Please note that Photo Avatars are not compatible with Interactive Avatar and cannot be used.
### Which voices can I use with my Streaming Avatar?
### Which voices can I use with my Interactive Avatar?
Most of HeyGen's AI Voices can be used with the Streaming API. To find the Voice IDs that you can use, please use the List Voices v2 endpoint from HeyGen: [https://docs.heygen.com/reference/list-voices-v2]
Most of HeyGen's AI Voices can be used with the Interactive Avatar API. To find the Voice IDs that you can use, please use the List Voices v2 endpoint from HeyGen: [https://docs.heygen.com/reference/list-voices-v2]
Please note that for voices that support Emotions, such as Christine and Tarquin, you need to pass in the Emotion string in the Voice Setting parameter: [https://docs.heygen.com/reference/new-session-copy#voicesetting]
You can also set the speed at which the Streaming Avatar speaks by passing in a Rate in the Voice Setting.
You can also set the speed at which the Interactive Avatar speaks by passing in a Rate in the Voice Setting.
### Where can I read more about enterprise-level usage of the Streaming API?
### Where can I read more about enterprise-level usage of the Interactive Avatar API?
Please read our Streaming Avatar 101 article for more information on pricing and how to increase your concurrent session limit: https://help.heygen.com/en/articles/9182113-streaming-avatar-101-your-ultimate-guide
Please read our Interactive Avatar 101 article for more information on pricing and how to increase your concurrent session limit: https://help.heygen.com/en/articles/9182113-interactive-avatar-101-your-ultimate-guide

View File

@@ -19,8 +19,8 @@ const fontMono = FontMono({
export const metadata: Metadata = {
title: {
default: "HeyGen Streaming Avatar SDK Demo",
template: `%s - HeyGen Streaming Avatar SDK Demo`,
default: "HeyGen Interactive Avatar SDK Demo",
template: `%s - HeyGen Interactive Avatar SDK Demo`,
},
icons: {
icon: "/heygen-logo.png",

135
app/lib/constants.ts Normal file
View File

@@ -0,0 +1,135 @@
export const AVATARS = [
{
avatar_id: "Eric_public_pro2_20230608",
name: "Edward in Blue Shirt",
},
{
avatar_id: "Tyler-incasualsuit-20220721",
name: "Tyler in Casual Suit",
},
{
avatar_id: "Anna_public_3_20240108",
name: "Anna in Brown T-shirt",
},
{
avatar_id: "Susan_public_2_20240328",
name: "Susan in Black Shirt",
},
{
avatar_id: "josh_lite3_20230714",
name: "Joshua Heygen CEO",
},
];
export const VOICES = [
{
voice_id: "077ab11b14f04ce0b49b5f6e5cc20979",
language: "English",
gender: "Male",
name: "Paul - Natural",
preview_audio:
"https://static.heygen.ai/voice_preview/k6dKrFe85PisZ3FMLeppUM.mp3",
support_pause: true,
emotion_support: false,
},
{
voice_id: "131a436c47064f708210df6628ef8f32",
language: "English",
gender: "Female",
name: "Amber - Friendly",
preview_audio:
"https://static.heygen.ai/voice_preview/5HHGT48B6g6aSg2buYcBvw.wav",
support_pause: true,
emotion_support: false,
},
{
voice_id: "0ebe70d83b2349529e56492c002c9572",
language: "English",
gender: "Male",
name: "Antoni - Friendly",
preview_audio:
"https://static.heygen.ai/voice_preview/TwupgZ2az5RiTnmAifPmmS.mp3",
support_pause: true,
emotion_support: false,
},
{
voice_id: "1bd001e7e50f421d891986aad5158bc8",
language: "English",
gender: "Female",
name: "Sara - Cheerful",
preview_audio:
"https://static.heygen.ai/voice_preview/func8CFnfVLKF2VzGDCDCR.wav",
support_pause: true,
emotion_support: false,
},
{
voice_id: "001cc6d54eae4ca2b5fb16ca8e8eb9bb",
language: "Spanish",
gender: "Male",
name: "Elias - Natural",
preview_audio:
"https://static.heygen.ai/voice_preview/JmCb3rgMZnCjCAA9aacnGj.wav",
support_pause: false,
emotion_support: false,
},
{
voice_id: "00988b7d451d0722635ff7b2b9540a7b",
language: "Portuguese",
gender: "Female",
name: "Brenda - Professional",
preview_audio:
"https://static.heygen.ai/voice_preview/fec6396adb73461c9997b2c0d7759b7b.wav",
support_pause: true,
emotion_support: false,
},
{
voice_id: "00c8fd447ad7480ab1785825978a2215",
language: "Chinese",
gender: "Female",
name: "Xiaoxuan - Serious",
preview_audio:
"https://static.heygen.ai/voice_preview/909633f8d34e408a9aaa4e1b60586865.wav",
support_pause: true,
emotion_support: false,
},
{
voice_id: "00ed77fac8b84ffcb2ab52739b9dccd3",
language: "Latvian",
gender: "Male",
name: "Nils - Affinity",
preview_audio:
"https://static.heygen.ai/voice_preview/KwTwAz3R4aBFN69fEYQFdX.wav",
support_pause: true,
emotion_support: false,
},
{
voice_id: "02bec3b4cb514722a84e4e18d596fddf",
language: "Arabic",
gender: "Female",
name: "Fatima - Professional",
preview_audio:
"https://static.heygen.ai/voice_preview/930a245487fe42158c810ac76b8ddbab.wav",
support_pause: true,
emotion_support: false,
},
{
voice_id: "04e95f5bcb8b4620a2c4ef45b8a4481a",
language: "Ukrainian",
gender: "Female",
name: "Polina - Professional",
preview_audio:
"https://static.heygen.ai/voice_preview/ntekV94yFpvv4RgBVPqW7c.wav",
support_pause: true,
emotion_support: false,
},
{
voice_id: "071d6bea6a7f455b82b6364dab9104a2",
language: "German",
gender: "Male",
name: "Jan - Natural",
preview_audio:
"https://static.heygen.ai/voice_preview/fa3728bed81a4d11b8ccef10506af5f4.wav",
support_pause: true,
emotion_support: false,
},
];

View File

@@ -1,7 +1,7 @@
"use client";
import StreamingAvatar from "@/components/StreamingAvatar";
import StreamingAvatarCode from "@/components/StreamingAvatarCode";
import InteractiveAvatar from "@/components/InteractiveAvatar";
import InteractiveAvatarCode from "@/components/InteractiveAvatarCode";
import { Tab, Tabs } from "@nextui-org/react";
export default function App() {
@@ -9,12 +9,12 @@ export default function App() {
{
id: "demo",
label: "Demo",
content: <StreamingAvatar />,
content: <InteractiveAvatar />,
},
{
id: "code",
label: "Code",
content: <StreamingAvatarCode />,
content: <InteractiveAvatarCode />,
},
];

View File

@@ -1,3 +1,4 @@
import { AVATARS, VOICES } from "@/app/lib/constants";
import {
Configuration,
NewSessionData,
@@ -10,6 +11,8 @@ import {
CardFooter,
Divider,
Input,
Select,
SelectItem,
Spinner,
Tooltip,
} from "@nextui-org/react";
@@ -18,14 +21,14 @@ import { useChat } from "ai/react";
import clsx from "clsx";
import OpenAI from "openai";
import { useEffect, useRef, useState } from "react";
import StreamingAvatarTextInput from "./StreamingAvatarTextInput";
import InteractiveAvatarTextInput from "./InteractiveAvatarTextInput";
const openai = new OpenAI({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
dangerouslyAllowBrowser: true,
});
export default function StreamingAvatar() {
export default function InteractiveAvatar() {
const [isLoadingSession, setIsLoadingSession] = useState(false);
const [isLoadingRepeat, setIsLoadingRepeat] = useState(false);
const [isLoadingChat, setIsLoadingChat] = useState(false);
@@ -50,7 +53,7 @@ export default function StreamingAvatar() {
return;
}
//send the ChatGPT response to the Streaming Avatar
//send the ChatGPT response to the Interactive Avatar
await avatar.current
.speak({
taskRequest: { text: message.content, sessionId: data?.sessionId },
@@ -103,10 +106,13 @@ export default function StreamingAvatar() {
);
setData(res);
setStream(avatar.current.mediaStream);
setIsLoadingSession(false);
} catch (error) {
console.error("Error starting avatar session:", error);
setDebug(
`There was an error starting the session. ${voiceId ? "This custom voice ID may not be supported." : ""}`
);
}
setIsLoadingSession(false);
}
async function updateToken() {
@@ -133,12 +139,14 @@ export default function StreamingAvatar() {
async function handleInterrupt() {
if (!initialized || !avatar.current) {
setDebug('Avatar API not initialized');
setDebug("Avatar API not initialized");
return;
}
await avatar.current.interrupt({ interruptRequest: { sessionId: data?.sessionId } }).catch((e) => {
setDebug(e.message);
});
await avatar.current
.interrupt({ interruptRequest: { sessionId: data?.sessionId } })
.catch((e) => {
setDebug(e.message);
});
}
async function endSession() {
@@ -259,35 +267,76 @@ export default function StreamingAvatar() {
>
<track kind="captions" />
</video>
<Button
size="md"
onClick={handleInterrupt}
className="bg-gradient-to-tr from-indigo-500 to-indigo-300 absolute bottom-20 right-3 text-white rounded-lg"
variant="shadow"
>
Interrupt task
</Button>
<Button
size="md"
onClick={endSession}
className="bg-gradient-to-tr from-indigo-500 to-indigo-300 absolute bottom-3 right-3 text-white rounded-lg"
variant="shadow"
>
End session
</Button>
<div className="flex flex-col gap-2 absolute bottom-3 right-3">
<Button
size="md"
onClick={handleInterrupt}
className="bg-gradient-to-tr from-indigo-500 to-indigo-300 text-white rounded-lg"
variant="shadow"
>
Interrupt task
</Button>
<Button
size="md"
onClick={endSession}
className="bg-gradient-to-tr from-indigo-500 to-indigo-300 text-white rounded-lg"
variant="shadow"
>
End session
</Button>
</div>
</div>
) : !isLoadingSession ? (
<div className="h-full justify-center items-center flex flex-col gap-4 w-96 self-center">
<Input
value={avatarId}
onChange={(e) => setAvatarId(e.target.value)}
placeholder="Custom Avatar ID (optional)"
/>
<Input
value={voiceId}
onChange={(e) => setVoiceId(e.target.value)}
placeholder="Custom Voice ID (optional)"
/>
<div className="h-full justify-center items-center flex flex-col gap-8 w-[500px] self-center">
<div className="flex flex-col gap-2 w-full">
<p className="text-sm font-medium leading-none">
Custom Avatar ID (optional)
</p>
<Input
value={avatarId}
onChange={(e) => setAvatarId(e.target.value)}
placeholder="Enter a custom avatar ID"
/>
<Select
placeholder="Or select one from these example avatars"
size="md"
onChange={(e) => {
setAvatarId(e.target.value);
}}
>
{AVATARS.map((avatar) => (
<SelectItem
key={avatar.avatar_id}
textValue={avatar.avatar_id}
>
{avatar.name}
</SelectItem>
))}
</Select>
</div>
<div className="flex flex-col gap-2 w-full">
<p className="text-sm font-medium leading-none">
Custom Voice ID (optional)
</p>
<Input
value={voiceId}
onChange={(e) => setVoiceId(e.target.value)}
placeholder="Enter a custom voice ID"
/>
<Select
placeholder="Or select one from these example voices"
size="md"
onChange={(e) => {
setVoiceId(e.target.value);
}}
>
{VOICES.map((voice) => (
<SelectItem key={voice.voice_id} textValue={voice.voice_id}>
{voice.name} | {voice.language} | {voice.gender}
</SelectItem>
))}
</Select>
</div>
<Button
size="md"
onClick={startSession}
@@ -303,7 +352,7 @@ export default function StreamingAvatar() {
</CardBody>
<Divider />
<CardFooter className="flex flex-col gap-3">
<StreamingAvatarTextInput
<InteractiveAvatarTextInput
label="Repeat"
placeholder="Type something for the avatar to repeat"
input={text}
@@ -312,7 +361,7 @@ export default function StreamingAvatar() {
disabled={!stream}
loading={isLoadingRepeat}
/>
<StreamingAvatarTextInput
<InteractiveAvatarTextInput
label="Chat"
placeholder="Chat with the avatar (uses ChatGPT)"
input={input}

View File

@@ -2,7 +2,7 @@ import { Card, CardBody } from "@nextui-org/react";
import { langs } from "@uiw/codemirror-extensions-langs";
import ReactCodeMirror from "@uiw/react-codemirror";
export default function StreamingAvatarCode() {
export default function InteractiveAvatarCode() {
return (
<div className="w-full flex flex-col gap-2">
<p>This SDK supports the following behavior:</p>
@@ -10,13 +10,13 @@ export default function StreamingAvatarCode() {
<li>
<div className="flex flex-row gap-2">
<p className="text-indigo-400 font-semibold">Start:</p> Start the
streaming avatar session
Interactive Avatar session
</div>
</li>
<li>
<div className="flex flex-row gap-2">
<p className="text-indigo-400 font-semibold">Close:</p> Close the
streaming avatar session
Interactive Avatar session
</div>
</li>
<li>
@@ -47,15 +47,15 @@ const TEXT = `
const [stream, setStream] = useState<MediaStream> ();
const mediaStream = useRef<HTMLVideoElement>(null);
// Instantiate the streaming avatar api using your access token
// Instantiate the Interactive Avatar api using your access token
const avatar = useRef(new StreamingAvatarApi(
new Configuration({accessToken: '<REPLACE_WITH_ACCESS_TOKEN>'})
));
// State holding streaming avatar session data
// State holding Interactive Avatar session data
const [sessionData, setSessionData] = useState<NewSessionData>();
// Function to start the streaming avatar session
// Function to start the Interactive Avatar session
async function start(){
const res = await avatar.current.createStartAvatar(
{ newSessionRequest:
@@ -70,7 +70,7 @@ const TEXT = `
setSessionData(res);
}
// Function to stop the streaming avatar session
// Function to stop the Interactive Avatar session
async function stop(){
await avatar.current.stopAvatar({stopSessionRequest: {sessionId: sessionData?.sessionId}});
}
@@ -82,7 +82,7 @@ const TEXT = `
}
useEffect(()=>{
// Handles the display of the streaming avatar
// Handles the display of the Interactive Avatar
if(stream && mediaStream.current){
mediaStream.current.srcObject = stream;
mediaStream.current.onloadedmetadata = () => {
@@ -95,4 +95,5 @@ const TEXT = `
<div className="w-full">
<video playsInline autoPlay width={500} ref={mediaStream}/>
</div>
)
}`;

View File

@@ -13,7 +13,7 @@ interface StreamingAvatarTextInputProps {
loading?: boolean;
}
export default function StreamingAvatarTextInput({
export default function InteractiveAvatarTextInput({
label,
placeholder,
input,

View File

@@ -19,7 +19,7 @@ export default function NavBar() {
</Link>
<div className="bg-gradient-to-br from-sky-300 to-indigo-500 bg-clip-text ml-4">
<p className="text-xl font-semibold text-transparent">
HeyGen Streaming Avatar SDK NextJS Demo
HeyGen Interactive Avatar SDK NextJS Demo
</p>
</div>
</NavbarBrand>
@@ -28,7 +28,7 @@ export default function NavBar() {
<Link
isExternal
color="foreground"
href="https://app.heygen.com/streaming-avatar"
href="https://app.heygen.com/interactive-avatar"
>
Avatars
</Link>
@@ -49,7 +49,7 @@ export default function NavBar() {
<Link
isExternal
color="foreground"
href="https://help.heygen.com/en/articles/9182113-streaming-avatar-101-your-ultimate-guide"
href="https://help.heygen.com/en/articles/9182113-interactive-avatar-101-your-ultimate-guide"
>
Guide
</Link>