多模态语音与文本代理
在语音代理系统中协调语音回复与屏幕文本。
多模态语音与文本代理 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。
纯语音与多模态环境
语音人工智能代理运行在两种根本不同的环境中:
- 纯语音:智能音箱、IVR、电话——用户只能听到音频,没有屏幕
- 多模态:移动应用、网页应用、汽车仪表盘——用户可以同时看到屏幕并听到音频
这两种环境需要不同的回应策略。在纯语音环境中,所有内容都必须通过语音表达。在多模态环境中,您可以协调语音内容和屏幕显示内容。
为纯语音回应编写提示
在纯语音环境中,LLM 必须生成完全不依赖视觉信息的回应。这意味着不能引用屏幕元素,不能使用需要通过视觉浏览的列表,也不能提供只有配合格式才能理解的内容。
VOICE_ONLY_SYSTEM_PROMPT = (
'You are a voice-only assistant. The user cannot see any screen.\n\n'
'Requirements:\n'
'- Never reference visual elements ("tap here", "see the chart", "the blue button")\n'
'- Never use numbered or bulleted lists — use spoken sequences instead:\n'
' BAD: "1. First do X 2. Then do Y"\n'
' GOOD: "Start by doing X. When that is done, do Y."\n'
'- Limit responses to what can be comfortably spoken in 30 seconds\n'
'- Offer to give more detail rather than overwhelming the user\n'
'- Use verbal signposts: "First", "Next", "Finally"\n'
'- Read out all important data: codes, dates, amounts as full words'
)
print(VOICE_ONLY_SYSTEM_PROMPT)协调语音与屏幕文字
在多模态环境中,您可以将内容分配到音频和屏幕上。音频负责对话性、情感性和动态内容;屏幕负责密集信息、表格和长篇文字。
MULTIMODAL_SYSTEM_PROMPT = (
'You are a multimodal assistant with both a voice and a screen.\n\n'
'When responding, consider what each modality does best:\n\n'
'SPEAK (voice):\n'
'- Conversational summary, emotional tone, key highlights\n'
'- Guide the user to look at the screen when needed:\n'
' "I have shown the details on screen. The key number to notice is..."\n\n'
'SHOW (screen):\n'
'- Detailed data, tables, long lists, code, maps, images\n\n'
'When your response includes structured data, respond in this format:\n'
'SPOKEN: <what to say aloud>\n'
'VISUAL: <what to display on screen in markdown>'
)
# Example LLM output for multimodal response:
EXAMPLE_MULTIMODAL_OUTPUT = (
'SPOKEN: Your top three expenses this month are food, transport, and entertainment. '
'Food was the biggest, almost double your budget. Check the screen for the full breakdown.\n\n'
'VISUAL: | Category | Budget | Actual | Difference |\n'
'|---|---|---|---|\n'
'| Food | $400 | $780 | -$380 |\n'
'| Transport | $150 | $162 | -$12 |\n'
'| Entertainment | $100 | $145 | -$45 |'
)
print(EXAMPLE_MULTIMODAL_OUTPUT)为语音代理构建 LLM 输出结构
对于语音代理应用,请提示 LLM 返回结构化输出,以便您解析内容,并分别将其路由到音频或屏幕。JSON 或预先定义的分段格式都很有效。
import anthropic
import json
client = anthropic.Anthropic(api_key='sk-ant-...')
VOICE_AGENT_SYSTEM = (
'You are a financial voice assistant. For each response, return JSON with:\n'
'{\n'
' "spoken": "Short spoken response (max 2 sentences)",\n'
' "visual_title": "Header for the on-screen card (optional)",\n'
' "visual_content": "Detailed content for screen (markdown, optional)",\n'
' "action_label": "Button label if action needed (optional)",\n'
' "action_type": "one of: none, confirm, navigate, call"\n'
'}\n'
'Return only the JSON object.'
)
def voice_agent_query(user_message):
r = client.messages.create(
model='claude-opus-4-5',
max_tokens=500,
system=VOICE_AGENT_SYSTEM,
messages=[{'role': 'user', 'content': user_message}]
)
try:
response_data = json.loads(r.content[0].text)
return response_data
except json.JSONDecodeError:
return {'spoken': r.content[0].text, 'visual_content': None}
result = voice_agent_query('What is my account balance?')
print('SPEAK:', result.get('spoken'))
print('SHOW:', result.get('visual_content', 'Nothing to display'))为语音代理设置文字记录格式
语音代理的对话必须记录为文字记录,以便调试、合规检查和质量审查。请设置文字记录格式,以记录说话者身份、时间戳以及音频和视觉输出。
import datetime
import json
class VoiceTranscript:
def __init__(self, session_id):
self.session_id = session_id
self.turns = []
def add_user_turn(self, text, audio_duration_ms=None):
self.turns.append({
'speaker': 'user',
'timestamp': datetime.datetime.utcnow().isoformat(),
'text': text,
'audio_duration_ms': audio_duration_ms,
})
def add_agent_turn(self, spoken_text, visual_content=None, action=None):
self.turns.append({
'speaker': 'agent',
'timestamp': datetime.datetime.utcnow().isoformat(),
'spoken': spoken_text,
'visual': visual_content,
'action': action,
})
def save(self, filepath):
with open(filepath, 'w') as f:
json.dump({'session_id': self.session_id, 'turns': self.turns}, f, indent=2)
print(f'Transcript saved: {filepath}')
# Usage
transcript = VoiceTranscript('session_001')
transcript.add_user_turn('What is my balance?', audio_duration_ms=1200)
transcript.add_agent_turn('Your balance is four hundred dollars.', visual_content='Balance: $400')
transcript.save('/tmp/session_001_transcript.json')处理语音输入错误
语音代理必须妥善处理语音识别错误,例如误听词语、话语不完整或背景噪声。请提示 LLM 检测含义不明确的输入并从中恢复。
import anthropic
client = anthropic.Anthropic(api_key='sk-ant-...')
AMBIGUITY_HANDLING_SYSTEM = (
'You are a voice assistant. User input comes from speech recognition '
'and may contain transcription errors.\n\n'
'When input seems unclear or ambiguous:\n'
'1. State what you think the user might have meant.\n'
'2. Ask a single clarifying yes/no question to confirm.\n'
'3. Never ask more than one question at a time.\n'
'4. Offer the most likely interpretation as the default.\n\n'
'Example:\n'
'Input: "transfer five hundred to john or gene" (ambiguous name)\n'
'Response: "It sounds like you want to transfer five hundred dollars. '
'Did you mean John Smith or Gene Lee?"'
)
def handle_voice_input(user_speech):
r = client.messages.create(
model='claude-opus-4-5',
max_tokens=200,
system=AMBIGUITY_HANDLING_SYSTEM,
messages=[{'role': 'user', 'content': user_speech}]
)
return r.content[0].text
print(handle_voice_input('pay the electric company bill thing'))语音对话中的轮次管理
与文字聊天不同,语音交流需要明确管理轮次。代理必须知道何时停止说话并开始聆听,用户也必须知道代理何时说完。请设计提示,使生成的回应带有自然的结束信号。
TURN_TAKING_SYSTEM = (
'You are a voice assistant. Responses must be designed for spoken conversation:\n\n'
'End each response with exactly ONE of:\n'
'- A direct question inviting the user to respond\n'
'- A clear statement that the task is complete (e.g., "That is done.")\n'
'- An explicit offer to continue (e.g., "Is there anything else?")\n\n'
'Never end mid-thought. Never trail off. '
'Avoid open-ended statements that leave the user unsure if they should speak.\n\n'
'GOOD endings:\n'
'- "The transfer is complete. Would you like a confirmation number?"\n'
'- "That is all I have. Is there anything else?"\n'
'BAD endings:\n'
'- "You might also want to consider..." (open, unclear)\n'
'- "The balance is..." (incomplete)'
)
print(TURN_TAKING_SYSTEM[:300])处理打断
用户可能会打断语音代理。系统必须检测打断(通过 VAD——语音活动检测),并提示代理自然地继续或转向其他内容。请提示 LLM 接受对话中途发生的主题变化。
import anthropic
client = anthropic.Anthropic(api_key='sk-ant-...')
INTERRUPTION_SYSTEM = (
'You are a voice assistant. Users may interrupt mid-conversation.\n\n'
'If the user changes topic abruptly, smoothly acknowledge the change:\n'
'"Of course. Let us switch to that." Then answer the new question.\n\n'
'If the user says something like "wait", "stop", "hold on":\n'
'Pause and say "Sure, take your time" and wait for them to continue.\n\n'
'If the user repeats a question, they likely did not hear the answer:\n'
'Say "Let me repeat that." and say it again more slowly.\n\n'
'Never express frustration at interruptions or repetition.'
)
def handle_conversation(turns):
"""Handle multi-turn voice conversation with interruptions."""
messages = []
for speaker, text in turns:
messages.append({'role': speaker, 'content': text})
r = client.messages.create(
model='claude-opus-4-5',
max_tokens=200,
system=INTERRUPTION_SYSTEM,
messages=messages
)
return r.content[0].text
# Simulate an interruption scenario
conversation = [
('user', 'What is my balance?'),
('assistant', 'Your checking account balance is four hundred dollars and—'),
('user', 'Actually wait, can you tell me my savings instead?'),
]
print(handle_conversation(conversation))语音的屏幕伴随内容
当有屏幕可用时,请设计屏幕内容来补充(而不是重复)语音内容。屏幕负责详细信息;语音负责导航和情感互动。
def render_multimodal_response(agent_output):
"""
Render a voice agent response to both TTS and screen components.
agent_output: dict with 'spoken', 'visual_content', 'action_label'
"""
# Route to TTS
spoken = agent_output.get('spoken', '')
if spoken:
send_to_tts(spoken) # Your TTS function
print(f'[AUDIO] {spoken}')
# Route to screen
visual = agent_output.get('visual_content')
if visual:
render_card_on_screen(visual) # Your UI function
print(f'[SCREEN] {visual[:100]}')
# Optional action button
action_label = agent_output.get('action_label')
if action_label:
show_action_button(action_label) # Your UI function
print(f'[BUTTON] {action_label}')
def send_to_tts(text):
print(f'TTS: {text}')
def render_card_on_screen(content):
print(f'Screen card: {content[:50]}')
def show_action_button(label):
print(f'Button: {label}')
# Test it
render_multimodal_response({
'spoken': 'I found three flights to New York.',
'visual_content': '| Flight | Departs | Price |\n|---|---|---|\n| AA101 | 08:00 | $299 |',
'action_label': 'Book cheapest'
})无障碍注意事项
对于视力受损或行动困难的用户而言,语音人工智能本身就是一项无障碍功能。请设计代理,使其也能支持主要依赖语音作为界面的用户。
ACCESSIBILITY_VOICE_SYSTEM = (
'This voice assistant serves users who may be using voice as their '
'primary access method due to disability or preference.\n\n'
'Guidelines:\n'
'- Never require the user to see a screen to complete a task.\n'
'- Read out all information that matters, including confirmation codes, '
'totals, and status messages.\n'
'- Offer to repeat any information: '
'"I can repeat that if you would like."\n'
'- Describe any actions you took: '
'"I have sent the confirmation to your email."\n'
'- Accept multiple phrasings for the same command — users phrase '
'voice commands inconsistently.\n'
'- Confirm all destructive or financial actions before executing:\n'
' "Just to confirm: you want to transfer $500 to John. Is that right?"'
)
print(ACCESSIBILITY_VOICE_SYSTEM[:300])测试语音代理回应
测试语音代理回应需要采用不同于测试文字回应的方法。您必须同时评估语音音频(韵律、清晰度、自然度)和视觉部分(完整性、格式)。读起来流畅的文字回应,在说出来时可能听起来很别扭。
请构建一个测试流程,使用您的 TTS 引擎将代理输出转换为音频,然后执行自动质量检查:句子长度、缩写词的发音、是否存在 Markdown 残留以及轮次切换信号。
知识检查:纯语音限制
在纯语音环境中(没有屏幕的智能音箱),哪种类型的代理回应最合适?
回顾:多模态语音与文字代理
语音代理有两种模式:纯语音(没有屏幕)和多模态(语音加屏幕)。纯语音回应必须避免视觉引用,完全通过语音表达,并使用口头提示来组织内容。多模态回应应分配内容:语音用于对话式摘要和表达情感基调,屏幕用于详细数据和长篇文字。请提示 LLM 返回结构化输出(包含语音字段和视觉字段的 JSON),以便轻松路由。请通过清晰的回应结束信号、自然的打断处理和明确的重复支持来设计轮次管理。请始终考虑无障碍需求——对于最需要语音的用户而言,语音往往是他们的主要界面。
常见问题解答
「多模态语音与文本代理」课时是免费的吗?
是的 — 「多模态语音与文本代理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。
「多模态语音与文本代理」这节课中我会学到什么?
在语音代理系统中协调语音回复与屏幕文本。 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Prompt Engineering 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「多模态语音与文本代理」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Prompt Engineering 课中编写并运行代码吗?
能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 适用于自然语音的 TTS 提示词模式
- SSML 与韵律控制
- 语音人工智能人格设计
- 多模态语音与文本代理