> ## Documentation Index
> Fetch the complete documentation index at: https://docs.veadk.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# 语音识别

## 功能说明

对应工具标识 `speech_to_text`。

`speech_to_text` 调用火山引擎录音文件识别服务，把音频中的语音转写为文本，自动识别口语语种，返回全文、时长与带时间戳的分句结果。音频来源支持本地文件路径或可公开访问的 `http(s)` URL。

该工具为异步函数（`async def`），凭证独立于智能体推理模型，不依赖 `MODEL_AGENT_API_KEY`。

导入路径：`from veadk.tools.builtin_tools.speech_to_text import speech_to_text`

## 环境变量与前提

> [!WARNING]
>
> 附加要求：配置语音识别服务的 API Key。解析顺序为 `TOOL_SPEECH_TO_TEXT_API_KEY`、`TOOL_VESPEECH_API_KEY`，均未设置时回退到配置文件中的 `tool.vespeech.api_key`。

环境变量：

* `TOOL_SPEECH_TO_TEXT_API_KEY`：语音识别 API Key，优先级最高
* `TOOL_VESPEECH_API_KEY`：VeSpeech 服务 API Key，作为回退
* 配置文件中的 `tool.vespeech.api_key`：以上环境变量均未设置时使用

支持的音频格式为 WAV、MP3、OGG、OPUS，本地文件不超过 100 MB。

## 使用方法

```python title="examples/tools/speech_to_text/agent.py" lines theme={null}
import asyncio

from veadk import Agent, Runner
from veadk.memory.short_term_memory import ShortTermMemory
from veadk.tools.builtin_tools.speech_to_text import speech_to_text

agent = Agent(
    name="asr_agent",
    model_name="doubao-seed-2-1-pro-260628",
    description="An agent that transcribes speech audio.",
    instruction="用户给出音频文件或链接并要求转写时，调用 speech_to_text 工具。",
    tools=[speech_to_text],
)

runner = Runner(agent=agent, short_term_memory=ShortTermMemory())


async def main():
    response = await runner.run("把 /tmp/meeting.mp3 里的发言转成文字")
    print(response)


if __name__ == "__main__":
    asyncio.run(main())
```

直接调用：

```python lines theme={null}
import asyncio

from veadk.tools.builtin_tools.speech_to_text import speech_to_text


async def main():
    result = await speech_to_text("/tmp/meeting.mp3", timeout=600)
    if "error" in result:
        print("识别失败:", result["error"])
    else:
        print(result["duration_ms"], result["log_id"])
        print(result["text"])
        for utterance in result["utterances"]:
            print(utterance["start_time"], utterance["end_time"], utterance["text"])


asyncio.run(main())
```

## 参数

| 参数 | 类型 | 默认值 | 说明 |
| :- | :- | :- | :- |
| `audio` | `str` | 必填 | 本地音频文件路径或可公开访问的 `http(s)` URL |
| `timeout` | `int` | `300` | 请求超时秒数，取 1–600 |

成功返回 `{"text", "duration_ms", "utterances", "log_id"}`：

* `text`：完整转写文本，结果包含标点并对数字等口语表达做规范化。
* `duration_ms`：音频时长（毫秒）。
* `utterances`：分句结果列表，每项为 `{"start_time", "end_time", "text"}`，最多 200 条。
* `log_id`：服务端请求标识，可用于问题排查。

缺少 API Key、音频无法读取或服务返回错误时，结果中包含 `error`，部分失败结果同时返回 `log_id`。

## 额外说明

> [!NOTE]
>
> * 本地音频经 Base64 编码后随请求上传，文件越大请求体积越大；大文件建议先确认网络与超时设置。
> * 远程 URL 会先经过 SSRF 校验，私网与环回地址会被拦截，随后由识别服务端公网拉取，链接必须可被服务端访问。
> * 语种由服务自动检测，无需指定；与 [`text_to_speech`](https://docs.veadk.xyz/productions/veadk/preview/zh/components/tools/text-to-speech) 不同，本工具只需要语音服务 API Key，不需要 App ID 或模型 API Key。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.