English 繁體中文 简体中文

如何在網頁中使用 LiveKit 和 Synthesia Avatar(版本 3)?

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

在版本 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 還在繼續說話。

你需要甚麼

設定 LiveKit Cloud

在 cloud.livekit.io 註冊。 在儀表板中點擊 Projects → Create Project,然後開啟 該專案並進入 Keys。複製三個數值:

設定 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)

延伸閱讀