495
English 繁體中文 简体中文

如何用 LiveKit + Synthesia 數位人(版本 2)?

林邦源博士 · AI 筆記 · 2026 年 11 月 6 日 · 約 7 分鐘閱讀

Synthesia 能生成逼真的 AI 數位人,即時說話、即時對口型。 LiveKit 則把數位人和語音代理綁在一起:麥克風 → 語音辨識 → LLM → 文字轉語音 → 數位人。

版本 1 裡數位人知道的所有東西都硬寫在 Python prompt 裡。這樣程式碼好讀,但每次想讓 Lin 多知道一件事, 都得改 Python、再重啟。

版本 2 把知識搬到一個純文字檔,叫做 FAQs.txt for frequently asked questions。 改完檔案、打開一通新的通話,數位人就會學到新內容——不用改程式碼。Lin 現在能回答四個問題 (營業時間、主打菜、地址、回覆其他問題的備案答案),不再只限一個。

整條流水線

瀏覽器麥克風 → VAD → STT → turn detection → LLM → TTS → Synthesia 數位人 → 瀏覽器視訊

五塊元件透過 LiveKit 的即時傳輸連在一起。 VAD(語音活動偵測)負責監聽你什麼時候開口、什麼時候停下, STT 把語音轉文字,LLM 負責回答, TTS 把回答念出來,Synthesia 渲染出跟語音同步的臉。 全部跑在 LiveKit Cloud 上。

準備工作

設定 LiveKit Cloud

在 cloud.livekit.io 註冊登入。進入控制台,點 Projects → Create Project, 打開專案後點 Keys,複製這三個值:

設定 Synthesia

登入 app.synthesia.io。 進入 Avatars,選一個或新建一個數位人——每個數位人都有一個 UUID, 打開它時 URL 裡就能看到(像 3190429b-1eda-4151-bf24-96162e405840), 這就是 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=3190429b-1eda-4151-bf24-96162e405840

注意:絕對不要把 .env 傳到 GitHub 或任何公開網站——裡面是你的真實憑證。

在自己電腦上執行

下載 zip 檔案, 解壓縮到一個資料夾裡。zip 裡包含 agent.py、server.py、 index.html、FAQs.txt、pyproject.toml 和 README.md。 把你的 .env 憑證檔案放到同一資料夾(如上面所示)。然後在 Visual Studio Code 裡打開這個資料夾, 在兩個不同的終端機視窗裡分別執行:

終端機 1 —— 語音代理 + 數位人引擎:

uv sync
uv run agent.py dev

終端機 2 —— 瀏覽器頁面的 Web 伺服器:

uv run server.py

uv sync 只需要第一次跑——它會自動裝 Python 3.13 和所有相依套件。之後每次只要開兩個終端機分別執行 agent.py 和 server.py 就行。

在瀏覽器裡打開頁面

兩個終端機都跑起來之後,在 Chrome、Safari 或 Edge 裡打開 http://127.0.0.1:8080, 點 Start,允許麥克風權限,然後等個幾秒讓代理和數位人加入房間。 你應該能看到 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 都會重新讀取這個檔案,把 prompt 裡的 {faqs} 佔位符換成最新內容,才啟動 session。要給 Lin 加新知識, 只要加一組 Q&A、存檔、再打開一通新的通話就行——不用改 Python。

zip 裡的檔案

pyproject.toml

[project]
name = "folder-ai-avatar-v2"
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 os
from pathlib import Path

from dotenv import load_dotenv
from livekit.agents import Agent, AgentSession, JobContext, WorkerOptions, cli, 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 "3190429b-1eda-4151-bf24-96162e405840"
VOICE_ID = "db6b0ed5-d5d3-463d-ae85-518a07d3c2b4"

FAQS_FILE = Path(__file__).parent / "FAQs.txt"  # the avatar's knowledge

# {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."""


def prewarm(proc) -> None:
    proc.userdata["vad"] = silero.VAD.load()


async def entrypoint(ctx: JobContext) -> None:
    await ctx.connect()

    session = AgentSession(
        vad=ctx.proc.userdata["vad"],
        stt=inference.STT(model="cartesia/ink-2"),
        llm=inference.LLM(model="openai/gpt-4.1-mini"),
        tts=inference.TTS(model="cartesia/sonic-3.6", voice=VOICE_ID),
        turn_handling={"turn_detection": "stt"},
    )

    avatar = synthesia.AvatarSession(
        synthesia.AvatarConfig(avatar_ids=[AVATAR_ID]),
        join_timeout=60.0,
    )
    for attempt in range(3):
        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 FAQs fresh 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=Agent(instructions=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">
... (same as in English version above)

工作原理,大白話解釋

兩個程式,兩個終端機,一個文字檔。 agent.py 是語音 + 數位人引擎。 server.py 是一個小小的 aiohttp Web 伺服器,負責提供頁面,並在每次造訪時簽發一個短期有效的 LiveKit 存取權杖。 FAQs.txt 是知識庫——agent 每次都會重新讀取它,把內容塞進 prompt 裡的 {faqs}。

為什麼用文字檔? 不會寫程式的人也能維護它。餐廳經理、寫專題的學生、做教學 demo 的老師——都不用打開 Python 就能加一件事。規則只有一條:每組問答以 Q: 和 A: 各起一行,兩組之間空一行。

瀏覽器完全不知道數位人這回事。 index.html 只是加入一個 LiveKit 房間、播放所有收到的視訊軌—— 它不關心軌來自真實攝影機還是 Synthesia 數位人。數位人從 agent 內部把自己的視訊流傳出來, 房間設定裡 sync_streams=True 保證嘴型和音訊同步。

冷啟動自動重試。 Synthesia 服務偶爾會花幾秒鐘才能拉起一個數位人會話,所以 agent 會最多重試三次再放棄。 這就是為什麼第一次點 Start 會感覺慢——不是壞了,是在熱身。

版本 1 vs. 版本 2 一眼看懂

版本 1 版本 2
知識庫在哪裡 Python prompt(INSTRUCTIONS) 文字檔(FAQs.txt)
更新知識需要 改 Python + 重啟 存檔 + 打新的一通
問題數量 1(營業時間) 4(時間、菜、地址、備案答案)
執行指令 兩個終端機,一樣 兩個終端機,一樣

版本 2 的限制

延伸閱讀