File size: 3,380 Bytes
4ad82b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import argparse
import io
from typing import Generator, Tuple, Union
import numpy as np
import soundfile as sf
from fastrtc import (
    AlgoOptions,
    ReplyOnPause,
    Stream,
    get_tts_model,
)
from groq import Groq
from loguru import logger
from dotenv import load_dotenv
import os
load_dotenv()
from websearch_agent import agent, agent_config

logger.remove()
logger.add(
    lambda msg: print(msg),
    colorize=True,
    format="<green>{time:HH:mm:ss}</green> | <level>{level}</level> | <level>{message}</level>",
)

groq_client = Groq()

# Initialize FastRTC TTS model (Kokoro)
logger.info("🎀 Initializing FastRTC TTS model...")
tts_model = get_tts_model()  # Uses Kokoro TTS
logger.info("βœ… FastRTC TTS model initialized successfully")


def response(

    audio: tuple[int, np.ndarray],

) -> Generator[Tuple[int, np.ndarray], None, None]:
    """

    Process audio input, transcribe it, generate a response using LangGraph, and deliver TTS audio.



    Args:

        audio: Tuple containing sample rate and audio data



    Yields:

        Tuples of (sample_rate, audio_array) for audio playback

    """
    logger.info("πŸŽ™οΈ Received audio input")

    logger.debug("πŸ”„ Transcribing audio...")
    # Convert numpy array to WAV bytes
    sample_rate, audio_data = audio
    buffer = io.BytesIO()
    sf.write(buffer, audio_data.T, sample_rate, format='WAV')
    buffer.seek(0)
    
    transcript = groq_client.audio.transcriptions.create(
        file=("audio-file.wav", buffer.read()),
        model="whisper-large-v3-turbo",
        response_format="text",
    )
    logger.info(f'πŸ‘‚ Transcribed: "{transcript}"')

    logger.debug("🧠 Running agent...")
    agent_response = agent.invoke(
        {"messages": [{"role": "user", "content": transcript}]}, config=agent_config
    )
    response_text = agent_response["messages"][-1].content
    logger.info(f'πŸ’¬ Response: "{response_text}"')

    logger.debug("πŸ”Š Generating speech with FastRTC TTS...")
    try:
        # Generate speech using FastRTC TTS model (Kokoro)
        for audio_chunk in tts_model.stream_tts_sync(response_text):
            yield audio_chunk
            
    except Exception as e:
        logger.error(f"Error in TTS generation: {str(e)}")
        raise


def create_stream() -> Stream:
    """

    Create and configure a Stream instance with audio capabilities.



    Returns:

        Stream: Configured FastRTC Stream instance

    """
    return Stream(
        modality="audio",
        mode="send-receive",
        handler=ReplyOnPause(
            response,
            algo_options=AlgoOptions(
                speech_threshold=0.5,
            ),
        ),
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="FastRTC Groq Voice Agent")
    parser.add_argument(
        "--phone",
        action="store_true",
        help="Launch with FastRTC phone interface (get a temp phone number)",
    )
    args = parser.parse_args()

    stream = create_stream()
    logger.info("🎧 Stream handler configured")

    if args.phone:
        logger.info("🌈 Launching with FastRTC phone interface...")
        stream.fastphone()
    else:
        logger.info("🌈 Launching with Gradio UI...")
        stream.ui.launch()