English 繁體中文 简体中文

如何在網頁中使用 LiveKit 和 Synthesia Avatar(版本 4)——普通話?

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

在版本 2(英文)中,餐廳接待員 Lin 用一個純文字檔案裏的知識, 回答你口頭提出的問題。在版本 3中,她搬進了一個 真正的網頁:當她回答時,頁面會捲動到她正在講述的部份。

版本 4 再作一個改動:Lin 現在講普通話。你用普通話提問,她用普通話的聲音回答, 而頁面仍然會隨着她說話而捲動。有趣的地方是:她的知識檔案仍然是英文,網頁也是英文 — AI 模型即時把一切翻譯過來。

版本 3 與版本 4 一覽

版本 3版本 4
對話語言英文普通話
耳朵(語音轉文字)Cartesia ink-2Cartesia ink-whisper,設定為中文
聲音(文字轉語音)Cartesia sonic-3.6,聲音「Skylar」Cartesia sonic-3,聲音「Jing」(普通話)
判斷你何時說完由 STT 模型告知靜音偵測(VAD)
知識檔案 FAQs.txt英文英文 — 即時翻譯
網頁文字英文英文(不變)
頁面捲動並標示是(show_section 工具)是(show_section 工具)

開始之前你需要甚麼

在自己的電腦上運行

下載 zip 檔案並解壓到 一個資料夾。zip 內有 agent.py、server.py、index.html、 FAQs.txt、pyproject.toml 和 README.md。加入你自己的 .env 檔案,用與版本 3 相同的五把金鑰。

步驟 1:設定專案資料夾

六個檔案中有四個 — server.py、index.html、FAQs.txt 和 pyproject.toml — 與版本 3 完全相同,所以如果你已經有那個資料夾, 可以複製它,只替換 agent.py。

載有你五把秘密金鑰的 .env 檔案與版本 3 完全一樣。pyproject.toml 裏的套件也沒有改變 — 講中文的模型來自 LiveKit 已經連接的同一個 Cartesia 服務。

步驟 2:看看 agent.py — 有甚麼改變

這個檔案與版本 3 幾乎相同。只有四處改動,而全部都與語言有關。

改動 1:會聽中文的新耳朵

stt=inference.STT(model="cartesia/ink-whisper", language="zh"),

語音轉文字模型 — Lin 的耳朵 — 由 cartesia/ink-2 改為 cartesia/ink-whisper,並加上 language="zh" (zh 是中文的代碼)。這個模型聽普通話,並用中文字寫下你說的話。

這個切換是被迫的:ink-2 只懂英文,所以不能保留來處理普通話。 ink-whisper 才是能夠處理的多語言模型。

改動 2:新的普通話聲音

VOICE_ID = "6eb8965c-e295-47bd-a9e4-3eeebb3abcff"  # Cartesia "Jing", a Mandarin female voice
tts=inference.TTS(model="cartesia/sonic-3", voice=VOICE_ID, language="zh"),

文字轉語音的聲音改為 Jing,一把普通話女聲,同樣加上 language="zh"。數位人仍然像以前一樣透過 Synthesia 說話 — 只有她的聲音是新的。

改動 3:用另一種方式判斷你已經說完

turn_handling={
    "turn_detection": "vad",                        # have they finished? (ink-whisper can't tell, so use silence)
    "preemptive_generation": {"enabled": False},    # keep off when using tools
},

在版本 3 中,STT 模型本身會報告你何時說完一句話。新的 ink-whisper 模型做不到 — 與 ink-2 不同,它沒有輪次偵測的訊號 — 所以我們把 turn_detection 改為 "vad":程式現在只靠察覺一段沉默, 就判斷你已經說完。

改動 4:提示詞多了兩行

The guest speaks Putonghua (Mandarin Chinese). Always reply in Putonghua, written in
simplified Chinese characters, even though the FAQs below are in English.

這就是版本 4 的核心。FAQs.txt 裏的常見問題仍然是英文,所以你仍然可以 像以前一樣編輯它們。LLM 讀取英文答案,然後用普通話說出來。後備句子也略有改變:

Those are the only things you know. If the guest asks anything the FAQs do not
cover, give the answer to "Any other question?", translated into Putonghua.

而歡迎語現在也要求用普通話:

session.generate_reply(
    instructions="Welcome the guest to YouFantasy and invite them to ask a question, in one short sentence of Putonghua."
)

其他一切 — show_section 工具、數位人的重試迴圈、每次通話都重新讀取 FAQs.txt — 都與版本 3 相同。

步驟 3:完整的 agent.py

以下是完整檔案,讓你看清這四處改動的上下文:

"""Version 4: Lin speaks Putonghua. The guest asks in Putonghua and Lin answers in Putonghua.

The pipeline:
    mic -> VAD -> STT -> turn detection -> LLM (+ tools) -> TTS -> Synthesia avatar -> browser
    VAD: Voice Activity Detection, STT: Speech-to-Text, LLM: Large Language Model, TTS: Text-to-Speech

New in version 4: the ears and the voice change to models that handle Chinese, and
the prompt tells Lin to reply in Putonghua. FAQs.txt, the prompt and the web page
stay in English: the LLM translates on the fly.

Run:  uv run agent.py dev    (terminal 1)
      uv run server.py       (terminal 2, then open http://localhost:8080)
"""

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"  # must match server.py
AVATAR_ID = os.getenv("SYNTHESIA_AVATAR_ID") or "8788bef1-8020-46e0-a8f4-510ea9989b25"  # Jenny
VOICE_ID = "6eb8965c-e295-47bd-a9e4-3eeebb3abcff"  # Cartesia "Jing", a Mandarin female voice

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.

The guest speaks Putonghua (Mandarin Chinese). Always reply in Putonghua, written in
simplified Chinese characters, even though the FAQs below are in English.

Answer only from these FAQs:

{faqs}

Those are the only things you know. If the guest asks anything the FAQs do not
cover, give the answer to "Any other question?", translated into Putonghua.

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-whisper", language="zh"),            # Chinese speech -> text
        llm=inference.LLM(model="openai/gpt-4.1-mini"),                            # text -> reply (+ tool calls)
        tts=inference.TTS(model="cartesia/sonic-3", voice=VOICE_ID, language="zh"),  # Chinese reply -> speech
        turn_handling={
            "turn_detection": "vad",                        # have they finished? (ink-whisper can't tell, so use silence)
            "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 of Putonghua."
    )


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm, agent_name=AGENT_NAME, port=8081))

步驟 4:server.py、index.html 和 FAQs.txt — 沒有改動

server.py 與版本 3 是同一個檔案:它仍然在 / 提供頁面, 並且仍然在 /token 發出權杖。

index.html 保留相同的部份(hours、mains、 location)、相同的金色高亮外框,以及相同的 "ui" 數據頻道監聽器。 只有那一行介紹文字,現在邀請訪客用普通話提問:

<p>Ask Lin, our host, in Putonghua about our hours, our main courses or where to find us.</p>

頁面本身仍然是英文,這讓示範更容易跟隨:Lin 講中文,而英文頁面隨着她捲動。

FAQs.txt 同樣沒有被改動 — 同樣四組英文問答,由 LLM 在通話時翻譯。

步驟 5:安裝、設定你的金鑰、運行

與版本 3 完全相同。在專案資料夾中執行一次 uv sync,然後開兩個終端機:

uv run agent.py dev

然後在第二個終端機:

uv run server.py

步驟 6:開啟頁面,用普通話跟 Lin 說話

在瀏覽器開啟 http://localhost:8080。餐廳頁面會載入,數位人小工具在右下角。 點擊 Start 並允許咪高峰權限。

等候 Lin 的歡迎語,然後用普通話提問,例如:

接下來可以試試

下一步看甚麼