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)

延伸阅读