Agent / tools /transcribe_audio.py
BiGuan's picture
Upload 13 files
e15103f verified
Raw
History Blame Contribute Delete
1.61 kB
"""
tools/transcribe_audio.py —— 工具⑤:把录音转成文字(语音识别)
有的题目附带一段录音(比如"语音备忘录""课堂录音"),问的内容藏在话里。
这个工具把音频文件交给专门的语音识别模型(whisper-1),让它"听写"成文字,
然后大模型就能从文字里找答案了。
"""
import os
from langchain_core.tools import tool
# 复用 config.py 里配置好的服务地址、密钥,以及语音识别专用模型的名字。
from config import LLM_BASE_URL, LLM_API_KEY, ASR_MODEL_ID
@tool
def transcribe_audio(file_path: str) -> str:
"""Transcribe a local audio file (.mp3/.wav/.m4a/...) to text. Use it whenever a
question references a voice memo or recording. The transcript is returned as plain
text."""
# 先确认音频文件存在。
if not os.path.exists(file_path):
return f"File not found: {file_path}"
try:
from openai import OpenAI
# 创建一个连接到我们模型服务的客户端。
client = OpenAI(base_url=LLM_BASE_URL, api_key=LLM_API_KEY)
# 以"二进制"方式打开音频文件("rb" = read binary),把它上传给语音识别模型。
with open(file_path, "rb") as f:
result = client.audio.transcriptions.create(model=ASR_MODEL_ID, file=f)
# 取出识别出的文字。getattr(...) 是稳妥写法:能取到 text 就用 text,取不到就退而求其次。
return getattr(result, "text", None) or str(result)
except Exception as e:
return f"Error transcribing audio '{file_path}': {e}"