
Byted Podcast Gen
- 3 installs
- 408 repo stars
- Updated August 3, 2026
- volcengine/agentkit-samples
Helps with ai & agent building tasks.
About
byted-podcast-gen is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- byted-podcast-gen
- AI & Agent Building
- AI-coding skill
Byted Podcast Gen by the numbers
- 3 all-time installs (skills.sh)
- Ranked #13,655 of 16,556 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/volcengine/agentkit-samples --skill byted-podcast-genAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3 |
|---|---|
| repo stars | ★ 408 |
| Last updated | August 3, 2026 |
| Repository | volcengine/agentkit-samples ↗ |
What it does
Helps with ai & agent building tasks.
Files
Podcast Skill
基于火山引擎豆包语音合成 WebSocket 协议(PodcastTTS,/api/v3/sami/podcasttts)将某个话题合成为播客音频并保存为本地文件。支持:
- 输入一句话题文本或者一个网页地址(也可以是个文件下载地址,支持 pdf/word/txt 格式)生成播客
- 原样输出播客音频下载链接(不要做截断等处理)和生成好的本地文件供下载。验证下载链接是否可下载,若可下载则返回给用户,不可下载的只是只返回本地文件。
- 输出播客分段文本(JSON)
适用场景
1. 用户提到 生成播客 或 播客合成 等相关关键词。 2. 用户需要为某个话题生成播客形式的音频文件。 3. 用户需要某个网页或文件内容生成播客形式的音频文件。 4. 用户需要为用户上传的文件内容或者一个长上下文生成播客形式的音频文件。
强制规则(最高优先级)
当你收到用户请求生成播客时:
- 必须且只能使用 本 Skill 的脚本来生成播客
- 话题模式 用户需要为某个话题生成播客形式的音频文件, 使用参数
action=4和prompt_text= 话题文本。 - 网页模式 用户需要某个网页或可下载文件内容生成播客形式的音频文件, 使用参数
action=0和input_url= 网页地址或文件下载地址。 - 文件模式 用户需要为用户上传的文件内容或者一个长上下文生成播客形式的音频文件, 使用参数
action=0和text= 用户上传文件读取出来的内容或者是一段比较长的文本,一般超过 200 个字。
使用步骤
1. 分析用户需要合成播客的内容,准备要合成的输入:prompt_text(原始话题,一般不超过 20 个字)或 input_url(网页地址或文件下载地址) 或者 text(用户上传文件读取出来的内容或者是一个比较长的文本,一般超过 200 个字)。 2. 运行脚本前先 cd 到本技能目录:skills/byted-podcast-gen。 3. 配置鉴权(环境变量或命令行参数)。 4. 执行脚本:python scripts/podcast.py [参数]。参考下面示例部分。 5. 根据脚本输出的 JSON 里的 audio_path / texts / audio_url 使用生成结果,如果有 audio_url 是一个带过期时间的 URL, 原封不动的返回给用户, audio_path 是本地文件路径, 可以给用户提供下载。
脚本参数
| 参数 | 简写 | 必填 | 说明 |
|---|---|---|---|
--text | 否 | 输入原始长文本(action=0 时使用) | |
--input_url | 否 | 输入文本的 URL(action=0 时使用,二选一) | |
--prompt_text | 否 | 提示词文本(action=4 时必填) | |
--action | 否 | 播客类型:0(原始文本/URL)、4(prompt);默认 4 | |
--speaker_info | 否 | 说话人配置 JSON(默认 {"random_order":false}) | |
--encoding | 否 | 音频格式:mp3(默认)、wav、ogg_opus | |
--output | 否 | 最终音频输出文件路径(默认自动生成到 output/) |
返回值说明
脚本输出 JSON,包含:
status:"success"或"error"task_id: 任务标识(用于定位一次生成任务)audio_path: 最终音频本地路径texts: 分段文本 JSON 字符串,每个发音人对应的文本列表。audio_url: 服务端返回的音频下载地址error: 失败时的错误信息
错误处理
- 若报错提示缺少
MODEL_SPEECH_API_KEY:检查环境变量或命令行参数是否已配置,不存在的时候提示用户输入, 然后设置到环境变量。 - 若收到服务端错误(
MsgType.Error):根据错误信息检查账号权限、资源 ID、输入内容及是否已开通服务。 - 若收到服务端错误包含关键字
quota说明当前账号已超量,需升级火山引擎豆包语音的播客服务。 - python 执行缺少相关 package 时,需要先安装依赖:
pip install -r requirements.txt
参考文档
示例
# 基于话题生成播客音频
ptompt_text="豆包语音合成服务"
python scripts/podcast.py --prompt_text $ptompt_text --action 4
# 基于网页内容生成播客音频
url="https://www.volcengine.com/docs/6561/1668014?lang=zh"
python scripts/podcast.py --input_url $url --action 0
# 基于长文本内容生成播客音频
text="欢迎收听本期节目,我们聊聊人工智能的关键拐点……"
python scripts/podcast.py --text $text --action 0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
websockets>=12.0
import json
import os
import urllib.error
import urllib.request
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
def _build_action_url(base: str, action: str, version: str = "2025-05-20") -> str:
base = (base or "").strip()
if not base:
return ""
parsed = urlparse(base)
path = parsed.path or "/"
if not path.endswith("/"):
path = f"{path}/"
query = dict(parse_qsl(parsed.query))
query["Action"] = action
query["Version"] = version
return urlunparse(parsed._replace(path=path, query=urlencode(query)))
def _extract_json(text: str) -> dict | None:
if not text:
return None
text = text.strip()
try:
return json.loads(text)
except Exception:
pass
start = text.find("{")
end = text.rfind("}")
if start == -1 or end == -1 or end <= start:
return None
try:
return json.loads(text[start : end + 1])
except Exception:
return None
def _post_json(url: str, headers: dict, payload: dict, timeout_s: int = 15) -> dict | None:
if not url:
return None
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(url, data=data, method="POST")
for k, v in (headers or {}).items():
if v is None:
continue
req.add_header(k, v)
try:
with urllib.request.urlopen(req, timeout=timeout_s) as resp:
body = resp.read().decode("utf-8", errors="replace")
return _extract_json(body)
except urllib.error.HTTPError as e:
try:
body = e.read().decode("utf-8", errors="replace")
return _extract_json(body)
except Exception:
return None
except Exception:
return None
def _dotenv_path() -> str:
return os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
def _load_dotenv_if_available(dotenv_path: str) -> None:
try:
from dotenv import load_dotenv # type: ignore
except Exception:
return
try:
load_dotenv(dotenv_path=dotenv_path, override=False)
except Exception:
return
def _persist_env_to_dotenv_if_available(dotenv_path: str, key: str, value: str) -> None:
value = (value or "").strip()
if not value:
return
try:
from dotenv import set_key # type: ignore
except Exception:
return
try:
os.makedirs(os.path.dirname(dotenv_path) or ".", exist_ok=True)
set_key(dotenv_path, key, value, quote_mode="never")
try:
os.chmod(dotenv_path, 0o600)
except Exception:
pass
except Exception:
return
def get_speech_api_key(project_name: str = "default", create_name: str = "arkclaw") -> str:
_load_dotenv_if_available(_dotenv_path())
speech_key = os.getenv("MODEL_SPEECH_API_KEY", "").strip()
if speech_key:
return speech_key
ark_key = os.getenv("ARK_SKILL_API_KEY", "").strip()
base = os.getenv("ARK_SKILL_API_BASE", "").strip()
if not ark_key or not base:
return ""
headers = {
"ServiceName": "speech_saas_prod",
"Authorization": f"Bearer {ark_key}",
"Content-Type": "application/json",
}
list_url = _build_action_url(base, "ListAPIKeys")
list_data = _post_json(
list_url,
headers=headers,
payload={"ProjectName": project_name, "OnlyAvailable": True},
)
if isinstance(list_data, dict):
api_keys = (list_data.get("Result") or {}).get("APIKeys") or []
if isinstance(api_keys, list) and api_keys:
first = api_keys[0] if isinstance(api_keys[0], dict) else {}
first_key = (first.get("APIKey") or "").strip()
if first_key:
os.environ["MODEL_SPEECH_API_KEY"] = first_key
_persist_env_to_dotenv_if_available(_dotenv_path(), "MODEL_SPEECH_API_KEY", first_key)
return first_key
create_url = _build_action_url(base, "CreateAPIKey")
create_data = _post_json(
create_url,
headers=headers,
payload={"ProjectName": project_name, "Name": create_name},
)
if isinstance(create_data, dict):
created_key = ((create_data.get("Result") or {}).get("APIKey") or "").strip()
if created_key:
os.environ["MODEL_SPEECH_API_KEY"] = created_key
_persist_env_to_dotenv_if_available(_dotenv_path(), "MODEL_SPEECH_API_KEY", created_key)
return created_key
return ""
# -*- coding: utf-8 -*-
import argparse
import asyncio
import json
import logging
import os
import sys
import uuid
import websockets
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if _SCRIPT_DIR not in sys.path:
sys.path.insert(0, _SCRIPT_DIR)
from api_key import get_speech_api_key
from protocols import (EventType, MsgType, finish_connection, # noqa: E402
finish_session, receive_message, start_connection,
start_session, wait_for_event)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("PodcastTTS")
ENDPOINT = "wss://openspeech.bytedance.com/api/v3/sami/podcasttts"
def _load_json_value(value: str):
if value is None:
return None
value = value.strip()
if not value:
return None
if os.path.exists(value):
with open(value, "r", encoding="utf-8") as f:
return json.load(f)
return json.loads(value)
def _output_dir_from_output_path(output_path: str) -> str:
if output_path:
d = os.path.dirname(output_path)
return d if d else "output"
return "output"
def _final_extension(encoding: str) -> str:
return "ogg" if encoding == "ogg_opus" else encoding
async def _generate(args) -> dict:
api_key = get_speech_api_key()
if not api_key:
raise ValueError("Missing MODEL_SPEECH_API_KEY")
resource_id ="volc.service_type.10050"
endpoint = ENDPOINT
return_audio_url = True
skip_round_audio_save = True
if args.action == 0 and not (args.text or args.input_url):
raise ValueError("action=0 requires --text or --input_url")
if args.action == 3 and not args.nlp_texts:
raise ValueError("action=3 requires --nlp_texts")
if args.action == 4 and not args.prompt_text:
raise ValueError("action=4 requires --prompt_text")
headers = {
"X-Api-Key": api_key,
"X-Api-Resource-Id": resource_id,
"X-Api-Connect-Id": str(uuid.uuid4()),
}
output_dir = _output_dir_from_output_path(args.output)
os.makedirs(output_dir, exist_ok=True)
task_id = str(uuid.uuid4())
session_id = str(uuid.uuid4())
speaker_info = _load_json_value(args.speaker_info) if args.speaker_info else None
nlp_texts = _load_json_value(args.nlp_texts) if args.nlp_texts else None
req_params = {
"input_id": args.input_id,
"input_text": args.text,
"nlp_texts": nlp_texts,
"prompt_text": args.prompt_text,
"action": args.action,
"use_head_music": args.use_head_music,
"use_tail_music": args.use_tail_music,
"aigc_watermark": args.aigc_watermark,
"input_info": {
"input_url": args.input_url,
"return_audio_url": return_audio_url,
"only_nlp_text": args.only_nlp_text,
},
"speaker_info": speaker_info,
"audio_config": {
"format": args.encoding,
"sample_rate": 24000,
"speech_rate": 0,
},
}
podcast_audio = bytearray()
round_audio = bytearray()
podcast_texts = []
audio_received = False
current_round = 0
current_speaker = "speaker"
podcast_end_payload = None
async with websockets.connect(endpoint, additional_headers=headers) as websocket:
await start_connection(websocket)
await wait_for_event(websocket, MsgType.FullServerResponse, EventType.ConnectionStarted)
await start_session(websocket, json.dumps(req_params, ensure_ascii=False).encode("utf-8"), session_id)
await wait_for_event(websocket, MsgType.FullServerResponse, EventType.SessionStarted)
await finish_session(websocket, session_id)
while True:
msg = await receive_message(websocket)
if msg.type == MsgType.AudioOnlyServer and msg.event == EventType.PodcastRoundResponse:
if msg.payload:
audio_received = True
round_audio.extend(msg.payload)
continue
if msg.type == MsgType.Error:
raise RuntimeError(msg.payload.decode("utf-8", errors="replace"))
if msg.type == MsgType.FullServerResponse:
if msg.event == EventType.PodcastRoundStart:
data = json.loads(msg.payload.decode("utf-8", errors="replace"))
if data.get("text"):
podcast_texts.append({"text": data.get("text"), "speaker": data.get("speaker")})
current_speaker = data.get("speaker") or "speaker"
current_round = data.get("round_id") if data.get("round_id") is not None else 0
continue
if msg.event == EventType.PodcastRoundEnd:
data = json.loads(msg.payload.decode("utf-8", errors="replace"))
if data.get("is_error"):
raise RuntimeError(json.dumps(data, ensure_ascii=False))
if round_audio:
if not skip_round_audio_save:
round_path = os.path.join(
output_dir,
f"{current_speaker}_{current_round}.{_final_extension(args.encoding)}",
)
with open(round_path, "wb") as f:
f.write(round_audio)
podcast_audio.extend(round_audio)
round_audio.clear()
continue
if msg.event == EventType.PodcastEnd:
podcast_end_payload = json.loads(msg.payload.decode("utf-8", errors="replace"))
continue
if msg.event == EventType.SessionFinished:
break
await finish_connection(websocket)
await wait_for_event(websocket, MsgType.FullServerResponse, EventType.ConnectionFinished)
result = {"status": "success", "task_id": session_id, "encoding": args.encoding}
if podcast_texts:
result["texts"] = json.dumps(podcast_texts, ensure_ascii=False, indent=2)
if args.only_nlp_text:
return result
if not audio_received:
raise RuntimeError("No audio data received")
if podcast_audio:
audio_path = args.output or os.path.join(output_dir, f"podcast_{session_id}.{_final_extension(args.encoding)}")
with open(audio_path, "wb") as f:
f.write(podcast_audio)
result["audio_path"] = audio_path
if return_audio_url and isinstance(podcast_end_payload, dict):
audio_url = podcast_end_payload.get("meta_info", {}).get("audio_url")
if audio_url:
result["audio_url"] = audio_url
return result
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument("--action", default=4, type=int, choices=[0,4], help="Podcast type")
parser.add_argument("--text", default="", help="Input text (action=0)")
parser.add_argument("--input_url", default="", help="Input text URL (action=0)")
parser.add_argument("--nlp_texts", default="", help="NLP texts JSON string or JSON file path (action=3)")
parser.add_argument("--prompt_text", default="", help="Prompt text (action=4)")
parser.add_argument("--encoding", default="mp3", choices=["mp3", "wav", "ogg_opus"], help="Audio format")
parser.add_argument("--input_id", default="podcast_input", help="Unique input identifier")
parser.add_argument("--speaker_info", default='{"random_order":false}', help="Speaker info JSON")
parser.add_argument("--use_head_music", action="store_true", help="Enable head music")
parser.add_argument("--use_tail_music", action="store_true", help="Enable tail music")
parser.add_argument("--aigc_watermark", action="store_true", help="Enable aigc watermark")
parser.add_argument("--only_nlp_text", action="store_true", help="Only output podcast texts")
parser.add_argument("--output", default="", help="Final audio output path")
parser.add_argument("--texts_output", default="", help="Podcast texts output path")
return parser
def main() -> int:
args = _build_parser().parse_args()
try:
result = asyncio.run(_generate(args))
print(json.dumps(result, ensure_ascii=False))
return 0
except Exception as e:
print(json.dumps({"status": "error", "error": str(e)}, ensure_ascii=False))
return 1
if __name__ == "__main__":
raise SystemExit(main())
from .protocols import (
CompressionBits,
EventType,
HeaderSizeBits,
Message,
MsgType,
MsgTypeFlagBits,
SerializationBits,
VersionBits,
audio_only_client,
cancel_session,
finish_connection,
finish_session,
full_client_request,
receive_message,
start_connection,
start_session,
task_request,
wait_for_event,
)
__all__ = [
"CompressionBits",
"EventType",
"HeaderSizeBits",
"Message",
"MsgType",
"MsgTypeFlagBits",
"SerializationBits",
"VersionBits",
"audio_only_client",
"cancel_session",
"finish_connection",
"finish_session",
"full_client_request",
"receive_message",
"start_connection",
"start_session",
"task_request",
"wait_for_event",
]
import io
import logging
import struct
from dataclasses import dataclass
from enum import IntEnum
from typing import Callable, List
import websockets
logger = logging.getLogger(__name__)
class MsgType(IntEnum):
"""Message type enumeration"""
Invalid = 0
FullClientRequest = 0b1
AudioOnlyClient = 0b10
FullServerResponse = 0b1001
AudioOnlyServer = 0b1011
FrontEndResultServer = 0b1100
Error = 0b1111
# Alias
ServerACK = AudioOnlyServer
def __str__(self) -> str:
return self.name if self.name else f"MsgType({self.value})"
class MsgTypeFlagBits(IntEnum):
"""Message type flag bits"""
NoSeq = 0 # Non-terminal packet with no sequence
PositiveSeq = 0b1 # Non-terminal packet with sequence > 0
LastNoSeq = 0b10 # Last packet with no sequence
NegativeSeq = 0b11 # Last packet with sequence < 0
WithEvent = 0b100 # Payload contains event number (int32)
class VersionBits(IntEnum):
"""Version bits"""
Version1 = 1
Version2 = 2
Version3 = 3
Version4 = 4
class HeaderSizeBits(IntEnum):
"""Header size bits"""
HeaderSize4 = 1
HeaderSize8 = 2
HeaderSize12 = 3
HeaderSize16 = 4
class SerializationBits(IntEnum):
"""Serialization method bits"""
Raw = 0
JSON = 0b1
Thrift = 0b11
Custom = 0b1111
class CompressionBits(IntEnum):
"""Compression method bits"""
None_ = 0
Gzip = 0b1
Custom = 0b1111
class EventType(IntEnum):
"""Event type enumeration"""
None_ = 0 # Default event
# 1 ~ 49 Upstream Connection events
StartConnection = 1
StartTask = 1 # Alias of StartConnection
FinishConnection = 2
FinishTask = 2 # Alias of FinishConnection
# 50 ~ 99 Downstream Connection events
ConnectionStarted = 50 # Connection established successfully
TaskStarted = 50 # Alias of ConnectionStarted
ConnectionFailed = 51 # Connection failed (possibly due to authentication failure)
TaskFailed = 51 # Alias of ConnectionFailed
ConnectionFinished = 52 # Connection ended
TaskFinished = 52 # Alias of ConnectionFinished
# 100 ~ 149 Upstream Session events
StartSession = 100
CancelSession = 101
FinishSession = 102
# 150 ~ 199 Downstream Session events
SessionStarted = 150
SessionCanceled = 151
SessionFinished = 152
SessionFailed = 153
UsageResponse = 154 # Usage response
ChargeData = 154 # Alias of UsageResponse
# 200 ~ 249 Upstream general events
TaskRequest = 200
UpdateConfig = 201
# 250 ~ 299 Downstream general events
AudioMuted = 250
# 300 ~ 349 Upstream TTS events
SayHello = 300
# 350 ~ 399 Downstream TTS events
TTSSentenceStart = 350
TTSSentenceEnd = 351
TTSResponse = 352
TTSEnded = 359
PodcastRoundStart = 360
PodcastRoundResponse = 361
PodcastRoundEnd = 362
PodcastEnd = 363
# 450 ~ 499 Downstream ASR events
ASRInfo = 450
ASRResponse = 451
ASREnded = 459
# 500 ~ 549 Upstream dialogue events
ChatTTSText = 500 # (Ground-Truth-Alignment) text for speech synthesis
# 550 ~ 599 Downstream dialogue events
ChatResponse = 550
ChatEnded = 559
# 650 ~ 699 Downstream dialogue events
# Events for source (original) language subtitle
SourceSubtitleStart = 650
SourceSubtitleResponse = 651
SourceSubtitleEnd = 652
# Events for target (translation) language subtitle
TranslationSubtitleStart = 653
TranslationSubtitleResponse = 654
TranslationSubtitleEnd = 655
def __str__(self) -> str:
return self.name if self.name else f"EventType({self.value})"
@dataclass
class Message:
"""Message object
Message format:
0 1 2 3
| 0 1 2 3 4 5 6 7 | 0 1 2 3 4 5 6 7 | 0 1 2 3 4 5 6 7 | 0 1 2 3 4 5 6 7 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Version | Header Size | Msg Type | Flags |
| (4 bits) | (4 bits) | (4 bits) | (4 bits) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Serialization | Compression | Reserved |
| (4 bits) | (4 bits) | (8 bits) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| Optional Header Extensions |
| (if Header Size > 1) |
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| Payload |
| (variable length) |
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
"""
version: VersionBits = VersionBits.Version1
header_size: HeaderSizeBits = HeaderSizeBits.HeaderSize4
type: MsgType = MsgType.Invalid
flag: MsgTypeFlagBits = MsgTypeFlagBits.NoSeq
serialization: SerializationBits = SerializationBits.JSON
compression: CompressionBits = CompressionBits.None_
event: EventType = EventType.None_
session_id: str = ""
connect_id: str = ""
sequence: int = 0
error_code: int = 0
payload: bytes = b""
@classmethod
def from_bytes(cls, data: bytes) -> "Message":
"""Create message object from bytes"""
if len(data) < 3:
raise ValueError(
f"Data too short: expected at least 3 bytes, got {len(data)}"
)
type_and_flag = data[1]
msg_type = MsgType(type_and_flag >> 4)
flag = MsgTypeFlagBits(type_and_flag & 0b00001111)
msg = cls(type=msg_type, flag=flag)
msg.unmarshal(data)
return msg
def marshal(self) -> bytes:
"""Serialize message to bytes"""
buffer = io.BytesIO()
# Write header
header = [
(self.version << 4) | self.header_size,
(self.type << 4) | self.flag,
(self.serialization << 4) | self.compression,
]
header_size = 4 * self.header_size
if padding := header_size - len(header):
header.extend([0] * padding)
buffer.write(bytes(header))
# Write other fields
writers = self._get_writers()
for writer in writers:
writer(buffer)
return buffer.getvalue()
def unmarshal(self, data: bytes) -> None:
"""Deserialize message from bytes"""
buffer = io.BytesIO(data)
# Read version and header size
version_and_header_size = buffer.read(1)[0]
self.version = VersionBits(version_and_header_size >> 4)
self.header_size = HeaderSizeBits(version_and_header_size & 0b00001111)
# Skip second byte
buffer.read(1)
# Read serialization and compression methods
serialization_compression = buffer.read(1)[0]
self.serialization = SerializationBits(serialization_compression >> 4)
self.compression = CompressionBits(serialization_compression & 0b00001111)
# Skip header padding
header_size = 4 * self.header_size
read_size = 3
if padding_size := header_size - read_size:
buffer.read(padding_size)
# Read other fields
readers = self._get_readers()
for reader in readers:
reader(buffer)
# Check for remaining data
remaining = buffer.read()
if remaining:
raise ValueError(f"Unexpected data after message: {remaining}")
def _get_writers(self) -> List[Callable[[io.BytesIO], None]]:
"""Get list of writer functions"""
writers = []
if self.flag == MsgTypeFlagBits.WithEvent:
writers.extend([self._write_event, self._write_session_id])
if self.type in [
MsgType.FullClientRequest,
MsgType.FullServerResponse,
MsgType.FrontEndResultServer,
MsgType.AudioOnlyClient,
MsgType.AudioOnlyServer,
]:
if self.flag in [MsgTypeFlagBits.PositiveSeq, MsgTypeFlagBits.NegativeSeq]:
writers.append(self._write_sequence)
elif self.type == MsgType.Error:
writers.append(self._write_error_code)
else:
raise ValueError(f"Unsupported message type: {self.type}")
writers.append(self._write_payload)
return writers
def _get_readers(self) -> List[Callable[[io.BytesIO], None]]:
"""Get list of reader functions"""
readers = []
if self.type in [
MsgType.FullClientRequest,
MsgType.FullServerResponse,
MsgType.FrontEndResultServer,
MsgType.AudioOnlyClient,
MsgType.AudioOnlyServer,
]:
if self.flag in [MsgTypeFlagBits.PositiveSeq, MsgTypeFlagBits.NegativeSeq]:
readers.append(self._read_sequence)
elif self.type == MsgType.Error:
readers.append(self._read_error_code)
else:
raise ValueError(f"Unsupported message type: {self.type}")
if self.flag == MsgTypeFlagBits.WithEvent:
readers.extend(
[self._read_event, self._read_session_id, self._read_connect_id]
)
readers.append(self._read_payload)
return readers
def _write_event(self, buffer: io.BytesIO) -> None:
"""Write event"""
buffer.write(struct.pack(">i", self.event))
def _write_session_id(self, buffer: io.BytesIO) -> None:
"""Write session ID"""
if self.event in [
EventType.StartConnection,
EventType.FinishConnection,
EventType.ConnectionStarted,
EventType.ConnectionFailed,
]:
return
session_id_bytes = self.session_id.encode("utf-8")
size = len(session_id_bytes)
if size > 0xFFFFFFFF:
raise ValueError(f"Session ID size ({size}) exceeds max(uint32)")
buffer.write(struct.pack(">I", size))
if size > 0:
buffer.write(session_id_bytes)
def _write_sequence(self, buffer: io.BytesIO) -> None:
"""Write sequence number"""
buffer.write(struct.pack(">i", self.sequence))
def _write_error_code(self, buffer: io.BytesIO) -> None:
"""Write error code"""
buffer.write(struct.pack(">I", self.error_code))
def _write_payload(self, buffer: io.BytesIO) -> None:
"""Write payload"""
size = len(self.payload)
if size > 0xFFFFFFFF:
raise ValueError(f"Payload size ({size}) exceeds max(uint32)")
buffer.write(struct.pack(">I", size))
buffer.write(self.payload)
def _read_event(self, buffer: io.BytesIO) -> None:
"""Read event"""
event_bytes = buffer.read(4)
if event_bytes:
self.event = EventType(struct.unpack(">i", event_bytes)[0])
def _read_session_id(self, buffer: io.BytesIO) -> None:
"""Read session ID"""
if self.event in [
EventType.StartConnection,
EventType.FinishConnection,
EventType.ConnectionStarted,
EventType.ConnectionFailed,
EventType.ConnectionFinished,
]:
return
size_bytes = buffer.read(4)
if size_bytes:
size = struct.unpack(">I", size_bytes)[0]
if size > 0:
session_id_bytes = buffer.read(size)
if len(session_id_bytes) == size:
self.session_id = session_id_bytes.decode("utf-8")
def _read_connect_id(self, buffer: io.BytesIO) -> None:
"""Read connection ID"""
if self.event in [
EventType.ConnectionStarted,
EventType.ConnectionFailed,
EventType.ConnectionFinished,
]:
size_bytes = buffer.read(4)
if size_bytes:
size = struct.unpack(">I", size_bytes)[0]
if size > 0:
self.connect_id = buffer.read(size).decode("utf-8")
def _read_sequence(self, buffer: io.BytesIO) -> None:
"""Read sequence number"""
sequence_bytes = buffer.read(4)
if sequence_bytes:
self.sequence = struct.unpack(">i", sequence_bytes)[0]
def _read_error_code(self, buffer: io.BytesIO) -> None:
"""Read error code"""
error_code_bytes = buffer.read(4)
if error_code_bytes:
self.error_code = struct.unpack(">I", error_code_bytes)[0]
def _read_payload(self, buffer: io.BytesIO) -> None:
"""Read payload"""
size_bytes = buffer.read(4)
if size_bytes:
size = struct.unpack(">I", size_bytes)[0]
if size > 0:
self.payload = buffer.read(size)
def __str__(self) -> str:
"""String representation"""
if self.type in [MsgType.AudioOnlyServer, MsgType.AudioOnlyClient]:
if self.flag in [MsgTypeFlagBits.PositiveSeq, MsgTypeFlagBits.NegativeSeq]:
return f"MsgType: {self.type}, EventType:{self.event}, Sequence: {self.sequence}, PayloadSize: {len(self.payload)}"
return f"MsgType: {self.type}, EventType:{self.event}, PayloadSize: {len(self.payload)}"
elif self.type == MsgType.Error:
return f"MsgType: {self.type}, EventType:{self.event}, ErrorCode: {self.error_code}, Payload: {self.payload.decode('utf-8', 'ignore')}"
else:
if self.flag in [MsgTypeFlagBits.PositiveSeq, MsgTypeFlagBits.NegativeSeq]:
return f"MsgType: {self.type}, EventType:{self.event}, Sequence: {self.sequence}, Payload: {self.payload.decode('utf-8', 'ignore')}"
return f"MsgType: {self.type}, EventType:{self.event}, Payload: {self.payload.decode('utf-8', 'ignore')}"
async def receive_message(websocket: websockets.WebSocketClientProtocol) -> Message:
"""Receive message from websocket"""
try:
data = await websocket.recv()
if isinstance(data, str):
raise ValueError(f"Unexpected text message: {data}")
elif isinstance(data, bytes):
msg = Message.from_bytes(data)
logger.info(f"Received: {msg}")
return msg
else:
raise ValueError(f"Unexpected message type: {type(data)}")
except Exception as e:
logger.error(f"Failed to receive message: {e}")
raise
async def wait_for_event(
websocket: websockets.WebSocketClientProtocol,
msg_type: MsgType,
event_type: EventType,
) -> Message:
"""Wait for specific event"""
while True:
msg = await receive_message(websocket)
if msg.type != msg_type or msg.event != event_type:
raise ValueError(f"Unexpected message: {msg}")
if msg.type == msg_type and msg.event == event_type:
return msg
async def full_client_request(
websocket: websockets.WebSocketClientProtocol, payload: bytes
) -> None:
"""Send full client message"""
msg = Message(type=MsgType.FullClientRequest, flag=MsgTypeFlagBits.NoSeq)
msg.payload = payload
logger.info(f"Sending: {msg}")
await websocket.send(msg.marshal())
async def audio_only_client(
websocket: websockets.WebSocketClientProtocol, payload: bytes, flag: MsgTypeFlagBits
) -> None:
"""Send audio-only client message"""
msg = Message(type=MsgType.AudioOnlyClient, flag=flag)
msg.payload = payload
logger.info(f"Sending: {msg}")
await websocket.send(msg.marshal())
async def start_connection(websocket: websockets.WebSocketClientProtocol) -> None:
"""Start connection"""
msg = Message(type=MsgType.FullClientRequest, flag=MsgTypeFlagBits.WithEvent)
msg.event = EventType.StartConnection
msg.payload = b"{}"
logger.info(f"Sending: {msg}")
await websocket.send(msg.marshal())
async def finish_connection(websocket: websockets.WebSocketClientProtocol) -> None:
"""Finish connection"""
msg = Message(type=MsgType.FullClientRequest, flag=MsgTypeFlagBits.WithEvent)
msg.event = EventType.FinishConnection
msg.payload = b"{}"
logger.info(f"Sending: {msg}")
await websocket.send(msg.marshal())
async def start_session(
websocket: websockets.WebSocketClientProtocol, payload: bytes, session_id: str
) -> None:
"""Start session"""
msg = Message(type=MsgType.FullClientRequest, flag=MsgTypeFlagBits.WithEvent)
msg.event = EventType.StartSession
msg.session_id = session_id
msg.payload = payload
logger.info(f"Sending: {msg}")
await websocket.send(msg.marshal())
async def finish_session(
websocket: websockets.WebSocketClientProtocol, session_id: str
) -> None:
"""Finish session"""
msg = Message(type=MsgType.FullClientRequest, flag=MsgTypeFlagBits.WithEvent)
msg.event = EventType.FinishSession
msg.session_id = session_id
msg.payload = b"{}"
logger.info(f"Sending: {msg}")
await websocket.send(msg.marshal())
async def cancel_session(
websocket: websockets.WebSocketClientProtocol, session_id: str
) -> None:
"""Cancel session"""
msg = Message(type=MsgType.FullClientRequest, flag=MsgTypeFlagBits.WithEvent)
msg.event = EventType.CancelSession
msg.session_id = session_id
msg.payload = b"{}"
logger.info(f"Sending: {msg}")
await websocket.send(msg.marshal())
async def task_request(
websocket: websockets.WebSocketClientProtocol, payload: bytes, session_id: str
) -> None:
"""Send task request"""
msg = Message(type=MsgType.FullClientRequest, flag=MsgTypeFlagBits.WithEvent)
msg.event = EventType.TaskRequest
msg.session_id = session_id
msg.payload = payload
logger.info(f"Sending: {msg}")
await websocket.send(msg.marshal())