HeyGen AI Agent

This example puts a HeyGen LiveAvatar (a photorealistic, real-time streaming
avatar) into a SightLab scene as the face and voice of the AI Agent.
Overview
- The avatar is streamed from HeyGen and shown on a video screen in the scene.
- The replies come from the AI model you choose (ChatGPT, Claude, Gemini, or an
offline Ollama model such as gemma3) using the prompt files inprompts/. You can
also let HeyGen's own AI answer instead (HEYGEN_USE_BUILTIN_AI = True). - Eye tracking and other SightLab data are recorded as usual, and the avatar's
video and voice are saved per trial so the session can be replayed with the
avatar playing on its screen (HeyGen_Replay.py).
Prefer running LiveAvatar in a browser instead? You can screencast any browser
window (including the LiveAvatar web app) into a SightLab scene with the
Virtual Screencasting
example (ExampleScripts/Virtual_Screencast). In that setup the avatar and its AI
are controlled entirely by the LiveAvatar web app.
Requirements
Python Packages
Install the required packages:
pip install livekit requests numpy opencv-python Pillow sounddevice SpeechRecognition
HeyGen Account
- Sign up for a HeyGen/LiveAvatar account at https://www.liveavatar.com/
- Get your API key from the LiveAvatar settings page
- Pick an avatar: with
USE_AVATAR_CHOOSER = Truethe script shows a dropdown of
every avatar your key can use; otherwise setHEYGEN_AVATAR_ID
Trying it without credits: set HEYGEN_SANDBOX_MODE = True. Sandbox sessions
are free, but they last about 1 minute and only the "Wayne" avatar is allowed (the
script switches to it automatically). An API key is still required; a key from
an account with 0 credits works. Paid sessions cost 2 credits per minute in FULL mode.
Configuration
Where the API key is read from
The LiveAvatar key is checked in this order:
keys/heygen_api_key.txt(next to the script, then../_dashboard/keys/, then
Documents/Sightlab2/ExampleScripts/_dashboard/keys/), the same folders the
OpenAI/Anthropic/Gemini key files useHEYGEN_API_KEYinConfig_Global.py- The
HEYGEN_API_KEYenvironment variable
The simplest setup is to paste the key (just the key, on one line) into
keys/heygen_api_key.txt.
Method 1: Environment Variables
Set these environment variables:
# Windows (PowerShell)
$env:HEYGEN_API_KEY = "your-api-key-here"
$env:HEYGEN_AVATAR_ID = "your-avatar-id"
# Windows (Command Prompt)
setx HEYGEN_API_KEY your-api-key-here
setx HEYGEN_AVATAR_ID your-avatar-id
# Linux/Mac
export HEYGEN_API_KEY="your-api-key-here"
export HEYGEN_AVATAR_ID="your-avatar-id"
Method 2: Config File
Edit Config_Global.py and set:
USE_HEYGEN_AVATAR = True
HEYGEN_API_KEY = "your-api-key-here"
HEYGEN_AVATAR_ID = "your-avatar-id"
Optional Configuration
In Config_Global.py:
# HeyGen Settings
HEYGEN_VOICE_ID = None # Optional: specific voice ID
HEYGEN_CONTEXT_ID = None # Optional: persona context
HEYGEN_LANGUAGE = "en" # Language code
HEYGEN_MODE = "FULL" # FULL or CUSTOM mode
HEYGEN_USE_BUILTIN_AI = False # Use HeyGen's AI or your own
# Video Screen Position in VR
HEYGEN_VIDEO_SCREEN_POSITION = [0, 1.5, 2] # [x, y, z]
HEYGEN_VIDEO_SCREEN_SCALE = [1.5, 1.5, 1.5] # Scale
HEYGEN_VIDEO_SCREEN_EULER = [0, 180, 0] # Rotation
# Development mode (uses fewer credits)
HEYGEN_SANDBOX_MODE = False
Usage
Running with HeyGen Avatar
Run AI_Agent_HeyGen.py. At startup you choose the prompt file, the AI model and
the avatar (each dropdown remembers your last choice).
Controls
| Key | Action |
|---|---|
c |
Start/stop speaking to avatar |
t |
Open text chat window |
m |
Scale video up |
n |
Scale video down |
h |
Take screenshot |
Space |
Start/end trial |
Recording and Replay
Each trial is saved in recordings/ when RECORD_AVATAR_VIDEO = True (the default):
| File | Contents |
|---|---|
<date>_<participant>_trial_<n>_avatar.mp4 |
The avatar's video, starting at trial start |
<date>_<participant>_trial_<n>_avatar.wav |
The avatar's voice, on the same timeline |
<date>_<participant>_trial_<n>_avatar.json |
Where the avatar screen was placed |
To replay, run HeyGen_Replay.py, pick the session, then pick the avatar video
(the selected session's videos are listed first). The avatar plays on its screen
and follows play, pause, restart and scrubbing.
SCREEN_RECORD = True additionally saves SightLab's own recording of the
participant's view (.avi). With USE_GUI = True, SightLab's screen-record
option does the same.
Recorded avatar video is HeyGen output: on a free HeyGen plan it may only be used
for personal, non-commercial evaluation; paid plans own their output (see
HeyGen's Terms of Service).
Architecture
How It Works
- Session Creation: The system creates a HeyGen session via the REST API
- LiveKit Connection: Connects to a LiveKit room for WebRTC streaming
- Video Display: Receives video frames and displays them on a quad in VR
- Audio Playback: Receives audio from the avatar for spatial playback
- Commands: Sends text to the avatar via LiveKit data channels
Modes
FULL Mode (Recommended):
- HeyGen handles speech recognition and can use its built-in AI
- You can also provide your own AI responses
- Full transcription and event support
CUSTOM Mode:
- You provide all audio input via websocket
- More control but more complex setup
Using Your Own AI vs HeyGen's AI
Your Own AI (HEYGEN_USE_BUILTIN_AI = False):
# Your AI generates the response
response = your_ai_model.generate(user_input)
# Send to HeyGen just for speech synthesis
heygen_session.speak_text(response)
HeyGen's Built-in AI (HEYGEN_USE_BUILTIN_AI = True):
# HeyGen handles AI response generation
heygen_session.speak_response(user_input)
API Reference
HeyGen_Avatar Module
import HeyGen_Avatar
# Initialize session
session = HeyGen_Avatar.initialize_heygen(
api_key="your-key",
avatar_id="your-avatar"
)
# Set up video display in Vizard
display = HeyGen_Avatar.setup_heygen_display(viz, vizfx)
# Make avatar speak
HeyGen_Avatar.speak("Hello, how can I help you?")
# Use HeyGen's AI for response
HeyGen_Avatar.speak_response("What is the weather?")
# Interrupt avatar
HeyGen_Avatar.interrupt()
# Clean up
HeyGen_Avatar.cleanup_heygen()
Event Handling
# Register event callbacks
session.on_event("avatar.speak_started", lambda msg: print("Speaking..."))
session.on_event("avatar.speak_ended", lambda msg: print("Done"))
session.on_event("user.transcription", lambda msg: print(f"User: {msg['text']}"))
Available Events (FULL Mode)
Command Events (you send):
- avatar.speak_text - Speak specific text
- avatar.speak_response - Generate AI response to text
- avatar.interrupt - Stop current speech
- avatar.start_listening - Start listening mode
- avatar.stop_listening - Stop listening mode
Server Events (you receive):
- user.speak_started - User started talking
- user.speak_ended - User stopped talking
- avatar.speak_started - Avatar started talking
- avatar.speak_ended - Avatar stopped talking
- user.transcription - User speech transcribed
- avatar.transcription - Avatar response text
Troubleshooting
Common Issues
"livekit package not installed"
pip install livekit
Do I need livekit-api?
No. livekit-api is LiveKit's server SDK for minting room tokens. HeyGen's
/sessions/start call already returns a client token, so only the livekit
client package (livekit.rtc) is used.
Avatar never answers after "User said: ..."
- The console should show [AI] Asking <model>... then [AI] Reply (Ns): ...
then [HeyGen] Sent command: avatar.speak_text (...). Whichever line is
missing tells you where it stopped.
- With AI_MODEL = 'OFFLINE_OLLAMA', the Ollama app must be running and the
model pulled (ollama pull gemma3). The startup line [AI] gemma3 ready
confirms this. Requests time out after 60 s instead of hanging.
"Session creation failed"
- Check your API key is valid
- Check your internet connection
- Verify your avatar ID exists
"No video appearing"
- Check the video screen position is visible
- Try adjusting HEYGEN_VIDEO_SCREEN_POSITION
- Check console for frame processing errors
"Avatar not speaking"
- Ensure session is connected
- Check the text is not empty
- Look for errors in console
Debug Mode
# Print detailed status
HeyGen_Avatar.print_heygen_status()
Resources
- LiveAvatar Documentation
- LiveAvatar Quick Start
- FULL Mode Events
- LiveKit Python SDK
- HeyGen Community
License
This integration is provided as-is for use with SightLab VR.
HeyGen/LiveAvatar services require a separate subscription.