From 43cb9f7a8aebe157c96214560bfe45dee373f0d6 Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 12 Nov 2025 10:54:59 +0800 Subject: [PATCH 1/4] feat: test file --- .../core/providers/asr/openai.py | 50 +-- .../core/providers/asr/test/QUICKSTART.txt | 126 ++++++ .../core/providers/asr/test/__init__.py | 2 + .../core/providers/asr/test/audio_recorder.py | 186 +++++++++ .../core/providers/asr/test/test_groq.py | 143 +++++++ .../core/providers/asr/test/test_openai.py | 144 +++++++ .../core/providers/llm/test/BENCHMARK.txt | 147 +++++++ .../core/providers/llm/test/QUICKSTART.txt | 182 +++++++++ .../core/providers/llm/test/__init__.py | 2 + .../core/providers/llm/test/benchmark.py | 379 ++++++++++++++++++ .../providers/llm/test/benchmark_report.md | 188 +++++++++ .../core/providers/llm/test/test_google.py | 162 ++++++++ .../core/providers/llm/test/test_groq.py | 163 ++++++++ .../core/providers/llm/test/test_openai.py | 160 ++++++++ .../providers/llm/test/test_openrouter.py | 168 ++++++++ 15 files changed, 2171 insertions(+), 31 deletions(-) create mode 100644 main/xiaozhi-server/core/providers/asr/test/QUICKSTART.txt create mode 100644 main/xiaozhi-server/core/providers/asr/test/__init__.py create mode 100644 main/xiaozhi-server/core/providers/asr/test/audio_recorder.py create mode 100644 main/xiaozhi-server/core/providers/asr/test/test_groq.py create mode 100644 main/xiaozhi-server/core/providers/asr/test/test_openai.py create mode 100644 main/xiaozhi-server/core/providers/llm/test/BENCHMARK.txt create mode 100644 main/xiaozhi-server/core/providers/llm/test/QUICKSTART.txt create mode 100644 main/xiaozhi-server/core/providers/llm/test/__init__.py create mode 100644 main/xiaozhi-server/core/providers/llm/test/benchmark.py create mode 100644 main/xiaozhi-server/core/providers/llm/test/benchmark_report.md create mode 100644 main/xiaozhi-server/core/providers/llm/test/test_google.py create mode 100644 main/xiaozhi-server/core/providers/llm/test/test_groq.py create mode 100644 main/xiaozhi-server/core/providers/llm/test/test_openai.py create mode 100644 main/xiaozhi-server/core/providers/llm/test/test_openrouter.py diff --git a/main/xiaozhi-server/core/providers/asr/openai.py b/main/xiaozhi-server/core/providers/asr/openai.py index 5c6e849c0..5cad3460b 100644 --- a/main/xiaozhi-server/core/providers/asr/openai.py +++ b/main/xiaozhi-server/core/providers/asr/openai.py @@ -1,12 +1,14 @@ import time import os + +from openai.types.audio import transcription from config.logger import setup_logging from typing import Optional, Tuple, List from core.providers.asr.dto.dto import InterfaceType from core.providers.asr.base import ASRProviderBase -import requests - +from openai import OpenAI +from openai.types.audio import Transcription TAG = __name__ logger = setup_logging() @@ -14,11 +16,16 @@ class ASRProvider(ASRProviderBase): def __init__(self, config: dict, delete_audio_file: bool): self.interface_type = InterfaceType.NON_STREAM self.api_key = config.get("api_key") - self.api_url = config.get("base_url") + self.base_url = config.get("base_url") self.model = config.get("model_name") self.output_dir = config.get("output_dir") self.delete_audio_file = delete_audio_file + self._client = OpenAI( + api_key=self.api_key, + base_url=self.base_url + ) + os.makedirs(self.output_dir, exist_ok=True) async def speech_to_text(self, opus_data: List[bytes], session_id: str, audio_format="opus") -> Tuple[Optional[str], Optional[str]]: @@ -32,44 +39,25 @@ class ASRProvider(ASRProviderBase): file_path = self.save_audio_to_file(pcm_data, session_id) logger.bind(tag=TAG).debug( - f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}" + f"Audio file save latency: {time.time() - start_time:.3f}s | Path: {file_path}" ) - logger.bind(tag=TAG).info(f"file path: {file_path}") - headers = { - "Authorization": f"Bearer {self.api_key}", - } - - # 使用data参数传递模型名称 - data = { - "model": self.model - } - - - with open(file_path, "rb") as audio_file: # 使用with语句确保文件关闭 - files = { - "file": audio_file - } + with open(file_path, "rb") as audio_file: # with open to ensure file is closed start_time = time.time() - response = requests.post( - self.api_url, - files=files, - data=data, - headers=headers + transcription: Transcription = self._client.audio.transcriptions.create( + model=self.model, + file=audio_file, + response_format="text" ) logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {response.text}" + f"Audio transcription latency: {time.time() - start_time:.3f}s | Result: {transcription.text}" ) - if response.status_code == 200: - text = response.json().get("text", "") - return text, file_path - else: - raise Exception(f"API请求失败: {response.status_code} - {response.text}") + return transcription.text, file_path except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}") + logger.bind(tag=TAG).error(f"Audio transcription failed: {e}") return "", None finally: # 文件清理逻辑 diff --git a/main/xiaozhi-server/core/providers/asr/test/QUICKSTART.txt b/main/xiaozhi-server/core/providers/asr/test/QUICKSTART.txt new file mode 100644 index 000000000..18856b92b --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/test/QUICKSTART.txt @@ -0,0 +1,126 @@ +ASR Test Quick Start Guide +========================== + +1. Set API Keys (one-time setup) +--------------------------------- + +Add to ~/.zshrc for permanent access: + +# Groq +echo 'export GROQ_API_KEY="gsk_your_key_here"' >> ~/.zshrc + +# OpenAI +echo 'export OPENAI_API_KEY="sk-proj-your_key_here"' >> ~/.zshrc + +source ~/.zshrc + + +2. Install Dependencies +----------------------- + +# Install required packages +pip install openai pyaudio + + +3. Run Tests +------------ + +cd /Users/harold/Projects/live-agent/main/xiaozhi-server/ + +# Test Groq ASR (with recording) +python3 -m core.providers.asr.test.test_groq + +# Test Groq ASR (with existing audio file) +python3 -m core.providers.asr.test.test_groq /path/to/audio.wav + +# Test OpenAI ASR (with recording) +python3 -m core.providers.asr.test.test_openai + +# Test OpenAI ASR (with existing audio file) +python3 -m core.providers.asr.test.test_openai /path/to/audio.wav + +# Test audio recorder only +python3 -m core.providers.asr.test.audio_recorder + + +4. Available Models +------------------- + +Groq Models: +- whisper-large-v3 (default, best accuracy) +- whisper-large-v3-turbo (faster) + +OpenAI Models: +- whisper-1 (official OpenAI Whisper) + + +5. Recording Instructions +------------------------- + +When running the test: +1. Press Enter to START recording +2. Speak into your microphone +3. Press Enter to STOP recording +4. Wait for transcription result + + +6. Example Output +----------------- + +🤖 OpenAI ASR Test + API: https://api.openai.com/v1 + Model: whisper-1 + Audio: core/providers/asr/test/tmp/recording_20251111_143022.wav + Size: 256.3 KB + +⏳ Transcribing audio... +============================================================ +✅ Transcription Result: +============================================================ + +Hello, this is a test of OpenAI Whisper speech recognition. + +============================================================ +⏱️ Latency: 1523 ms (1.52s) +============================================================ + +✅ Test completed successfully! + + +7. Check Output +--------------- + +Generated audio files are in: +core/providers/asr/test/tmp/ + - recording_YYYYMMDD_HHMMSS.wav + + +8. Troubleshooting +------------------ + +If API key error: + echo $GROQ_API_KEY # Check Groq key + echo $OPENAI_API_KEY # Check OpenAI key + source ~/.zshrc # Reload config + +If pyaudio not installed: + pip install pyaudio + + # macOS (if pip install fails): + brew install portaudio + pip install pyaudio + +If OpenAI SDK not installed: + pip install openai + +If module not found: + cd /Users/harold/Projects/live-agent/main/xiaozhi-server/ + # Make sure you're in the right directory! + +Get API keys: + Groq: https://console.groq.com/keys + OpenAI: https://platform.openai.com/api-keys + + +That's it! 🎉 + diff --git a/main/xiaozhi-server/core/providers/asr/test/__init__.py b/main/xiaozhi-server/core/providers/asr/test/__init__.py new file mode 100644 index 000000000..615e3b08c --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/test/__init__.py @@ -0,0 +1,2 @@ +# ASR Test Module + diff --git a/main/xiaozhi-server/core/providers/asr/test/audio_recorder.py b/main/xiaozhi-server/core/providers/asr/test/audio_recorder.py new file mode 100644 index 000000000..6ee580e14 --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/test/audio_recorder.py @@ -0,0 +1,186 @@ +""" +Audio Recorder Utility for ASR Testing + +Simple command-line based audio recorder that supports cross-platform recording. +""" + +import os +import sys +import wave +import time +import platform +from typing import Optional + +try: + import pyaudio +except ImportError: + print("❌ Error: pyaudio not installed") + print(" Install with: pip install pyaudio") + sys.exit(1) + + +class AudioRecorder: + def __init__( + self, + sample_rate: int = 16000, + channels: int = 1, + chunk_size: int = 1024, + format: int = pyaudio.paInt16 + ): + """ + Initialize audio recorder + + Args: + sample_rate: Sampling rate in Hz (default: 16000) + channels: Number of audio channels (default: 1 for mono) + chunk_size: Audio buffer size + format: Audio format (default: 16-bit PCM) + """ + self.sample_rate = sample_rate + self.channels = channels + self.chunk_size = chunk_size + self.format = format + self.audio = pyaudio.PyAudio() + + def record_audio(self, output_path: Optional[str] = None) -> str: + """ + Record audio with interactive command-line control + + Args: + output_path: Path to save the WAV file (optional) + + Returns: + Path to the saved audio file + """ + if output_path is None: + timestamp = time.strftime("%Y%m%d_%H%M%S") + output_path = os.path.join( + os.path.dirname(__file__), + "tmp", + f"recording_{timestamp}.wav" + ) + + # Ensure output directory exists + os.makedirs(os.path.dirname(output_path), exist_ok=True) + + print("\n🎤 Audio Recorder") + print(f" Sample Rate: {self.sample_rate} Hz") + print(f" Channels: {self.channels} (Mono)") + print(f" Format: 16-bit PCM") + print(f"\n📁 Output: {output_path}\n") + + # Wait for user to start recording + input("▶️ Press Enter to start recording...") + + print("\n🔴 Recording... Press Enter to stop") + + # Open audio stream + stream = self.audio.open( + format=self.format, + channels=self.channels, + rate=self.sample_rate, + input=True, + frames_per_buffer=self.chunk_size + ) + + frames = [] + recording = True + start_time = time.time() + + # Start recording in a separate thread to allow keyboard interrupt + import threading + + def record_frames(): + while recording: + try: + data = stream.read(self.chunk_size, exception_on_overflow=False) + frames.append(data) + except Exception as e: + print(f"⚠️ Warning: {e}") + break + + record_thread = threading.Thread(target=record_frames, daemon=True) + record_thread.start() + + # Wait for user to stop recording + try: + input() + except KeyboardInterrupt: + print("\n") + + recording = False + record_thread.join(timeout=1.0) + + duration = time.time() - start_time + + # Stop and close stream + stream.stop_stream() + stream.close() + + print(f"⏹️ Recording stopped ({duration:.1f}s)") + + # Save to WAV file + with wave.open(output_path, 'wb') as wf: + wf.setnchannels(self.channels) + wf.setsampwidth(self.audio.get_sample_size(self.format)) + wf.setframerate(self.sample_rate) + wf.writeframes(b''.join(frames)) + + file_size = os.path.getsize(output_path) / 1024 # KB + print(f"✅ Audio saved: {file_size:.1f} KB\n") + + return output_path + + def cleanup(self): + """Clean up PyAudio resources""" + self.audio.terminate() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.cleanup() + + +def record_audio_file(output_path: Optional[str] = None) -> str: + """ + Convenient function to record audio file + + Args: + output_path: Path to save the WAV file (optional) + + Returns: + Path to the saved audio file + """ + with AudioRecorder() as recorder: + return recorder.record_audio(output_path) + + +if __name__ == "__main__": + """ + Test the audio recorder + + Usage: + python3 -m core.providers.asr.test.audio_recorder + python3 -m core.providers.asr.test.audio_recorder output.wav + """ + output_file = sys.argv[1] if len(sys.argv) > 1 else None + + try: + audio_path = record_audio_file(output_file) + print(f"🎉 Recording completed: {audio_path}") + + # Play audio on macOS + if platform.system() == "Darwin": + print("\n🔊 Playing back audio...") + os.system(f"afplay '{audio_path}'") + + except KeyboardInterrupt: + print("\n\n👋 Recording cancelled") + sys.exit(0) + except Exception as e: + print(f"\n❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + diff --git a/main/xiaozhi-server/core/providers/asr/test/test_groq.py b/main/xiaozhi-server/core/providers/asr/test/test_groq.py new file mode 100644 index 000000000..5f552b651 --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/test/test_groq.py @@ -0,0 +1,143 @@ +""" +Groq ASR (Whisper) Test + +This script tests Groq's speech-to-text API using the OpenAI SDK. +Groq is compatible with OpenAI's API format. + +Usage: + # Record and transcribe + python3 -m core.providers.asr.test.test_groq + + # Transcribe existing audio file + python3 -m core.providers.asr.test.test_groq path/to/audio.wav + +Environment: + GROQ_API_KEY - Your Groq API key (required) + +Examples: + export GROQ_API_KEY="gsk_your_key_here" + python3 -m core.providers.asr.test.test_groq + python3 -m core.providers.asr.test.test_groq /path/to/test.wav +""" + +import sys +import os +import time +import platform + +# Check if OpenAI SDK is installed +try: + from openai import OpenAI +except ImportError: + print("❌ Error: openai package not installed") + print(" Install with: pip install openai") + sys.exit(1) + +# Import audio recorder +try: + from core.providers.asr.test.audio_recorder import record_audio_file +except ImportError: + print("❌ Error: Could not import audio_recorder") + print(" Make sure you're running from xiaozhi-server directory") + sys.exit(1) + + +def test_groq_asr(audio_file_path: str): + """ + Test Groq ASR with the given audio file + + Args: + audio_file_path: Path to the audio WAV file + api_key: Groq API key + model: Groq Whisper model name (default: whisper-large-v3) + + Returns: + Tuple of (transcribed_text, latency_ms) + """ + print(f"🤖 Groq ASR Test") + print(f" API: https://api.groq.com/openai/v1") + model = "whisper-large-v3" + api_key = os.environ.get("GROQ_API_KEY") + print(f" Model: {model}") + print(f" Audio: {audio_file_path}") + + # Get file size + file_size = os.path.getsize(audio_file_path) / 1024 # KB + print(f" Size: {file_size:.1f} KB\n") + + # Initialize OpenAI client with Groq endpoint + client = OpenAI( + api_key=api_key, + base_url="https://api.groq.com/openai/v1" + ) + + try: + print("⏳ Transcribing audio...") + start_time = time.time() + + # Open audio file and send to Groq + with open(audio_file_path, "rb") as audio_file: + transcription = client.audio.transcriptions.create( + model=model, + file=audio_file, + response_format="text" + ) + + end_time = time.time() + latency_ms = (end_time - start_time) * 1000 + + # Get transcription text + if isinstance(transcription, str): + text = transcription + else: + text = transcription.text if hasattr(transcription, 'text') else str(transcription) + + return text, latency_ms + + except Exception as e: + print(f"❌ Transcription failed: {e}") + raise + + +if __name__ == "__main__": + + try: + # Check if audio file path is provided as argument + if len(sys.argv) > 1: + audio_path = sys.argv[1] + if not os.path.exists(audio_path): + print(f"❌ Error: Audio file not found: {audio_path}") + sys.exit(1) + print(f"📂 Using provided audio file: {audio_path}\n") + else: + # Record audio + audio_path = record_audio_file() + + # Test Groq ASR + text, latency = test_groq_asr(audio_path) + + # Print results + print("=" * 60) + print("✅ Transcription Result:") + print("=" * 60) + print(f"\n{text}\n") + print("=" * 60) + print(f"⏱️ Latency: {latency:.0f} ms ({latency/1000:.2f}s)") + print("=" * 60) + + # Play audio on macOS if it was just recorded + if len(sys.argv) == 1 and platform.system() == "Darwin": + print("\n🔊 Playing back audio...") + os.system(f"afplay '{audio_path}'") + + print("\n✅ Test completed successfully!") + + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(0) + except Exception as e: + print(f"\n❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + diff --git a/main/xiaozhi-server/core/providers/asr/test/test_openai.py b/main/xiaozhi-server/core/providers/asr/test/test_openai.py new file mode 100644 index 000000000..3e9310534 --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/test/test_openai.py @@ -0,0 +1,144 @@ +""" +OpenAI ASR (Whisper) Test + +This script tests OpenAI's official Whisper speech-to-text API. + +Usage: + # Record and transcribe + python3 -m core.providers.asr.test.test_openai + + # Transcribe existing audio file + python3 -m core.providers.asr.test.test_openai path/to/audio.wav + +Environment: + OPENAI_API_KEY - Your OpenAI API key (required) + +Examples: + export OPENAI_API_KEY="sk-proj-your_key_here" + python3 -m core.providers.asr.test.test_openai + python3 -m core.providers.asr.test.test_openai /path/to/test.wav +""" + +import sys +import os +import time +import platform + +# Check if OpenAI SDK is installed +try: + from openai import OpenAI +except ImportError: + print("❌ Error: openai package not installed") + print(" Install with: pip install openai") + sys.exit(1) + +# Import audio recorder +try: + from core.providers.asr.test.audio_recorder import record_audio_file +except ImportError: + print("❌ Error: Could not import audio_recorder") + print(" Make sure you're running from xiaozhi-server directory") + sys.exit(1) + + +def test_openai_asr(audio_file_path: str): + """ + Test OpenAI Whisper ASR with the given audio file + + Args: + audio_file_path: Path to the audio WAV file + + Returns: + Tuple of (transcribed_text, latency_ms) + """ + api_key = os.environ.get("OPENAI_API_KEY") + if not api_key: + print("❌ Error: OPENAI_API_KEY not set") + print(" export OPENAI_API_KEY='sk-proj-your_key_here'") + print("\n💡 Get your API key from: https://platform.openai.com/api-keys") + sys.exit(1) + + # model = "whisper-1" # transcription performance is low + model = "gpt-4o-transcribe" + + print(f"🤖 OpenAI ASR Test") + print(f" API: https://api.openai.com/v1") + print(f" Model: {model}") + print(f" Audio: {audio_file_path}") + + # Get file size + file_size = os.path.getsize(audio_file_path) / 1024 # KB + print(f" Size: {file_size:.1f} KB\n") + + # Initialize OpenAI client + client = OpenAI(api_key=api_key) + + try: + print("⏳ Transcribing audio...") + start_time = time.time() + + # Open audio file and send to OpenAI + with open(audio_file_path, "rb") as audio_file: + transcription = client.audio.transcriptions.create( + model=model, + file=audio_file, + response_format="text" + ) + + end_time = time.time() + latency_ms = (end_time - start_time) * 1000 + + # Get transcription text + if isinstance(transcription, str): + text = transcription + else: + text = transcription.text if hasattr(transcription, 'text') else str(transcription) + + return text, latency_ms + + except Exception as e: + print(f"❌ Transcription failed: {e}") + raise + + +if __name__ == "__main__": + try: + # Check if audio file path is provided as argument + if len(sys.argv) > 1: + audio_path = sys.argv[1] + if not os.path.exists(audio_path): + print(f"❌ Error: Audio file not found: {audio_path}") + sys.exit(1) + print(f"📂 Using provided audio file: {audio_path}\n") + else: + # Record audio + audio_path = record_audio_file() + + # Test OpenAI ASR + text, latency = test_openai_asr(audio_path) + + # Print results + print("=" * 60) + print("✅ Transcription Result:") + print("=" * 60) + print(f"\n{text}\n") + print("=" * 60) + print(f"⏱️ Latency: {latency:.0f} ms ({latency/1000:.2f}s)") + print("=" * 60) + + # Play audio on macOS if it was just recorded + if len(sys.argv) == 1 and platform.system() == "Darwin": + print("\n🔊 Playing back audio...") + os.system(f"afplay '{audio_path}'") + + print("\n✅ Test completed successfully!") + + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(0) + except Exception as e: + print(f"\n❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + diff --git a/main/xiaozhi-server/core/providers/llm/test/BENCHMARK.txt b/main/xiaozhi-server/core/providers/llm/test/BENCHMARK.txt new file mode 100644 index 000000000..2f6c9d420 --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/test/BENCHMARK.txt @@ -0,0 +1,147 @@ +LLM Model Benchmark Guide +========================= + +This benchmark script tests multiple LLM models from different providers +and generates a detailed performance comparison report. + +1. Prerequisites +---------------- + +# Set API keys +export GROQ_API_KEY="gsk_your_key_here" +export OPENROUTER_API_KEY="sk-or-v1-your_key_here" + +# Install dependencies +pip install openai + + +2. Quick Start +-------------- + +cd /Users/harold/Projects/live-agent/main/xiaozhi-server/ + +# Run the benchmark +python3 -m core.providers.llm.test.benchmark + +# Output file: core/providers/llm/test/benchmark_report.md + + +3. What Gets Tested +------------------- + +Groq Models: +- llama-3.3-70b-versatile +- openai/gpt-oss-120b +- groq/compound + +OpenRouter Models: +- openai/gpt-4o +- anthropic/claude-sonnet-4.5 +- openai/gpt-5 +- google/gemini-2.5 + + +4. Metrics Collected +-------------------- + +For each model: +✅ TTFT (Time to First Token) - How fast the model starts responding +✅ Total Latency - Complete response time +✅ Response Length - Character count +✅ Token Chunks - Number of streaming chunks +✅ Avg Token Time - Average generation speed per token + + +5. Customizing the Test +----------------------- + +Edit benchmark.py to customize: + +# Change test prompt +TEST_PROMPT = "Your custom question here" + +# Add/remove models +GROQ_MODELS = [ + "llama-3.3-70b-versatile", + "your-custom-model", +] + +OPENROUTER_MODELS = [ + "openai/gpt-4o", + "your-custom-model", +] + + +6. Output Report Structure +-------------------------- + +The generated markdown report includes: + +📊 Performance Metrics Summary + - Ranked table by TTFT (fastest to slowest) + - Failed model information + +📈 Detailed Performance Metrics + - Per-provider breakdown + - All performance metrics + +📝 Response Samples + - Preview of each model's response + +🏆 Performance Analysis + - Fastest/slowest models + - Provider comparison + - Speed differences + + +7. Example Output +----------------- + +See benchmark_report_example.md for a sample output. + +Key insights from example: +- Groq models: 234-289ms TTFT +- OpenRouter models: 412-612ms TTFT +- Groq is ~50% faster on average + + +8. Tips +------- + +✅ Run during off-peak hours for consistent results +✅ Multiple runs recommended for averaging +✅ Script includes 1-second delay between tests (rate limiting) +✅ Failed models are tracked but don't stop the benchmark +✅ Results saved automatically to benchmark_report.md + + +9. Troubleshooting +------------------ + +If models fail: +- Check API key validity +- Verify model names are correct +- Check rate limits +- Review error messages in report + +If script hangs: +- Press Ctrl+C to stop +- Partial results may be incomplete +- Re-run for complete benchmark + + +10. Advanced Usage +------------------ + +# Test specific providers only +unset OPENROUTER_API_KEY # Skip OpenRouter models + +# Run multiple times for averaging +for i in {1..3}; do + python3 -m core.providers.llm.test.benchmark + mv benchmark_report.md benchmark_report_$i.md +done + + +That's it! 🚀 + diff --git a/main/xiaozhi-server/core/providers/llm/test/QUICKSTART.txt b/main/xiaozhi-server/core/providers/llm/test/QUICKSTART.txt new file mode 100644 index 000000000..8b01c2152 --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/test/QUICKSTART.txt @@ -0,0 +1,182 @@ +LLM Test Quick Start Guide +========================== + +1. Set API Keys (one-time setup) +--------------------------------- + +Add to ~/.zshrc for permanent access: + +# Groq +echo 'export GROQ_API_KEY="gsk_your_key_here"' >> ~/.zshrc +echo 'export GROQ_MODEL="openai/gpt-oss-120b"' >> ~/.zshrc # optional + +# OpenRouter +echo 'export OPENROUTER_API_KEY="sk-or-v1-your_key_here"' >> ~/.zshrc +echo 'export OPENROUTER_MODEL="openai/gpt-4o"' >> ~/.zshrc # optional + +# OpenAI +echo 'export OPENAI_API_KEY="sk-proj-your_key_here"' >> ~/.zshrc +echo 'export OPENAI_MODEL="gpt-4o-mini"' >> ~/.zshrc # optional + +# Google Gemini +echo 'export GOOGLE_API_KEY="your_api_key_here"' >> ~/.zshrc +echo 'export GOOGLE_MODEL="gemini-2.0-flash-exp"' >> ~/.zshrc # optional + +source ~/.zshrc + + +2. Install Dependencies +----------------------- + +# Install required packages +pip install openai google-generativeai + + +3. Run Tests +------------ + +cd /Users/harold/Projects/live-agent/main/xiaozhi-server/ + +# Test with default prompt and model +python3 -m core.providers.llm.test.test_groq +python3 -m core.providers.llm.test.test_openrouter +python3 -m core.providers.llm.test.test_openai +python3 -m core.providers.llm.test.test_google + +# Test with custom prompt +python3 -m core.providers.llm.test.test_groq "What is machine learning?" +python3 -m core.providers.llm.test.test_openai "解释一下什么是人工智能" + +# Test with custom model (specify model via --model flag) +python3 -m core.providers.llm.test.test_groq --model llama-3.1-8b-instant +python3 -m core.providers.llm.test.test_openrouter --model anthropic/claude-3.5-sonnet +python3 -m core.providers.llm.test.test_openai --model gpt-4o +python3 -m core.providers.llm.test.test_google --model gemini-1.5-pro + +# Test with custom prompt and model +python3 -m core.providers.llm.test.test_groq "Tell me a joke" --model mixtral-8x7b-32768 +python3 -m core.providers.llm.test.test_openai "讲个笑话" --model gpt-4o-mini + + +4. Available Models +------------------- + +Groq Models: +- openai/gpt-oss-120b (default, fast) +- llama-3.3-70b-versatile (best balance) +- llama-3.1-8b-instant (fastest) +- mixtral-8x7b-32768 (large context) + +OpenRouter Models: +- openai/gpt-4o (default, best quality) +- openai/gpt-4o-mini (faster, cheaper) +- anthropic/claude-3.5-sonnet +- google/gemini-pro-1.5 +- meta-llama/llama-3.3-70b-instruct + +OpenAI Models: +- gpt-4o-mini (default, fast & cheap) +- gpt-4o (best quality) +- gpt-4-turbo +- gpt-3.5-turbo + +Google Gemini Models: +- gemini-2.0-flash-exp (default, fastest, experimental) +- gemini-1.5-pro (best quality) +- gemini-1.5-flash (fast & balanced) +- gemini-1.0-pro (stable) + +Set models: +export GROQ_MODEL="llama-3.1-8b-instant" +export OPENROUTER_MODEL="openai/gpt-4o-mini" +export OPENAI_MODEL="gpt-4o" +export GOOGLE_MODEL="gemini-1.5-flash" + + +5. Output Metrics +----------------- + +Test measures streaming performance: +- ⚡ TTFT (Time to First Token): How fast the model starts responding +- ⏱️ Total Latency: Total time to complete the response +- 📝 Response Length: Character count +- 🔢 Token Chunks: Number of chunks received +- 🚀 Avg Time per Token: Average generation speed + + +6. Example Output +----------------- + +🤖 Groq LLM Test (Streaming) + API: https://api.groq.com/openai/v1 + Model: llama-3.3-70b-versatile + Prompt: Hello! Please introduce yourself briefly in 2-3... + +⏳ Generating response... + +============================================================ +Hello! I'm an AI assistant powered by Groq. I'm designed +to be helpful, informative, and conversational. How can I +assist you today? +============================================================ + +📊 Performance Metrics: + ⚡ TTFT (Time to First Token): 234 ms + ⏱️ Total Latency: 1567 ms (1.57s) + 📝 Response Length: 123 characters + 🔢 Token Chunks: 45 + 🚀 Avg Time per Token: 29.6 ms + +✅ Test completed successfully! + + +7. Troubleshooting +------------------ + +If API key error: + echo $GROQ_API_KEY # Check Groq key + echo $OPENROUTER_API_KEY # Check OpenRouter key + echo $OPENAI_API_KEY # Check OpenAI key + echo $GOOGLE_API_KEY # Check Google key + source ~/.zshrc # Reload config + +If packages not installed: + pip install openai google-generativeai + +If module not found: + cd /Users/harold/Projects/live-agent/main/xiaozhi-server/ + # Make sure you're in the right directory! + +Get API keys: + Groq: https://console.groq.com/keys + OpenRouter: https://openrouter.ai/keys + OpenAI: https://platform.openai.com/api-keys + Google: https://aistudio.google.com/apikey + + +8. Benchmark Multiple Models +---------------------------- + +Run benchmark to test multiple models and generate performance report: + +cd /Users/harold/Projects/live-agent/main/xiaozhi-server/ + +# Run benchmark (requires both GROQ_API_KEY and OPENROUTER_API_KEY) +python3 -m core.providers.llm.test.benchmark + +# Output: benchmark_report.md with detailed performance comparison + + +9. Tips +------- + +- TTFT is crucial for chat applications (aim for <500ms) +- Groq is known for extremely fast inference speed +- Lower TTFT = better user experience +- Token chunks count may vary based on response length +- Adjust temperature (0-2) in code for creativity control +- Use benchmark script to compare multiple models at once + + +That's it! 🎉 + diff --git a/main/xiaozhi-server/core/providers/llm/test/__init__.py b/main/xiaozhi-server/core/providers/llm/test/__init__.py new file mode 100644 index 000000000..530e0b827 --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/test/__init__.py @@ -0,0 +1,2 @@ +# LLM Test Module + diff --git a/main/xiaozhi-server/core/providers/llm/test/benchmark.py b/main/xiaozhi-server/core/providers/llm/test/benchmark.py new file mode 100644 index 000000000..b173bfc7e --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/test/benchmark.py @@ -0,0 +1,379 @@ +""" +LLM Model Benchmark Script + +This script tests multiple LLM models from different providers with the same prompt +and generates a markdown report comparing their performance metrics. + +Usage: + python3 -m core.providers.llm.test.benchmark + +Environment: + GROQ_API_KEY - Your Groq API key (required for Groq models) + OPENROUTER_API_KEY - Your OpenRouter API key (required for OpenRouter models) + OPENAI_API_KEY - Your OpenAI API key (required for OpenAI models) + +Output: + benchmark_report.md - Performance comparison report +""" + +import sys +import os +import time +from datetime import datetime + +# Check if OpenAI SDK is installed +try: + from openai import OpenAI +except ImportError: + print("❌ Error: openai package not installed") + print(" Install with: pip install openai") + sys.exit(1) + + +# Test configuration +TEST_PROMPT = "What is artificial intelligence? Please explain in 2-3 sentences." + +GROQ_MODELS = [ + "llama-3.3-70b-versatile", + "openai/gpt-oss-120b", + "groq/compound", + "openai/gpt-oss-20b" +] + +OPENROUTER_MODELS = [ + "openai/gpt-4o", + "anthropic/claude-sonnet-4.5", + "openai/gpt-oss-120b", + "openai/gpt-oss-20b" +] + +OPENAI_MODELS = [ + "gpt-4o", + "gpt-4o-mini", + "gpt-4-turbo", +] + + +def test_model(provider: str, model: str, prompt: str, api_key: str, base_url: str): + """ + Test a single model and return performance metrics + + Args: + provider: Provider name (e.g., "Groq", "OpenRouter") + model: Model name + prompt: Test prompt + api_key: API key + base_url: API base URL + + Returns: + dict with metrics or None if failed + """ + try: + print(f" Testing {provider}/{model}... ", end="", flush=True) + + client = OpenAI(api_key=api_key, base_url=base_url) + + start_time = time.time() + ttft = None + full_response = "" + token_count = 0 + + # Create streaming chat completion + stream = client.chat.completions.create( + model=model, + messages=[{"role": "user", "content": prompt}], + stream=True, + max_tokens=1024, + temperature=0.7 + ) + + # Process stream + for chunk in stream: + if chunk.choices[0].delta.content: + content = chunk.choices[0].delta.content + + if ttft is None: + ttft = (time.time() - start_time) * 1000 + + full_response += content + token_count += 1 + + end_time = time.time() + total_latency = (end_time - start_time) * 1000 + + print(f"✅ TTFT: {ttft:.0f}ms") + + return { + "provider": provider, + "model": model, + "ttft": ttft, + "total_latency": total_latency, + "response_length": len(full_response), + "token_count": token_count, + "response": full_response[:100] + "..." if len(full_response) > 100 else full_response, + "success": True + } + + except Exception as e: + print(f"❌ Failed: {str(e)[:50]}") + return { + "provider": provider, + "model": model, + "error": str(e), + "success": False + } + + +def generate_markdown_report(results: list, prompt: str): + """ + Generate a markdown report from test results + + Args: + results: List of test results + prompt: The test prompt used + + Returns: + str: Markdown formatted report + """ + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + md = f"""# LLM Model Benchmark Report + +**Generated:** {timestamp} + +## Test Configuration + +**Test Prompt:** +``` +{prompt} +``` + +**Tested Models:** +- Groq: {len([r for r in results if r['provider'] == 'Groq'])} models +- OpenRouter: {len([r for r in results if r['provider'] == 'OpenRouter'])} models +- OpenAI: {len([r for r in results if r['provider'] == 'OpenAI'])} models + +--- + +## Performance Metrics Summary + +### Time to First Token (TTFT) Comparison + +Lower is better. This metric indicates how quickly the model starts responding. + +| Rank | Provider | Model | TTFT (ms) | Status | +|------|----------|-------|-----------|--------| +""" + + # Sort by TTFT + successful_results = [r for r in results if r['success']] + sorted_by_ttft = sorted(successful_results, key=lambda x: x['ttft']) + + for i, result in enumerate(sorted_by_ttft, 1): + ttft = f"{result['ttft']:.0f}" if result['ttft'] else "N/A" + status = "✅" if result['success'] else "❌" + md += f"| {i} | {result['provider']} | `{result['model']}` | **{ttft}** | {status} |\n" + + # Failed models + failed_results = [r for r in results if not r['success']] + if failed_results: + md += "\n### Failed Models\n\n" + md += "| Provider | Model | Error |\n" + md += "|----------|-------|-------|\n" + for result in failed_results: + error = result.get('error', 'Unknown error')[:50] + md += f"| {result['provider']} | `{result['model']}` | {error} |\n" + + md += "\n---\n\n" + + # Detailed metrics + md += "## Detailed Performance Metrics\n\n" + + for provider in ["Groq", "OpenRouter", "OpenAI"]: + provider_results = [r for r in successful_results if r['provider'] == provider] + if not provider_results: + continue + + md += f"### {provider} Models\n\n" + md += "| Model | TTFT (ms) | Total Latency (ms) | Response Length | Token Chunks | Avg Token Time (ms) |\n" + md += "|-------|-----------|-------------------|-----------------|--------------|--------------------|\n" + + for result in sorted(provider_results, key=lambda x: x['ttft']): + ttft = f"{result['ttft']:.0f}" + total = f"{result['total_latency']:.0f}" + length = result['response_length'] + tokens = result['token_count'] + avg_token = f"{(result['total_latency'] - result['ttft']) / tokens:.1f}" if tokens > 0 else "N/A" + + md += f"| `{result['model']}` | {ttft} | {total} | {length} | {tokens} | {avg_token} |\n" + + md += "\n" + + # Response samples + md += "## Response Samples\n\n" + for result in successful_results: + md += f"### {result['provider']} - {result['model']}\n\n" + md += f"**TTFT:** {result['ttft']:.0f}ms\n\n" + md += f"**Response Preview:**\n```\n{result['response']}\n```\n\n" + + # Performance analysis + md += "---\n\n## Performance Analysis\n\n" + + if successful_results: + fastest = min(successful_results, key=lambda x: x['ttft']) + slowest = max(successful_results, key=lambda x: x['ttft']) + avg_ttft = sum(r['ttft'] for r in successful_results) / len(successful_results) + + md += f"**Fastest Model:** `{fastest['model']}` ({fastest['provider']}) - {fastest['ttft']:.0f}ms TTFT\n\n" + md += f"**Slowest Model:** `{slowest['model']}` ({slowest['provider']}) - {slowest['ttft']:.0f}ms TTFT\n\n" + md += f"**Average TTFT:** {avg_ttft:.0f}ms\n\n" + + # Provider comparison + groq_results = [r for r in successful_results if r['provider'] == 'Groq'] + openrouter_results = [r for r in successful_results if r['provider'] == 'OpenRouter'] + openai_results = [r for r in successful_results if r['provider'] == 'OpenAI'] + + if groq_results or openrouter_results or openai_results: + md += "### Provider Comparison\n\n" + + if groq_results: + groq_avg = sum(r['ttft'] for r in groq_results) / len(groq_results) + md += f"- **Groq Average TTFT:** {groq_avg:.0f}ms\n" + + if openrouter_results: + openrouter_avg = sum(r['ttft'] for r in openrouter_results) / len(openrouter_results) + md += f"- **OpenRouter Average TTFT:** {openrouter_avg:.0f}ms\n" + + if openai_results: + openai_avg = sum(r['ttft'] for r in openai_results) / len(openai_results) + md += f"- **OpenAI Average TTFT:** {openai_avg:.0f}ms\n" + + md += "\n" + + md += "---\n\n" + md += "*Report generated by LLM Benchmark Script*\n" + + return md + + +def main(): + """Main benchmark execution""" + print("=" * 60) + print("LLM Model Benchmark") + print("=" * 60) + print(f"\nTest Prompt: {TEST_PROMPT}\n") + + # Check API keys + groq_api_key = os.environ.get("GROQ_API_KEY") + openrouter_api_key = os.environ.get("OPENROUTER_API_KEY") + openai_api_key = os.environ.get("OPENAI_API_KEY") + + if not groq_api_key: + print("⚠️ Warning: GROQ_API_KEY not set, skipping Groq models") + if not openrouter_api_key: + print("⚠️ Warning: OPENROUTER_API_KEY not set, skipping OpenRouter models") + if not openai_api_key: + print("⚠️ Warning: OPENAI_API_KEY not set, skipping OpenAI models") + + if not groq_api_key and not openrouter_api_key and not openai_api_key: + print("\n❌ Error: No API keys configured") + print(" export GROQ_API_KEY='your_key'") + print(" export OPENROUTER_API_KEY='your_key'") + print(" export OPENAI_API_KEY='your_key'") + sys.exit(1) + + print() + results = [] + + # Test Groq models + if groq_api_key: + print("📊 Testing Groq Models:") + for model in GROQ_MODELS: + result = test_model( + provider="Groq", + model=model, + prompt=TEST_PROMPT, + api_key=groq_api_key, + base_url="https://api.groq.com/openai/v1" + ) + results.append(result) + time.sleep(1) # Rate limiting + print() + + # Test OpenRouter models + if openrouter_api_key: + print("📊 Testing OpenRouter Models:") + for model in OPENROUTER_MODELS: + result = test_model( + provider="OpenRouter", + model=model, + prompt=TEST_PROMPT, + api_key=openrouter_api_key, + base_url="https://openrouter.ai/api/v1" + ) + results.append(result) + time.sleep(1) # Rate limiting + print() + + # Test OpenAI models + if openai_api_key: + print("📊 Testing OpenAI Models:") + for model in OPENAI_MODELS: + result = test_model( + provider="OpenAI", + model=model, + prompt=TEST_PROMPT, + api_key=openai_api_key, + base_url="https://api.openai.com/v1" + ) + results.append(result) + time.sleep(1) # Rate limiting + print() + + # Generate report + print("=" * 60) + print("Generating Report...") + print("=" * 60) + + markdown_report = generate_markdown_report(results, TEST_PROMPT) + + # Save to file + output_file = os.path.join( + os.path.dirname(__file__), + "benchmark_report.md" + ) + + with open(output_file, 'w', encoding='utf-8') as f: + f.write(markdown_report) + + print(f"\n✅ Report saved to: {output_file}") + + # Print summary + successful = len([r for r in results if r['success']]) + failed = len([r for r in results if not r['success']]) + + print(f"\n📊 Summary:") + print(f" Total Models Tested: {len(results)}") + print(f" Successful: {successful}") + print(f" Failed: {failed}") + + if successful > 0: + fastest = min([r for r in results if r['success']], key=lambda x: x['ttft']) + print(f"\n🏆 Fastest Model: {fastest['model']} ({fastest['provider']})") + print(f" TTFT: {fastest['ttft']:.0f}ms") + + print(f"\n✅ Benchmark completed!") + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + print("\n\n👋 Benchmark interrupted") + sys.exit(0) + except Exception as e: + print(f"\n❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + diff --git a/main/xiaozhi-server/core/providers/llm/test/benchmark_report.md b/main/xiaozhi-server/core/providers/llm/test/benchmark_report.md new file mode 100644 index 000000000..79eefff8d --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/test/benchmark_report.md @@ -0,0 +1,188 @@ +# LLM Model Benchmark Report + +**Generated:** 2025-11-11 18:37:21 + +## Test Configuration + +**Test Prompt:** +``` +What is artificial intelligence? Please explain in 2-3 sentences. +``` + +**Tested Models:** +- Groq: 4 models +- OpenRouter: 4 models +- OpenAI: 3 models + +--- + +## Performance Metrics Summary + +### Time to First Token (TTFT) Comparison + +Lower is better. This metric indicates how quickly the model starts responding. + +| Rank | Provider | Model | TTFT (ms) | Status | +|------|----------|-------|-----------|--------| +| 1 | Groq | `openai/gpt-oss-20b` | **453** | ✅ | +| 2 | Groq | `openai/gpt-oss-120b` | **455** | ✅ | +| 3 | Groq | `groq/compound` | **593** | ✅ | +| 4 | OpenRouter | `openai/gpt-oss-20b` | **1016** | ✅ | +| 5 | Groq | `llama-3.3-70b-versatile` | **1019** | ✅ | +| 6 | OpenRouter | `openai/gpt-4o` | **1429** | ✅ | +| 7 | OpenRouter | `anthropic/claude-sonnet-4.5` | **1513** | ✅ | +| 8 | OpenAI | `gpt-4o` | **1703** | ✅ | +| 9 | OpenAI | `gpt-4-turbo` | **1882** | ✅ | +| 10 | OpenAI | `gpt-4o-mini` | **1983** | ✅ | +| 11 | OpenRouter | `openai/gpt-oss-120b` | **2135** | ✅ | + +--- + +## Detailed Performance Metrics + +### Groq Models + +| Model | TTFT (ms) | Total Latency (ms) | Response Length | Token Chunks | Avg Token Time (ms) | +|-------|-----------|-------------------|-----------------|--------------|--------------------| +| `openai/gpt-oss-20b` | 453 | 530 | 416 | 76 | 1.0 | +| `openai/gpt-oss-120b` | 455 | 595 | 364 | 64 | 2.2 | +| `groq/compound` | 593 | 736 | 384 | 69 | 2.1 | +| `llama-3.3-70b-versatile` | 1019 | 1178 | 477 | 79 | 2.0 | + +### OpenRouter Models + +| Model | TTFT (ms) | Total Latency (ms) | Response Length | Token Chunks | Avg Token Time (ms) | +|-------|-----------|-------------------|-----------------|--------------|--------------------| +| `openai/gpt-oss-20b` | 1016 | 1666 | 539 | 87 | 7.5 | +| `openai/gpt-4o` | 1429 | 2238 | 362 | 60 | 13.5 | +| `anthropic/claude-sonnet-4.5` | 1513 | 2748 | 468 | 18 | 68.6 | +| `openai/gpt-oss-120b` | 2135 | 2800 | 547 | 94 | 7.1 | + +### OpenAI Models + +| Model | TTFT (ms) | Total Latency (ms) | Response Length | Token Chunks | Avg Token Time (ms) | +|-------|-----------|-------------------|-----------------|--------------|--------------------| +| `gpt-4o` | 1703 | 2367 | 393 | 62 | 10.7 | +| `gpt-4-turbo` | 1882 | 5315 | 520 | 88 | 39.0 | +| `gpt-4o-mini` | 1983 | 3797 | 400 | 64 | 28.3 | + +## Response Samples + +### Groq - llama-3.3-70b-versatile + +**TTFT:** 1019ms + +**Response Preview:** +``` +Artificial intelligence (AI) refers to the development of computer systems that can perform tasks th... +``` + +### Groq - openai/gpt-oss-120b + +**TTFT:** 455ms + +**Response Preview:** +``` +Artificial intelligence (AI) is a branch of computer science that creates systems capable of perform... +``` + +### Groq - groq/compound + +**TTFT:** 593ms + +**Response Preview:** +``` +Artificial intelligence (AI) is the field of computer science that creates systems capable of perfor... +``` + +### Groq - openai/gpt-oss-20b + +**TTFT:** 453ms + +**Response Preview:** +``` +Artificial intelligence (AI) is the field of computer science that focuses on creating systems capab... +``` + +### OpenRouter - openai/gpt-4o + +**TTFT:** 1429ms + +**Response Preview:** +``` +Artificial intelligence (AI) is a branch of computer science that focuses on creating systems capabl... +``` + +### OpenRouter - anthropic/claude-sonnet-4.5 + +**TTFT:** 1513ms + +**Response Preview:** +``` +Artificial intelligence (AI) is technology that enables computers and machines to simulate human int... +``` + +### OpenRouter - openai/gpt-oss-120b + +**TTFT:** 2135ms + +**Response Preview:** +``` +Artificial intelligence (AI) is the field of computer science that designs systems capable of perfor... +``` + +### OpenRouter - openai/gpt-oss-20b + +**TTFT:** 1016ms + +**Response Preview:** +``` +Artificial intelligence (AI) is a branch of computer science that creates systems capable of perform... +``` + +### OpenAI - gpt-4o + +**TTFT:** 1703ms + +**Response Preview:** +``` +Artificial intelligence (AI) refers to the development of computer systems and software that can per... +``` + +### OpenAI - gpt-4o-mini + +**TTFT:** 1983ms + +**Response Preview:** +``` +Artificial intelligence (AI) refers to the simulation of human intelligence processes by computer sy... +``` + +### OpenAI - gpt-4-turbo + +**TTFT:** 1882ms + +**Response Preview:** +``` +Artificial intelligence (AI) refers to the simulation of human intelligence in machines that are pro... +``` + +--- + +## Performance Analysis + +**Fastest Model:** `openai/gpt-oss-20b` (Groq) - 453ms TTFT + +**Slowest Model:** `openai/gpt-oss-120b` (OpenRouter) - 2135ms TTFT + +**Average TTFT:** 1289ms + +### Provider Comparison + +- **Groq Average TTFT:** 630ms +- **OpenRouter Average TTFT:** 1523ms +- **OpenAI Average TTFT:** 1856ms + +--- + +*Report generated by LLM Benchmark Script* diff --git a/main/xiaozhi-server/core/providers/llm/test/test_google.py b/main/xiaozhi-server/core/providers/llm/test/test_google.py new file mode 100644 index 000000000..0b97542a5 --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/test/test_google.py @@ -0,0 +1,162 @@ +""" +Google Gemini LLM Test (Streaming with TTFT Measurement) + +This script tests Google's Gemini API using streaming mode. +Focuses on measuring Time to First Token (TTFT) latency. + +Usage: + # Default prompt and model + python3 -m core.providers.llm.test.test_google + + # Custom prompt + python3 -m core.providers.llm.test.test_google "What is the capital of France?" + + # Custom model + python3 -m core.providers.llm.test.test_google --model gemini-1.5-pro + + # Custom prompt and model + python3 -m core.providers.llm.test.test_google "Tell me a joke" --model gemini-1.5-flash + +Environment: + GOOGLE_API_KEY - Your Google AI API key (required) + GOOGLE_MODEL - Default model name (optional, default: gemini-2.0-flash-exp) + +Examples: + export GOOGLE_API_KEY="your_api_key_here" + python3 -m core.providers.llm.test.test_google + python3 -m core.providers.llm.test.test_google "解释一下什么是人工智能" + python3 -m core.providers.llm.test.test_google --model gemini-1.0-pro +""" + +import sys +import os +import time + +# Check if Google Generative AI SDK is installed +try: + import google.generativeai as genai +except ImportError: + print("❌ Error: google-generativeai package not installed") + print(" Install with: pip install google-generativeai") + sys.exit(1) + + +def test_google_llm_streaming(prompt: str, model_name: str = None): + """ + Test Google Gemini LLM with streaming mode and measure TTFT + + Args: + prompt: User prompt text + model_name: Model name (optional, uses env or default) + + Returns: + Tuple of (response_text, ttft_ms, total_latency_ms, token_count) + """ + api_key = os.environ.get("GOOGLE_API_KEY") + if not api_key: + print("❌ Error: GOOGLE_API_KEY not set") + print(" export GOOGLE_API_KEY='your_api_key_here'") + print("\n💡 Get your API key from: https://aistudio.google.com/apikey") + sys.exit(1) + + if model_name is None: + model_name = os.environ.get("GOOGLE_MODEL", "gemini-2.0-flash-exp") + + print(f"🤖 Google Gemini LLM Test (Streaming)") + print(f" API: Google AI Studio") + print(f" Model: {model_name}") + print(f" Prompt: {prompt[:50]}{'...' if len(prompt) > 50 else ''}\n") + + # Configure Google AI + genai.configure(api_key=api_key) + + try: + print("⏳ Generating response...\n") + print("=" * 60) + + # Initialize model + model = genai.GenerativeModel(model_name) + + start_time = time.time() + ttft = None + full_response = "" + token_count = 0 + + # Generate content with streaming + response = model.generate_content( + prompt, + stream=True, + generation_config=genai.types.GenerationConfig( + max_output_tokens=1024, + temperature=0.7, + ) + ) + + # Process stream + for chunk in response: + if chunk.text: + content = chunk.text + + # Record time to first token + if ttft is None: + ttft = (time.time() - start_time) * 1000 + + full_response += content + token_count += 1 + print(content, end="", flush=True) + + end_time = time.time() + total_latency = (end_time - start_time) * 1000 + + print("\n" + "=" * 60) + + return full_response, ttft, total_latency, token_count + + except Exception as e: + print(f"\n❌ Error: {e}") + raise + + +if __name__ == "__main__": + # Parse command line arguments + prompt = "Hello! Please introduce yourself briefly in 2-3 sentences." + model = None + + args = sys.argv[1:] + i = 0 + while i < len(args): + if args[i] == "--model" and i + 1 < len(args): + model = args[i + 1] + i += 2 + elif not args[i].startswith("--"): + prompt = args[i] + i += 1 + else: + i += 1 + + try: + # Run streaming test + response, ttft, total_latency, token_count = test_google_llm_streaming(prompt, model) + + # Print metrics + print(f"\n📊 Performance Metrics:") + print(f" ⚡ TTFT (Time to First Token): {ttft:.0f} ms") + print(f" ⏱️ Total Latency: {total_latency:.0f} ms ({total_latency/1000:.2f}s)") + print(f" 📝 Response Length: {len(response)} characters") + print(f" 🔢 Token Chunks: {token_count}") + + if token_count > 0 and total_latency > ttft: + avg_token_time = (total_latency - ttft) / token_count + print(f" 🚀 Avg Time per Token: {avg_token_time:.1f} ms") + + print("\n✅ Test completed successfully!") + + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(0) + except Exception as e: + print(f"\n❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + diff --git a/main/xiaozhi-server/core/providers/llm/test/test_groq.py b/main/xiaozhi-server/core/providers/llm/test/test_groq.py new file mode 100644 index 000000000..178847fff --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/test/test_groq.py @@ -0,0 +1,163 @@ +""" +Groq LLM Test (Streaming with TTFT Measurement) + +This script tests Groq's chat completion API using streaming mode. +Focuses on measuring Time to First Token (TTFT) latency. + +Usage: + # Default prompt and model + python3 -m core.providers.llm.test.test_groq + + # Custom prompt + python3 -m core.providers.llm.test.test_groq "What is the capital of France?" + + # Custom model + python3 -m core.providers.llm.test.test_groq --model llama-3.3-70b-versatile + + # Custom prompt and model + python3 -m core.providers.llm.test.test_groq "Tell me a joke" --model llama-3.1-8b-instant + +Environment: + GROQ_API_KEY - Your Groq API key (required) + GROQ_MODEL - Default model name (optional, default: openai/gpt-oss-120b) + +Examples: + export GROQ_API_KEY="gsk_your_key_here" + python3 -m core.providers.llm.test.test_groq + python3 -m core.providers.llm.test.test_groq "解释一下什么是人工智能" + python3 -m core.providers.llm.test.test_groq --model mixtral-8x7b-32768 +""" + +import sys +import os +import time + +# Check if OpenAI SDK is installed +try: + from openai import OpenAI +except ImportError: + print("❌ Error: openai package not installed") + print(" Install with: pip install openai") + sys.exit(1) + + +def test_groq_llm_streaming(prompt: str, model: str = None): + """ + Test Groq LLM with streaming mode and measure TTFT + + Args: + prompt: User prompt text + model: Model name (optional, uses env or default) + + Returns: + Tuple of (response_text, ttft_ms, total_latency_ms, token_count) + """ + api_key = os.environ.get("GROQ_API_KEY") + if not api_key: + print("❌ Error: GROQ_API_KEY not set") + print(" export GROQ_API_KEY='gsk_your_key_here'") + print("\n💡 Get your API key from: https://console.groq.com/keys") + sys.exit(1) + + if model is None: + model = os.environ.get("GROQ_MODEL", "openai/gpt-oss-120b") + + print(f"🤖 Groq LLM Test (Streaming)") + print(f" API: https://api.groq.com/openai/v1") + print(f" Model: {model}") + print(f" Prompt: {prompt[:50]}{'...' if len(prompt) > 50 else ''}\n") + + # Initialize OpenAI client with Groq endpoint + client = OpenAI( + api_key=api_key, + base_url="https://api.groq.com/openai/v1" + ) + + try: + print("⏳ Generating response...\n") + print("=" * 60) + + start_time = time.time() + ttft = None + full_response = "" + token_count = 0 + + # Create streaming chat completion + stream = client.chat.completions.create( + model=model, + messages=[ + {"role": "user", "content": prompt} + ], + stream=True, + max_tokens=1024, + temperature=0.7 + ) + + # Process stream + for chunk in stream: + if chunk.choices[0].delta.content: + content = chunk.choices[0].delta.content + + # Record time to first token + if ttft is None: + ttft = (time.time() - start_time) * 1000 + + full_response += content + token_count += 1 + print(content, end="", flush=True) + + end_time = time.time() + total_latency = (end_time - start_time) * 1000 + + print("\n" + "=" * 60) + + return full_response, ttft, total_latency, token_count + + except Exception as e: + print(f"\n❌ Error: {e}") + raise + + +if __name__ == "__main__": + # Parse command line arguments + prompt = "Hello! Please introduce yourself briefly in 2-3 sentences." + model = None + + args = sys.argv[1:] + i = 0 + while i < len(args): + if args[i] == "--model" and i + 1 < len(args): + model = args[i + 1] + i += 2 + elif not args[i].startswith("--"): + prompt = args[i] + i += 1 + else: + i += 1 + + try: + # Run streaming test + response, ttft, total_latency, token_count = test_groq_llm_streaming(prompt, model) + + # Print metrics + print(f"\n📊 Performance Metrics:") + print(f" ⚡ TTFT (Time to First Token): {ttft:.0f} ms") + print(f" ⏱️ Total Latency: {total_latency:.0f} ms ({total_latency/1000:.2f}s)") + print(f" 📝 Response Length: {len(response)} characters") + print(f" 🔢 Token Chunks: {token_count}") + + if token_count > 0 and total_latency > ttft: + avg_token_time = (total_latency - ttft) / token_count + print(f" 🚀 Avg Time per Token: {avg_token_time:.1f} ms") + + print("\n✅ Test completed successfully!") + + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(0) + except Exception as e: + print(f"\n❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + diff --git a/main/xiaozhi-server/core/providers/llm/test/test_openai.py b/main/xiaozhi-server/core/providers/llm/test/test_openai.py new file mode 100644 index 000000000..f971d9804 --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/test/test_openai.py @@ -0,0 +1,160 @@ +""" +OpenAI LLM Test (Streaming with TTFT Measurement) + +This script tests OpenAI's chat completion API using streaming mode. +Focuses on measuring Time to First Token (TTFT) latency. + +Usage: + # Default prompt and model + python3 -m core.providers.llm.test.test_openai + + # Custom prompt + python3 -m core.providers.llm.test.test_openai "What is the capital of France?" + + # Custom model + python3 -m core.providers.llm.test.test_openai --model gpt-4o + + # Custom prompt and model + python3 -m core.providers.llm.test.test_openai "Tell me a joke" --model gpt-4-turbo + +Environment: + OPENAI_API_KEY - Your OpenAI API key (required) + OPENAI_MODEL - Default model name (optional, default: gpt-4o-mini) + +Examples: + export OPENAI_API_KEY="sk-proj-your_key_here" + python3 -m core.providers.llm.test.test_openai + python3 -m core.providers.llm.test.test_openai "解释一下什么是人工智能" + python3 -m core.providers.llm.test.test_openai --model gpt-3.5-turbo +""" + +import sys +import os +import time + +# Check if OpenAI SDK is installed +try: + from openai import OpenAI +except ImportError: + print("❌ Error: openai package not installed") + print(" Install with: pip install openai") + sys.exit(1) + + +def test_openai_llm_streaming(prompt: str, model: str = None): + """ + Test OpenAI LLM with streaming mode and measure TTFT + + Args: + prompt: User prompt text + model: Model name (optional, uses env or default) + + Returns: + Tuple of (response_text, ttft_ms, total_latency_ms, token_count) + """ + api_key = os.environ.get("OPENAI_API_KEY") + if not api_key: + print("❌ Error: OPENAI_API_KEY not set") + print(" export OPENAI_API_KEY='sk-proj-your_key_here'") + print("\n💡 Get your API key from: https://platform.openai.com/api-keys") + sys.exit(1) + + if model is None: + model = os.environ.get("OPENAI_MODEL", "gpt-4o-mini") + + print(f"🤖 OpenAI LLM Test (Streaming)") + print(f" API: https://api.openai.com/v1") + print(f" Model: {model}") + print(f" Prompt: {prompt[:50]}{'...' if len(prompt) > 50 else ''}\n") + + # Initialize OpenAI client + client = OpenAI(api_key=api_key) + + try: + print("⏳ Generating response...\n") + print("=" * 60) + + start_time = time.time() + ttft = None + full_response = "" + token_count = 0 + + # Create streaming chat completion + stream = client.chat.completions.create( + model=model, + messages=[ + {"role": "user", "content": prompt} + ], + stream=True, + max_tokens=1024, + temperature=0.7 + ) + + # Process stream + for chunk in stream: + if chunk.choices[0].delta.content: + content = chunk.choices[0].delta.content + + # Record time to first token + if ttft is None: + ttft = (time.time() - start_time) * 1000 + + full_response += content + token_count += 1 + print(content, end="", flush=True) + + end_time = time.time() + total_latency = (end_time - start_time) * 1000 + + print("\n" + "=" * 60) + + return full_response, ttft, total_latency, token_count + + except Exception as e: + print(f"\n❌ Error: {e}") + raise + + +if __name__ == "__main__": + # Parse command line arguments + prompt = "Hello! Please introduce yourself briefly in 2-3 sentences." + model = None + + args = sys.argv[1:] + i = 0 + while i < len(args): + if args[i] == "--model" and i + 1 < len(args): + model = args[i + 1] + i += 2 + elif not args[i].startswith("--"): + prompt = args[i] + i += 1 + else: + i += 1 + + try: + # Run streaming test + response, ttft, total_latency, token_count = test_openai_llm_streaming(prompt, model) + + # Print metrics + print(f"\n📊 Performance Metrics:") + print(f" ⚡ TTFT (Time to First Token): {ttft:.0f} ms") + print(f" ⏱️ Total Latency: {total_latency:.0f} ms ({total_latency/1000:.2f}s)") + print(f" 📝 Response Length: {len(response)} characters") + print(f" 🔢 Token Chunks: {token_count}") + + if token_count > 0 and total_latency > ttft: + avg_token_time = (total_latency - ttft) / token_count + print(f" 🚀 Avg Time per Token: {avg_token_time:.1f} ms") + + print("\n✅ Test completed successfully!") + + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(0) + except Exception as e: + print(f"\n❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + diff --git a/main/xiaozhi-server/core/providers/llm/test/test_openrouter.py b/main/xiaozhi-server/core/providers/llm/test/test_openrouter.py new file mode 100644 index 000000000..257d8d66e --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/test/test_openrouter.py @@ -0,0 +1,168 @@ +""" +OpenRouter LLM Test (Streaming with TTFT Measurement) + +This script tests OpenRouter's chat completion API using streaming mode. +Focuses on measuring Time to First Token (TTFT) latency. + +Usage: + # Default prompt and model + python3 -m core.providers.llm.test.test_openrouter + + # Custom prompt + python3 -m core.providers.llm.test.test_openrouter "What is the capital of France?" + + # Custom model + python3 -m core.providers.llm.test.test_openrouter --model openai/gpt-4o-mini + + # Custom prompt and model + python3 -m core.providers.llm.test.test_openrouter "Tell me a joke" --model anthropic/claude-3.5-sonnet + +Environment: + OPENROUTER_API_KEY - Your OpenRouter API key (required) + OPENROUTER_MODEL - Default model name (optional, default: openai/gpt-4o) + +Examples: + export OPENROUTER_API_KEY="sk-or-v1-your_key_here" + python3 -m core.providers.llm.test.test_openrouter + python3 -m core.providers.llm.test.test_openrouter "解释一下什么是人工智能" + python3 -m core.providers.llm.test.test_openrouter --model google/gemini-pro-1.5 +""" + +import sys +import os +import time + +# Check if OpenAI SDK is installed +try: + from openai import OpenAI +except ImportError: + print("❌ Error: openai package not installed") + print(" Install with: pip install openai") + sys.exit(1) + + +def test_openrouter_llm_streaming(prompt: str, model: str = None): + """ + Test OpenRouter LLM with streaming mode and measure TTFT + + Args: + prompt: User prompt text + model: Model name (optional, uses env or default) + + Returns: + Tuple of (response_text, ttft_ms, total_latency_ms, token_count) + """ + api_key = os.environ.get("OPENROUTER_API_KEY") + if not api_key: + print("❌ Error: OPENROUTER_API_KEY not set") + print(" export OPENROUTER_API_KEY='sk-or-v1-your_key_here'") + print("\n💡 Get your API key from: https://openrouter.ai/keys") + sys.exit(1) + + if model is None: + model = os.environ.get("OPENROUTER_MODEL", "openai/gpt-4o") + + print(f"🤖 OpenRouter LLM Test (Streaming)") + print(f" API: https://openrouter.ai/api/v1") + print(f" Model: {model}") + print(f" Prompt: {prompt[:50]}{'...' if len(prompt) > 50 else ''}\n") + + # Initialize OpenAI client with OpenRouter endpoint + client = OpenAI( + api_key=api_key, + base_url="https://openrouter.ai/api/v1" + ) + + try: + print("⏳ Generating response...\n") + print("=" * 60) + + start_time = time.time() + ttft = None + full_response = "" + token_count = 0 + + # Create streaming chat completion + # OpenRouter supports additional headers for better tracking + stream = client.chat.completions.create( + model=model, + messages=[ + {"role": "user", "content": prompt} + ], + stream=True, + max_tokens=1024, + temperature=0.7, + extra_headers={ + "HTTP-Referer": "https://github.com/ai-bot-pro/live-agent", + "X-Title": "Live Agent Test" + } + ) + + # Process stream + for chunk in stream: + if chunk.choices[0].delta.content: + content = chunk.choices[0].delta.content + + # Record time to first token + if ttft is None: + ttft = (time.time() - start_time) * 1000 + + full_response += content + token_count += 1 + print(content, end="", flush=True) + + end_time = time.time() + total_latency = (end_time - start_time) * 1000 + + print("\n" + "=" * 60) + + return full_response, ttft, total_latency, token_count + + except Exception as e: + print(f"\n❌ Error: {e}") + raise + + +if __name__ == "__main__": + # Parse command line arguments + prompt = "Hello! Please introduce yourself briefly in 2-3 sentences." + model = None + + args = sys.argv[1:] + i = 0 + while i < len(args): + if args[i] == "--model" and i + 1 < len(args): + model = args[i + 1] + i += 2 + elif not args[i].startswith("--"): + prompt = args[i] + i += 1 + else: + i += 1 + + try: + # Run streaming test + response, ttft, total_latency, token_count = test_openrouter_llm_streaming(prompt, model) + + # Print metrics + print(f"\n📊 Performance Metrics:") + print(f" ⚡ TTFT (Time to First Token): {ttft:.0f} ms") + print(f" ⏱️ Total Latency: {total_latency:.0f} ms ({total_latency/1000:.2f}s)") + print(f" 📝 Response Length: {len(response)} characters") + print(f" 🔢 Token Chunks: {token_count}") + + if token_count > 0 and total_latency > ttft: + avg_token_time = (total_latency - ttft) / token_count + print(f" 🚀 Avg Time per Token: {avg_token_time:.1f} ms") + + print("\n✅ Test completed successfully!") + + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(0) + except Exception as e: + print(f"\n❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + From 8b4f197b31ed6a2e477fa20c17dd41ffc1338319 Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 12 Nov 2025 13:57:21 +0800 Subject: [PATCH 2/4] feat: asr integration && test_page audio process --- main/xiaozhi-server/core/providers/asr/openai.py | 6 +++--- main/xiaozhi-server/test/test_page.html | 11 +++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/main/xiaozhi-server/core/providers/asr/openai.py b/main/xiaozhi-server/core/providers/asr/openai.py index 5cad3460b..d789911e2 100644 --- a/main/xiaozhi-server/core/providers/asr/openai.py +++ b/main/xiaozhi-server/core/providers/asr/openai.py @@ -45,16 +45,16 @@ class ASRProvider(ASRProviderBase): with open(file_path, "rb") as audio_file: # with open to ensure file is closed start_time = time.time() - transcription: Transcription = self._client.audio.transcriptions.create( + transcription: str = self._client.audio.transcriptions.create( model=self.model, file=audio_file, response_format="text" ) logger.bind(tag=TAG).debug( - f"Audio transcription latency: {time.time() - start_time:.3f}s | Result: {transcription.text}" + f"Audio transcription latency: {time.time() - start_time:.3f}s | Result: {transcription}" ) - return transcription.text, file_path + return transcription, file_path except Exception as e: logger.bind(tag=TAG).error(f"Audio transcription failed: {e}") diff --git a/main/xiaozhi-server/test/test_page.html b/main/xiaozhi-server/test/test_page.html index a6672dbcb..f3183ef2c 100644 --- a/main/xiaozhi-server/test/test_page.html +++ b/main/xiaozhi-server/test/test_page.html @@ -1430,6 +1430,12 @@ }; log('使用AudioWorklet处理音频', 'success'); + // 需要连接输出,否则不会触发处理 + // 我们创建一个静音通道 + const silent = audioContext.createGain(); + silent.gain.value = 0; + audioProcessor.connect(silent); + silent.connect(audioContext.destination); return { node: audioProcessor, type: 'worklet' }; } else { // 使用旧版ScriptProcessorNode作为回退方案 @@ -1604,6 +1610,11 @@ // 创建音频上下文和分析器 audioContext = getAudioContextInstance(); + // 浏览器出于安全和性能考虑,新创建的 AudioContext 默认处于 suspended 状态,必须显式调用 resume() 才会开始处理音频。 + if (audioContext.state === 'suspended') { + await audioContext.resume(); + } + // 创建音频处理器 const processorResult = await createAudioProcessor(); if (!processorResult) { From 97739bea9e08162b7bcc2247c48d2147c9adcba9 Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 12 Nov 2025 16:17:57 +0800 Subject: [PATCH 3/4] fix: client_voice_stop doesn't change if listen_mode is manual --- main/xiaozhi-server/core/providers/asr/openai.py | 2 +- main/xiaozhi-server/core/providers/vad/silero.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/main/xiaozhi-server/core/providers/asr/openai.py b/main/xiaozhi-server/core/providers/asr/openai.py index d789911e2..bd089070c 100644 --- a/main/xiaozhi-server/core/providers/asr/openai.py +++ b/main/xiaozhi-server/core/providers/asr/openai.py @@ -50,7 +50,7 @@ class ASRProvider(ASRProviderBase): file=audio_file, response_format="text" ) - logger.bind(tag=TAG).debug( + logger.bind(tag=TAG).info( f"Audio transcription latency: {time.time() - start_time:.3f}s | Result: {transcription}" ) diff --git a/main/xiaozhi-server/core/providers/vad/silero.py b/main/xiaozhi-server/core/providers/vad/silero.py index 2263fcb73..9270e4bef 100644 --- a/main/xiaozhi-server/core/providers/vad/silero.py +++ b/main/xiaozhi-server/core/providers/vad/silero.py @@ -78,7 +78,8 @@ class VADProvider(VADProviderBase): if conn.client_have_voice and not client_have_voice: stop_duration = time.time() * 1000 - conn.last_activity_time if stop_duration >= self.silence_threshold_ms: - conn.client_voice_stop = True + if conn.client_listen_mode != "manual": + conn.client_voice_stop = True if client_have_voice: conn.client_have_voice = True conn.last_activity_time = time.time() * 1000 From 03752cc6ab04302b508a33f4755ca5656cbb3a2f Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 12 Nov 2025 16:21:30 +0800 Subject: [PATCH 4/4] feat: log --- main/xiaozhi-server/core/providers/asr/openai.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main/xiaozhi-server/core/providers/asr/openai.py b/main/xiaozhi-server/core/providers/asr/openai.py index bd089070c..d789911e2 100644 --- a/main/xiaozhi-server/core/providers/asr/openai.py +++ b/main/xiaozhi-server/core/providers/asr/openai.py @@ -50,7 +50,7 @@ class ASRProvider(ASRProviderBase): file=audio_file, response_format="text" ) - logger.bind(tag=TAG).info( + logger.bind(tag=TAG).debug( f"Audio transcription latency: {time.time() - start_time:.3f}s | Result: {transcription}" )