0Pricing
AI Prompt Engineering · Lezione

Agenti vocali e testuali multimodali

Coordinamento delle risposte vocali con il testo visualizzato sullo schermo nei sistemi di agenti vocali

Agenti vocali e testuali multimodali è una lezione AI Prompt Engineering gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento AI Prompt Engineering, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso AI Prompt Engineering include 4 lezioni in totale.

Contesti solo voce e multimodali

Gli agenti di IA vocale operano in due contesti fondamentalmente diversi:

  • Solo voce: smart speaker, IVR, telefonate — gli utenti ascoltano solo l'audio e non hanno uno schermo
  • Multimodale: app per dispositivi mobili, app web, cruscotti delle automobili — gli utenti possono vedere uno schermo E ascoltare l'audio contemporaneamente

Questi contesti richiedono strategie di risposta diverse. Nei contesti solo voce, tutto deve essere pronunciato. In quelli multimodali, è possibile coordinare ciò che viene pronunciato con ciò che viene visualizzato.

Creare prompt per risposte solo voce

Nei contesti solo voce, l'LLM deve produrre risposte che funzionino interamente senza elementi visivi. Ciò significa evitare riferimenti agli elementi sullo schermo, elenchi che richiedono una consultazione visiva e contenuti comprensibili solo grazie alla formattazione.

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)

Coordinare testo pronunciato e testo sullo schermo

Nei contesti multimodali, è possibile distribuire i contenuti tra audio e schermo. L'audio gestisce i contenuti conversazionali, emotivi e dinamici. Lo schermo gestisce le informazioni dense, le tabelle e i testi lunghi.

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)

Strutturare l'output dell'LLM per gli agenti vocali

Per le applicazioni con agenti vocali, chieda all'LLM di restituire un output strutturato che possa essere analizzato e instradato separatamente verso l'audio o lo schermo. JSON o un formato con sezioni definite funzionano bene.

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'))

Formattare le trascrizioni per gli agenti vocali

Le conversazioni degli agenti vocali devono essere registrate sotto forma di trascrizioni per il debugging, la conformità e il controllo della qualità. Formatti le trascrizioni in modo da acquisire l'identità di chi parla, i timestamp e sia gli output audio sia quelli visivi.

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')

Gestire gli errori dell'input vocale

Gli agenti vocali devono gestire con naturalezza gli errori di riconoscimento vocale, come parole fraintese, enunciati incompleti o rumori di fondo. Chieda all'LLM di rilevare e risolvere gli input ambigui.

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'))

Gestire i turni nelle conversazioni vocali

A differenza delle chat testuali, la voce richiede una gestione esplicita dei turni. L'agente deve sapere quando smettere di parlare e ascoltare, mentre l'utente deve capire quando l'agente ha finito. Progetti prompt che producano risposte con segnali naturali di fine intervento.

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])

Gestire le interruzioni

Gli utenti interrompono gli agenti vocali. Il sistema deve rilevare le interruzioni (tramite VAD — rilevamento dell'attività vocale) e chiedere all'agente di riprendere la conversazione o reindirizzarla con naturalezza. Chieda all'LLM di accettare cambi di argomento a metà conversazione.

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))

Contenuti sullo schermo a supporto della voce

Quando è disponibile uno schermo, progetti i contenuti visualizzati in modo che completino, anziché duplicare, l'audio pronunciato. Lo schermo gestisce i dettagli; la voce gestisce la navigazione e il coinvolgimento emotivo.

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'
})

Considerazioni sull'accessibilità

L'IA vocale è di per sé una funzionalità di accessibilità per gli utenti con disabilità visive o difficoltà motorie. Progetti l'agente in modo che supporti anche gli utenti che si affidano alla voce come interfaccia principale.

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])

Testare le risposte degli agenti vocali

Per testare le risposte degli agenti vocali è necessario un approccio diverso da quello usato per le risposte testuali. È necessario valutare sia l'audio pronunciato (prosodia, chiarezza, naturalezza), sia la componente visiva (completezza, formattazione). Una risposta testuale che si legge bene potrebbe risultare innaturale quando viene pronunciata.

Costruisca una pipeline di test che converta gli output dell'agente in audio usando il motore TTS, quindi applichi un controllo automatico della qualità: lunghezza delle frasi, pronuncia delle abbreviazioni, assenza di residui di Markdown e segnali di gestione dei turni.

Verifica delle conoscenze: vincolo solo voce

In un contesto solo voce (uno smart speaker senza schermo), quale tipo di risposta dell'agente è PIÙ appropriato?

Riepilogo: agenti vocali e testuali multimodali

Gli agenti vocali operano in due modalità: solo voce (senza schermo) e multimodale (voce e schermo). Le risposte solo voce devono evitare riferimenti visivi e funzionare interamente come audio pronunciato, usando indicatori verbali. Le risposte multimodali dividono i contenuti: la voce viene usata per i riepiloghi conversazionali e il tono emotivo, mentre lo schermo viene usato per i dati dettagliati e i testi lunghi. Chieda agli LLM di restituire un output strutturato (JSON con campi spoken/visual) per semplificarne l'instradamento. Progetti la gestione dei turni con conclusioni chiare, una gestione naturale delle interruzioni e il supporto esplicito alla ripetizione. Consideri sempre l'accessibilità: per gli utenti che ne hanno più bisogno, la voce è spesso l'interfaccia principale.

Domande Frequenti

La lezione «Agenti vocali e testuali multimodali» è gratuita?

Sì — il testo completo di «Agenti vocali e testuali multimodali» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso AI Prompt Engineering, passa a CoddyKit PRO. Il corso AI Prompt Engineering include 4 lezioni in totale.

Cosa imparerò in «Agenti vocali e testuali multimodali»?

Coordinamento delle risposte vocali con il testo visualizzato sullo schermo nei sistemi di agenti vocali Eserciti AI Prompt Engineering con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare AI Prompt Engineering?

Non è richiesta alcuna esperienza precedente. AI Prompt Engineering su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Agenti vocali e testuali multimodali»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione AI Prompt Engineering?

Sì. Ogni lezione AI Prompt Engineering include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Pattern di prompt TTS per un parlato naturale
  2. SSML e controllo della prosodia
  3. Progettazione della persona per la Voice AI
  4. Agenti vocali e testuali multimodali
← Torna a AI Prompt Engineering