如何在網頁中使用 LiveKit 和 Synthesia Avatar(版本 3)?
在版本 1(英文)中,avatar 的知識直接寫死在 Python 程式裏;
在版本 2(英文)中,知識搬到一個名為
FAQs.txt 的純文字檔案。但兩個版本的瀏覽器頁面都只有一段影片和一個 Start
按鈕 — avatar 會說話,卻不能在頁面上做任何事情。
版本 3 把 avatar 放進一個真正的網頁。Lin 是虛構餐廳 YouFantasy 的接待員,住在餐廳網站
右下角的小工具裏。當客人問「你們幾點開門?」時,她會開聲回答,同時把頁面捲動到
營業時間的部份,並在上面畫一個金色圓圈。她靠的是她的第一個工具:
一個名為 show_section 的函數。
運作流程
browser mic → VAD → STT → turn detection → LLM (+ tools) → TTS → Synthesia avatar → browser video
與版本 2 相同的五個部份,用 LiveKit 的實時傳輸連接起來,外加一項新能力: LLM 可以呼叫工具。工具是模型獲准執行的一個小 Python 函數。在這裏, 工具把一個很小的訊息從代理(agent)傳到瀏覽器,頁面隨即作出反應 — 全程不到一秒,Lin 還在繼續說話。
你需要甚麼
- 一部 Mac(同樣的步驟在 Windows 和 Linux 也適用)。
- 已安裝 Homebrew(英文)和
uv套件管理工具 — 如果你沒有uv,執行brew install uv。 - 一個 LiveKit Cloud 帳戶(免費的 Build 計劃已經足夠)。
- 一個 Synthesia 帳戶。你需要至少一個在那裏建立的 avatar(免費計劃可以試用)。
- 你的 LiveKit 和 Synthesia 憑證,需要複製到一個名為
.env的檔案 — 見下文。
設定 LiveKit Cloud
在 cloud.livekit.io 註冊。 在儀表板中點擊 Projects → Create Project,然後開啟 該專案並進入 Keys。複製三個數值:
LIVEKIT_URL— 樣子像wss://your-project.livekit.cloud。LIVEKIT_API_KEY— 像APIxxxxxxxxxxxxx這樣的短字串。LIVEKIT_API_SECRET— 較長的字串,只會顯示一次。
設定 Synthesia
在 app.synthesia.io 登入。
到 Avatars 選擇或建立一個 avatar — 每個 avatar 都有一個 UUID,
開啟它時會顯示在網址中(樣子像 8788bef1-8020-46e0-a8f4-510ea9989b25)。
把它複製為 SYNTHESIA_AVATAR_ID。
然後到 API Keys
建立一把金鑰 — 那就是 SYNTHESIA_API_KEY。
建立你的 .env
在你的專案資料夾中,建立一個名為 .env 的檔案,寫入以下五行:
LIVEKIT_URL=wss://your-project.livekit.cloud
LIVEKIT_API_KEY=APIxxxxxxxxxxxxx
LIVEKIT_API_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SYNTHESIA_API_KEY=syn_xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SYNTHESIA_AVATAR_ID=8788bef1-8020-46e0-a8f4-510ea9989b25
重要:切勿把 .env 放上 GitHub 或任何公開網站 — 它載有你的有效憑證。
在自己的電腦上運行
下載 zip 檔案並解壓到一個資料夾。
zip 內有 agent.py、server.py、index.html、
FAQs.txt、pyproject.toml 和 README.md。
按照上文加入你自己的 .env 檔案。然後在 Visual Studio Code 開啟該資料夾,
在兩個獨立的終端機視窗分別執行以下命令:
終端機 1 — 語音代理 + avatar 引擎:
uv sync
uv run agent.py dev
終端機 2 — 提供瀏覽器頁面的網頁伺服器:
uv run server.py
uv sync 只需在第一次執行 — 它會安裝 Python 3.13 和所有套件。
之後只需在一個終端機啟動代理,在另一個啟動伺服器。
在瀏覽器開啟頁面
當兩個終端機都在運行時,在 Chrome、Safari 或 Edge 開啟 http://127.0.0.1:8080。 你會見到 YouFantasy 餐廳頁面,Lin 的小工具在右下角。點擊 Start, 允許咪高峰權限,等候幾秒讓代理和 avatar 加入房間。然後問一條問題,例如 「你們在哪裏?」或「你們有甚麼主菜?」— 留意頁面:當 Lin 回答時, 它會捲動到相應的部份,並畫上一個金色圓圈。
版本 3 的新功能:show_section 工具
Lin 怎樣移動頁面?三個小部份互相配合。
1. 提示詞告訴她何時做。在 agent.py 裏,Lin 的指示
現在以一本小小的規則手冊作結:當你回答關於營業時間的問題時,同時呼叫
show_section("hours");主菜呼叫 show_section("mains");
地址呼叫 show_section("location")。
2. 工具發送一個小訊息。工具本身是一個以 @function_tool
標記的短 Python 函數。當 LLM 呼叫它時,它把部份名稱包裝成一個小 JSON 訊息
— 例如 {"action": "show_section", "section": "hours"}
— 並在名為 "ui" 的數據頻道上發佈給瀏覽器。
3. 頁面監聽並捲動。在 index.html 裏,幾行 JavaScript
監聽 "ui" 頻道上的訊息。當訊息到達時,頁面找到具有該 id
的部份,平滑地捲動過去,並加上金色外框,讓客人清楚看到 Lin 正在講哪一部份。
有一個細節很重要:hours、mains 和 location
這三個名稱同時出現在兩個檔案中 — 在 agent.py 裏是一個名為
SECTIONS 的集合,在 index.html 裏是 id 屬性。
如果你在頁面新增一個部份,兩邊都要用同一個名稱(並在提示詞中提及),
否則 Lin 將無法指向它。
不用改 Python 也能編輯知識
Lin 知道的一切都存放在 FAQs.txt,就在 agent.py 旁邊:
Q: When is YouFantasy open?
A: YouFantasy is open every day from 9am to 10pm.
Q: What are the main courses?
A: Salmon, Beef, Chicken, Pork, Tofu.
Q: Where is YouFantasy?
A: YouFantasy is on Tat Chee Avenue, Kowloon Tong, Hong Kong.
Q: Any other question?
A: Sorry, I do not have answer for that question.
每次新通話開始時,agent.py 都會重新讀取這個檔案,取代提示詞中的
{faqs} 佔位符,然後開始工作階段。所以要教 Lin 新東西,只需加一組問答、
儲存檔案、開啟新通話。不用改 Python,也不用重新啟動代理。
zip 內的檔案
pyproject.toml
[project]
name = "folder-ai-avatar-v3"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = [
"aiohttp>=3.14.4",
"livekit-agents[openai,silero]~=1.8",
"livekit-plugins-synthesia~=1.8",
"python-dotenv>=1.2.4",
]
[build-system]
requires = ["setuptools>=70"]
build-backend = "setuptools.build_meta"
[tool.setuptools.packages.find]
include = []
agent.py
import asyncio
import json
import os
from pathlib import Path
from dotenv import load_dotenv
from livekit.agents import Agent, AgentSession, JobContext, WorkerOptions, cli, function_tool, inference
from livekit.plugins import silero, synthesia
load_dotenv(dotenv_path=Path(__file__).parent / ".env")
AGENT_NAME = "avatar-demo"
AVATAR_ID = os.getenv("SYNTHESIA_AVATAR_ID") or "8788bef1-8020-46e0-a8f4-510ea9989b25" # Jenny
VOICE_ID = "db6b0ed5-d5d3-463d-ae85-518a07d3c2b4" # Cartesia "Skylar"
FAQS_FILE = Path(__file__).parent / "FAQs.txt" # the avatar's knowledge
SECTIONS = {"hours", "mains", "location"} # must match the section ids in index.html
# {faqs} is replaced with the contents of FAQs.txt at the start of every call.
INSTRUCTIONS = """\
You are Lin, the host at YouFantasy, a made-up restaurant. You are a real-time
avatar in a spoken conversation, so answer in one to three short sentences and never use
markdown, lists, or URLs.
Answer only from these FAQs:
{faqs}
Those are the only things you know. If the guest asks anything the FAQs do not
cover, use the answer to "Any other question?" word for word.
The guest is looking at our web page. Every time you answer one of the FAQs,
also call show_section so the page scrolls to that part:
- opening hours: show_section("hours")
- main courses: show_section("mains")
- address: show_section("location")
Do not call show_section for any other question."""
class Host(Agent):
def __init__(self, room, instructions: str) -> None:
super().__init__(instructions=instructions)
self.room = room # needed to send messages to the browser
@function_tool
async def show_section(self, section: str) -> str:
"""Scroll the guest's web page to one section and highlight it.
Args:
section: One of: hours, mains, location.
"""
if section not in SECTIONS: # tell the model, so it retries with a real name
return f"No section {section!r}. Use one of: hours, mains, location."
message = json.dumps({"action": "show_section", "section": section})
await self.room.local_participant.publish_data(message, topic="ui") # index.html listens on "ui"
return "Done."
def prewarm(proc) -> None:
proc.userdata["vad"] = silero.VAD.load()
async def entrypoint(ctx: JobContext) -> None:
await ctx.connect()
# The brain: each line is one piece of the pipeline.
session = AgentSession(
vad=ctx.proc.userdata["vad"], # is someone talking?
stt=inference.STT(model="cartesia/ink-2"), # speech -> text
llm=inference.LLM(model="openai/gpt-4.1-mini"), # text -> reply (+ tool calls)
tts=inference.TTS(model="cartesia/sonic-3.6", voice=VOICE_ID), # reply -> speech
turn_handling={
"turn_detection": "stt", # have they finished?
"preemptive_generation": {"enabled": False}, # keep off when using tools
},
)
# The face. Start it BEFORE session.start().
avatar = synthesia.AvatarSession(
synthesia.AvatarConfig(avatar_ids=[AVATAR_ID]),
join_timeout=60.0,
)
for attempt in range(3): # cold starts occasionally time out, so retry
try:
await avatar.start(session, room=ctx.room)
break
except synthesia.SynthesiaError as e:
if not e.retryable or attempt == 2:
raise
await asyncio.sleep(2)
# Read the FAQs fresh for each call, so edits to FAQs.txt show up on the next call.
faqs = FAQS_FILE.read_text(encoding="utf-8").strip()
await session.start(agent=Host(ctx.room, INSTRUCTIONS.replace("{faqs}", faqs)), room=ctx.room)
session.generate_reply(
instructions="Welcome the guest to YouFantasy and invite them to ask a question, in one short sentence."
)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm, agent_name=AGENT_NAME, port=8081))
server.py
import os
import uuid
from datetime import timedelta
from pathlib import Path
from aiohttp import web
from dotenv import load_dotenv
from livekit import api
load_dotenv(dotenv_path=Path(__file__).parent / ".env")
AGENT_NAME = "avatar-demo"
async def token(request: web.Request) -> web.Response:
room = f"avatar-demo-{uuid.uuid4().hex[:8]}"
jwt = (
api.AccessToken()
.with_identity(f"user-{uuid.uuid4().hex[:8]}")
.with_ttl(timedelta(minutes=15))
.with_grants(api.VideoGrants(room_join=True, room=room))
.with_room_config(
api.RoomConfiguration(
sync_streams=True,
agents=[api.RoomAgentDispatch(agent_name=AGENT_NAME)],
)
)
.to_jwt()
)
return web.json_response({"url": os.environ["LIVEKIT_URL"], "token": jwt})
async def index(request: web.Request) -> web.FileResponse:
return web.FileResponse(
Path(__file__).parent / "index.html", headers={"Cache-Control": "no-store"}
)
app = web.Application()
app.router.add_get("/", index)
app.router.add_get("/token", token)
if __name__ == "__main__":
web.run_app(app, host="127.0.0.1", port=8080)
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>YouFantasy</title>
<style>
/* page styling omitted here for readability — see the zip for the full file */
html { scroll-behavior: smooth; }
section.highlight { box-shadow: 0 0 0 2px #c8a35a; } /* added by show_section */
#widget { position: fixed; right: 16px; bottom: 16px; width: 260px; }
</style>
</head>
<body>
<!-- The restaurant page. Each section id is a name show_section can use. -->
<nav>
<b>YouFantasy</b>
<a href="#hours">Hours</a>
<a href="#mains">Mains</a>
<a href="#location">Location</a>
</nav>
<section id="hours">
<h2>When we are open</h2>
<p>Every day, 9am to 10pm</p>
</section>
<section id="mains">
<h2>Main courses</h2>
<ul><li>Salmon</li><li>Beef</li><li>Chicken</li><li>Pork</li><li>Tofu</li></ul>
</section>
<section id="location">
<h2>Location</h2>
<p>Tat Chee Avenue, Kowloon Tong, Hong Kong</p>
</section>
<!-- The avatar -->
<div id="widget">
<video id="video" autoplay playsinline></video>
<span><span id="label">Talk to Lin</span><span id="mic"></span></span>
<button id="start">Start</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/livekit-client@2/dist/livekit-client.umd.min.js"></script>
<script>
// What the page does when Lin calls show_section.
function showSection(section) {
const el = document.getElementById(section);
if (!el) return;
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
document.querySelectorAll('.highlight').forEach((h) => h.classList.remove('highlight'));
el.classList.add('highlight');
}
const { Room, RoomEvent } = LivekitClient;
const video = document.getElementById('video');
const label = document.getElementById('label');
const btn = document.getElementById('start');
let room = null;
btn.onclick = async () => {
if (room) return leave();
btn.textContent = 'Stop'; label.textContent = 'Connecting…';
try {
const { url, token } = await (await fetch('/token')).json();
room = new Room();
room.on(RoomEvent.TrackSubscribed, (track) => track.attach(video));
room.on(RoomEvent.ParticipantAttributesChanged, (changed) => {
if (changed['lk.agent.state']) label.textContent = changed['lk.agent.state'];
});
// Tool calls arrive here as small JSON messages on the "ui" topic.
room.on(RoomEvent.DataReceived, (payload, participant, kind, topic) => {
if (topic !== 'ui') return;
const message = JSON.parse(new TextDecoder().decode(payload));
if (message.action === 'show_section') showSection(message.section);
});
await room.connect(url, token);
await room.localParticipant.setMicrophoneEnabled(true);
label.textContent = 'Waiting for Lin…';
} catch (err) { leave(); label.textContent = err.message; }
};
function leave() {
room?.disconnect(); room = null;
btn.textContent = 'Start'; label.textContent = 'Talk to Lin';
}
</script>
</body>
</html>
用大白話解釋原理
兩個程式、兩個終端機、一個文字檔、一個工具。
agent.py 是語音 + avatar 引擎,版本 3 在裏面的唯一改動就是
show_section 工具。
server.py 是一個很小的 aiohttp 網頁伺服器,負責提供頁面,
並在每次到訪時簽發一個短暫有效的 LiveKit 存取權杖。
FAQs.txt 是知識庫 — 代理每次通話都會重新讀取它,
把內容以 {faqs} 注入提示詞。
頁面就是普通頁面。index.html 是一個普通的餐廳網站,
有三個以 id 屬性標記的部份。avatar 小工具浮在角落,覆蓋在頁面之上。
頁面本身沒有任何特別 — 這正是重點:你可以把同樣的小工具放進任何
你已經擁有的網站。
由 LLM 決定何時捲動。沒有人寫「如果問題包含 hours 這個字, 就捲動」。模型閱讀提示詞中的小規則手冊,理解客人的問題,並選擇呼叫工具 — 就像它選擇說哪些字一樣。如果問題不在 FAQs 裏,它根本不會呼叫工具。
訊息經數據頻道傳送。LiveKit 房間不只傳送語音和影像,
還可以在參與者之間傳送小文字訊息。代理把捲動指令發佈到名為 "ui"
的頻道,只有瀏覽器在監聽。整個過程 — 決定、訊息、捲動 —
在 Lin 說到答案的第二個字之前已經完成。
冷啟動重試。Synthesia 服務偶爾需要幾秒來啟動 avatar 工作階段, 所以代理最多重試三次才放棄。這就是為甚麼第一次點擊 Start 會感覺慢 — 它不是壞了,只是在熱身。
版本 2 與版本 3 一覽
| 版本 2 | 版本 3 | |
|---|---|---|
| 知識存放在 | 文字檔(FAQs.txt) |
文字檔(FAQs.txt) |
| 編輯知識需要 | 儲存檔案 + 新通話 | 儲存檔案 + 新通話 |
| 瀏覽器頁面 | 只有影片 + Start 按鈕 | 一個有章節的真正網頁 |
| Avatar 能操作頁面 | 不能 | 能 — 捲動並標示(show_section 工具) |
| 運行命令 | 兩個終端機,相同 | 兩個終端機,相同 |
限制(版本 3)
- Lin 仍然只知道 FAQs.txt 裏的內容。純文字檔方便快速更新, 但不能做計算,也不能查詢實時資訊。如果你想要天氣、股價或日曆預約, 下一步是加入更多工具或 RAG。
- 捲動工具只認識三個部份。要加第四個,必須同時改三個地方:
提示詞的規則手冊、
agent.py的SECTIONS集合, 以及index.html中對應的id。漏了一個, 工具會靜靜地不做任何事(或者模型用有效名稱重試)。 - 你需要兩個帳戶(LiveKit 和 Synthesia)。LiveKit Cloud 的 Inference 服務涵蓋 STT、LLM 和 TTS(包括 Cartesia 和 Deepgram 的聲音), 所以你不需要另外開服務商帳戶。Synthesia 提供免費的 Basic 計劃 (截至 2026 年 11 月撰寫時),內含 Interactive Avatar 及 1 個並行工作階段; 付費計劃會提高上限並增加點數。
- 兩個終端機的工作流程。你必須分別啟動
agent.py和server.py。做示範沒有問題,但正式部署會把它們交給單一監督程式管理, 或者索性只跑在 LiveKit Cloud Agents 上。 - 網頁伺服器沒有身分驗證。
server.py為每位訪客簽發 全新的房間權杖,沒有登入。本地測試可以;切勿原樣部署到公開互聯網。
延伸閱讀
- livekit.io — LiveKit 官方主頁,有價格和文件。
- livekit/agents — LiveKit Agents 的 Python 儲存庫,有更多例子,包括 Synthesia。
- LiveKit Synthesia Avatar 文件 — 把 Synthesia avatar 接入 LiveKit Agents 的官方指南。
- synthesia.io — 建立和管理你的 avatars。
- 如何使用 LiveKit 和 Synthesia Avatar(版本 2)?(英文)
— 上一個版本,知識搬到
FAQs.txt,但頁面還不能作出反應。 - 如何使用 LiveKit 和 Synthesia Avatar(版本 1)?(英文) — 同一個 avatar 的簡化初版,知識寫死在 Python 裏。
- 如何使用 LiveKit 語音代理配天氣工具?(英文) — 另一個為代理加工具的例子,這次是呼叫外部 API。