### Install Dependencies and Run Web Server Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Installs project dependencies and starts the web server. Ensure you are in the project directory and have Python 3.11+ installed. ```bash cd ~/activi-dev-repos/stepsales # Install dependencies pip install -r requirements.txt # Run web server python web_server.py ``` -------------------------------- ### Install Dependencies and Configure API Key Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Install project dependencies using pip and configure your OpenAI API key by copying the example environment file and editing it. ```bash pip install -r requirements.txt cp .env.example .env # Edit .env and add your OPENAI_API_KEY ``` -------------------------------- ### Start Web Server Source: https://context7.com/dsactivi-2/stepsales/llms.txt Initiate the FastAPI-based web server by running the web_server.py script. The server will be accessible at http://localhost:8010. ```bash python web_server.py ``` -------------------------------- ### Run Agent Initialization Test Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Execute the main agent script to test its initialization. This command should start the agent and display expected output if configured correctly. ```bash python telesales_agent.py ``` -------------------------------- ### Clone Repository and Setup Virtual Environment Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Clone the Stepsales repository and set up a Python virtual environment for dependency management. Ensure you are using Python 3.11 or higher. ```bash cd ~/activi-dev-repos/stepsales python3.11 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate ``` -------------------------------- ### Run Local Python Server Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Start the local Python web server after loading environment variables. Ensure the virtual environment is activated. ```bash set -a && source environment/.env && set +a && .venv/bin/python web_server.py ``` -------------------------------- ### Docker Compose Deployment Source: https://context7.com/dsactivi-2/stepsales/llms.txt Commands for building, starting, viewing logs, checking health, and stopping Docker Compose services for the StepSales agent, Qdrant, and Neo4j. ```bash # Build and start all services docker compose up -d # Services started: # - stepsales-agent (port 8010) # - qdrant-stepsales (port 6333, 6334) # - neo4j-stepsales (port 7474, 7687) # View logs docker compose logs -f stepsales-agent # Health check curl http://localhost:8010/health # Stop services docker compose down ``` -------------------------------- ### Environment File Configuration (.env) Source: https://context7.com/dsactivi-2/stepsales/llms.txt Example .env file for configuring various services including OpenAI, Telnyx, Deepgram, ElevenLabs, Stripe, and application runtime settings. ```dotenv # .env file configuration OPENAI_API_KEY=sk-proj-xxxxx TELNYX_API_KEY=xxxxx TELNYX_CONNECTION_ID=xxxxx TELNYX_FROM_NUMBER=+49xxxxx DEEPGRAM_API_KEY=xxxxx ELEVENLABS_API_KEY=xxxxx ELEVENLABS_VOICE_ID=xxxxx STRIPE_API_KEY=sk_xxxxx HOST=0.0.0.0 PORT=8010 LOG_LEVEL=INFO DATABASE_URL=sqlite:///data/stepsales.db TRANSCRIPT_DIR=data/transcripts ``` -------------------------------- ### Initialize and Use TelesalesAgent Source: https://context7.com/dsactivi-2/stepsales/llms.txt Initializes the TelesalesAgent, retrieves system prompts and tool definitions, and generates a conversational response. Also shows how to get call summaries. ```python from telesales_agent import TelesalesAgent # Initialize the agent agent = TelesalesAgent() print(f"Call ID: {agent.call_id}") # Output: Call ID: abc12345 # Get the German system prompt for OpenAI Realtime API system_prompt = agent.get_system_prompt() # Returns formatted German sales persona instructions # Get OpenAI-compatible tool definitions tools = agent.build_tool_definitions() # Returns list of 4 tool definitions: search_jobs, qualify_lead, schedule_demo, send_followup # Generate conversational response based on user input response = agent.generate_response("Wir suchen einen Software Engineer") print(response) # Output: "Danke, das hilft. Wie viele Rollen sind offen und bis wann sollen sie besetzt sein?" # Get call summary after conversation summary = agent.get_call_summary() # Returns: { # "call_id": "abc12345", # "duration_seconds": 245, # "contact_info": {"company": "TechCorp", "email": "max@techcorp.de"}, # "qualification_score": 75, # "job_interests": ["Software Engineer"], # "conversation_turns": 8, # "stage": "qualify", # "timestamp": "2026-04-22T14:30:00" # } ``` -------------------------------- ### Start Docker Compose Services Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Build and start the application services in detached mode using Docker Compose. This command ensures the Docker images are built before containers are created. ```bash docker compose up -d --build ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Builds a Docker image for the Stepsales web application and runs it as a detached container. Alternatively, use Docker Compose for multi-container setups. ```bash # Build docker build -t stepsales-web:latest . # Run docker run -d -p 8010:8010 stepsales-web:latest # Or with Docker Compose docker-compose up -d ``` -------------------------------- ### Manual API Testing with cURL Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Demonstrates how to interact with the StepSales API using cURL commands. Includes starting the web server, performing health checks, retrieving transcripts, and ending calls. ```bash # Start web server in background python web_server.py & ``` ```bash # Health check curl http://localhost:8010/health ``` ```bash # Get transcript after call curl http://localhost:8010/api/calls/{session_id}/transcript ``` ```bash # End call curl -X POST http://localhost:8010/api/calls/{session_id}/end ``` -------------------------------- ### Send Follow-up Materials via Agent Source: https://context7.com/dsactivi-2/stepsales/llms.txt Utilize the agent.handle_tool_call with the 'send_followup' tool to send case studies, pricing guides, or product briefs. Specify the recipient's email and the material type. ```python from telesales_agent import TelesalesAgent agent = TelesalesAgent() # Send a case study result = agent.handle_tool_call("send_followup", { "email": "max@techcorp.de", "material_type": "case_study" }) ``` ```python # Send pricing guide result = agent.handle_tool_call("send_followup", { "email": "max@techcorp.de", "material_type": "pricing" }) ``` ```python # Send product brief result = agent.handle_tool_call("send_followup", { "email": "max@techcorp.de", "material_type": "product_brief" }) ``` -------------------------------- ### Start Call and Audio Processing Source: https://github.com/dsactivi-2/stepsales/blob/master/static/index.html Initiates a call by requesting microphone access, setting up audio analysis, configuring a MediaRecorder, and establishing a WebSocket connection. Handles errors during microphone access. ```javascript async function startCall() { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } }); audioContext = new (window.AudioContext || window.webkitAudioContext)(); analyser = audioContext.createAnalyser(); analyser.fftSize = 256; const source = audioContext.createMediaStreamSource(stream); source.connect(analyser); mediaRecorder = new MediaRecorder(stream); mediaRecorder.ondataavailable = (e) => { if (e.data.size > 0 && isConnected) { const reader = new FileReader(); reader.onload = (event) => { const base64Audio = event.target.result.split(',')[1]; if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'user_audio', audio: base64Audio, transcript: 'User audio input' })); } }; reader.readAsDataURL(new Blob([e.data], { type: 'audio/webm' })); } }; mediaRecorder.start(1000); monitorMicLevel(); connectWebSocket(); document.getElementById('startBtn').style.display = 'none'; document.getElementById('stopBtn').style.display = 'block'; updateStatus('Verbindung wird aufgebaut...', false); callStartTime = Date.now(); durationInterval = setInterval(updateDuration, 1000); } catch (error) { showError('Mikrofonzugriff verweigert: ' + error.message); updateStatus('Fehler', false); } } ``` -------------------------------- ### Send Follow-up Tool Source: https://context7.com/dsactivi-2/stepsales/llms.txt Sends follow-up materials such as case studies, pricing guides, or product briefs to qualified leads via email. ```APIDOC ## POST /send_followup ### Description Sends follow-up materials to qualified leads via email. ### Method POST ### Endpoint /send_followup ### Parameters #### Request Body - **email** (string) - Required - The email address of the lead. - **material_type** (string) - Required - The type of material to send. Accepted values: 'case_study', 'pricing', 'product_brief'. ### Request Example ```json { "email": "max@techcorp.de", "material_type": "case_study" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **sent_to** (string) - The email address the material was sent to. - **file** (string) - The name of the file sent. - **message** (string) - A confirmation message. ### Response Example ```json { "success": true, "sent_to": "max@techcorp.de", "file": "case-study-fortune500-recruitment.pdf", "message": "Case Study wurde versendet" } ``` ``` -------------------------------- ### Retrieve Call Transcript via REST API Source: https://context7.com/dsactivi-2/stepsales/llms.txt Fetch the transcript and summary for a specific call session by sending a GET request to the /api/calls/{session_id}/transcript endpoint. ```bash curl http://localhost:8010/api/calls/session123/transcript ``` -------------------------------- ### End Call Functionality Source: https://github.com/dsactivi-2/stepsales/blob/master/static/index.html Stops the media recorder, sends an 'end_call' message via WebSocket, closes the connection, clears the duration interval, updates the status, adds a transcript message, and resets the UI for starting a new call. Requires `mediaRecorder`, `ws`, `durationInterval`, `updateStatus`, and `addTranscript` to be defined. ```javascript if (mediaRecorder && mediaRecorder.state !== 'inactive') { mediaRecorder.stop(); } if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'end_call' })); ws.close(); } clearInterval(durationInterval); updateStatus('Call beendet', false); addTranscript('System', '👋 Call beendet'); document.getElementById('startBtn').style.display = 'block'; document.getElementById('stopBtn').style.display = 'none'; ``` -------------------------------- ### Get Transcript HTTP Endpoint Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Retrieve the call transcript for a given session ID using this cURL command. The response includes session details, a list of transcript entries with timestamps, and a summary. ```bash curl http://localhost:8010/api/calls/abc123/transcript ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Define essential environment variables for runtime. Ensure the `.env` file is not committed to version control. ```bash OPENAI_API_KEY= HOST=0.0.0.0 PORT=8010 LOG_LEVEL=INFO ``` -------------------------------- ### Deploy with Docker Compose Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Build and manage StepSales agent services using Docker Compose. Recommended for ease of use and managing multiple services. ```bash # Build and start services docker compose up -d ``` ```bash # Check logs docker compose logs -f stepsales-agent ``` ```bash # Stop services docker compose down ``` -------------------------------- ### Schedule Demo Tool Source: https://context7.com/dsactivi-2/stepsales/llms.txt Books a demo appointment using the schedule_demo tool, returning confirmation details and a meeting link. Manages available time slots. ```python from telesales_agent import TelesalesAgent agent = TelesalesAgent() # Book a specific demo slot result = agent.handle_tool_call("schedule_demo", { "email": "max@techcorp.de", "preferred_date": "2026-04-24", "preferred_time": "10:00" }) print(result) # Output: # { # "success": True, # "message": "Demo gebucht für 2026-04-24 10:00", # "confirmation_email": "max@techcorp.de", # "time": "2026-04-24 10:00", # "duration_minutes": 30, # "meeting_link": "https://meet.example.com/demo/max" # } ``` -------------------------------- ### Build and Run Docker Standalone Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Build a Docker image for the StepSales agent and run it as a standalone container. Useful for custom deployments. ```bash # Build image docker build -t stepsales-agent:latest . ``` ```bash # Run container docker run -d \ -p 8010:8010 \ -e OPENAI_API_KEY=sk-proj-xxxxx \ -v ./data:/app/data \ --name stepsales-agent \ stepsales-agent:latest ``` ```bash # Check status docker ps | grep stepsales-agent ``` ```bash # View logs docker logs -f stepsales-agent ``` -------------------------------- ### Initialize Application State Source: https://github.com/dsactivi-2/stepsales/blob/master/static/index.html Sets the initial status of the application to 'Bereit' (Ready) and displays the session ID. Assumes `updateStatus` and `sessionId` are available. ```javascript updateStatus('Bereit', false); document.getElementById('id').textContent = sessionId; ``` -------------------------------- ### Check Available Slots with Agent Source: https://context7.com/dsactivi-2/stepsales/llms.txt Use the agent.handle_tool_call to check for available demo slots without making a booking. Provide email and leave date/time empty to query availability. ```python result = agent.handle_tool_call("schedule_demo", { "email": "max@techcorp.de", "preferred_date": "", "preferred_time": "" }) ``` -------------------------------- ### Configure Web Server Port and Host Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Set the host and port for the web server using environment variables in a .env file or via command line arguments. Defaults are PORT=8010 and HOST=0.0.0.0. ```bash # Host/Port (Optional) PORT=8010 HOST=0.0.0.0 # Or set via command line PORT=8080 python web_server.py ``` -------------------------------- ### Check for Environment File Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Verify the existence of the `.env` file in the `environment` directory. This is a step in diagnosing missing API key issues. ```bash ls environment/.env ``` -------------------------------- ### Initialize Stepstone Integration Source: https://context7.com/dsactivi-2/stepsales/llms.txt Set up the StepstoneIntegration class with specific search parameters like zip code, radius, and request timeout. This prepares for job searches on Stepstone.de. ```python from stepstone_integration import StepstoneIntegration import asyncio # Initialize with custom location integration = StepstoneIntegration( zip_code="10115", # Berlin radius=25, # 25km radius timeout=10 # 10 second timeout ) ``` -------------------------------- ### Create and Score Lead Object Source: https://context7.com/dsactivi-2/stepsales/llms.txt Instantiate a Lead object with detailed prospect information and calculate its qualification score. The score is automatically computed based on provided attributes. ```python from tools import Lead, crm # Create a lead with full information lead = Lead( company_name="TechCorp GmbH", contact_name="Max Müller", contact_email="max@techcorp.de", contact_phone="+49301234567", job_interests=["Software Engineer", "DevOps"], budget_range="70000-90000 EUR", timeline="In 2 Wochen", call_id="abc12345" ) # Calculate qualification score score = lead.calculate_score() print(f"Score: {score}") # Output: Score: 100 ``` -------------------------------- ### Standalone Docker Run Source: https://context7.com/dsactivi-2/stepsales/llms.txt Builds a Docker image for the StepSales agent and runs it as a detached container, mapping ports and setting environment variables. ```bash # Standalone Docker run docker build -t stepsales-agent:latest . docker run -d \ -p 8010:8010 \ -e OPENAI_API_KEY=sk-proj-xxxxx \ -e TELNYX_API_KEY=xxxxx \ -e DEEPGRAM_API_KEY=xxxxx \ -v ./data:/app/data \ --name stepsales-agent \ stepsales-agent:latest ``` -------------------------------- ### schedule_demo Tool Source: https://context7.com/dsactivi-2/stepsales/llms.txt Books a demo appointment and returns confirmation with meeting link. Manages available time slots and removes booked slots from availability. ```APIDOC ## schedule_demo Tool Books a demo appointment and returns confirmation with meeting link. Manages available time slots and removes booked slots from availability. ### Usage ```python from telesales_agent import TelesalesAgent agent = TelesalesAgent() # Book a specific demo slot result = agent.handle_tool_call("schedule_demo", { "email": "max@techcorp.de", "preferred_date": "2026-04-24", "preferred_time": "10:00" }) print(result) # Output: # { # "success": True, # "message": "Demo gebucht für 2026-04-24 10:00", # "confirmation_email": "max@techcorp.de", # "time": "2026-04-24 10:00", # "duration_minutes": 30, # "meeting_link": "https://meet.example.com/demo/max" # } ``` ### Parameters #### Request Body - **email** (string) - Required - The email address of the person to book the demo for. - **preferred_date** (string) - Required - The preferred date for the demo in YYYY-MM-DD format. - **preferred_time** (string) - Required - The preferred time for the demo in HH:MM format. ``` -------------------------------- ### Nginx Load Balancing Configuration Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Configures Nginx to listen on port 80 for stepsales.example.com, proxying requests to a backend server. Includes separate handling for WebSocket connections. ```nginx server { listen 80; server_name stepsales.example.com; location / { proxy_pass http://localhost:8010; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; } location /ws { proxy_pass http://localhost:8010; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } } ``` -------------------------------- ### Qualify Lead Tool Source: https://context7.com/dsactivi-2/stepsales/llms.txt Qualifies and saves a prospect using the qualify_lead tool. Automatically calculates a qualification score based on provided information. ```python from telesales_agent import TelesalesAgent agent = TelesalesAgent() # Qualify a lead with full information result = agent.handle_tool_call("qualify_lead", { "company_name": "TechCorp GmbH", "contact_name": "Max Müller", "contact_email": "max@techcorp.de", "contact_phone": "+49301234567", "job_interests": ["Senior Developer", "DevOps Engineer"], "budget_range": "70000-90000 EUR", "timeline": "In 2 Wochen" }) print(result) # Output: # { # "success": True, # "lead_id": "LEAD-00001", # "company": "TechCorp GmbH", # "score": 100, # "message": "Lead TechCorp GmbH gespeichert" # } # Check the agent's stored qualification score print(agent.current_qualification_score) # 100 # Scoring logic: # - Company name: +10 points # - Contact name: +10 points # - Contact email: +10 points # - Job interests provided: +20 points # - Budget range provided: +20 points # - Timeline with "Woche" or "Monat": +30 points ``` -------------------------------- ### Set Production Environment Variables Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Configure environment variables for production deployment, including API keys for future integrations and log level settings. ```bash OPENAI_API_KEY=sk-proj-xxxxx # For future Realtime API integration LOG_LEVEL=INFO ``` -------------------------------- ### Connect WebSocket Source: https://github.com/dsactivi-2/stepsales/blob/master/static/index.html Establishes a WebSocket connection to the server for real-time communication. Handles connection events, message parsing, and errors. ```javascript function connectWebSocket() { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; ws = new WebSocket(`${protocol}//${window.location.host}/ws/call/${sessionId}`); ws.onopen = () => { updateStatus('Verbunden', true); addTranscript('System', '📞 Call gestartet. Agent wartet auf Ihre Nachricht...'); console.log('WebSocket connected'); }; ws.onmessage = (event) => { try { const data = JSON.parse(event.data); if (data.type === 'agent_message') { addTranscript('Agent', data.text); } else if (data.type === 'call_ended') { updateStatus('Call beendet', false); addTranscript('System', '✅ Call beendet'); } else if (data.type === 'error') { showError(data.message); } } catch (error) { console.error('Message parse error:', error); } }; ws.onerror = (error) => { showError('WebSocket-Fehler'); console.error('WebSocket error:', error); }; ws.onclose = () => { updateStatus('Verbindung beendet', false); console.log('WebSocket closed'); }; } ``` -------------------------------- ### Configure Environment Variables in Docker Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Run the StepSales agent container with specific environment variables to customize its behavior. Essential for API keys and settings. ```bash docker run -d \ -e OPENAI_API_KEY=sk-proj-xxxxx \ -e OPENAI_MODEL=gpt-realtime-1.5 \ -e VOICE=shimmer \ -e LOG_LEVEL=INFO \ -e DEFAULT_ZIP_CODE=10115 \ stepsales-agent:latest ``` -------------------------------- ### View Real-time Logs Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Monitor agent logs in real-time using `tail -f`. Useful for live debugging and tracking agent activity. ```bash # View logs in real-time tail -f logs/stepsales.log ``` -------------------------------- ### Schedule Demo API Source: https://context7.com/dsactivi-2/stepsales/llms.txt Handles scheduling demo appointments by checking for available slots. ```APIDOC ## POST /schedule_demo ### Description Checks for available slots to schedule a demo without booking. ### Method POST ### Endpoint /schedule_demo ### Parameters #### Request Body - **email** (string) - Required - The email address of the user. - **preferred_date** (string) - Optional - The preferred date for the demo. - **preferred_time** (string) - Optional - The preferred time for the demo. ### Request Example ```json { "email": "max@techcorp.de", "preferred_date": "", "preferred_time": "" } ``` ### Response #### Success Response (200) - **available_slots** (array of strings) - A list of available time slots in 'YYYY-MM-DD HH:MM' format. ### Response Example ```json { "available_slots": ["2026-04-24 14:00", "2026-04-25 09:00"] } ``` ``` -------------------------------- ### Set OpenAI API Key Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Configure the OpenAI API key, either by exporting it as an environment variable or adding it to a .env file. Crucial for agent authentication. ```bash export OPENAI_API_KEY=sk-proj-xxxxx ``` ```bash # or echo "OPENAI_API_KEY=sk-proj-xxxxx" >> .env ``` -------------------------------- ### Monitor Server Logs with Tail and Grep Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Provides commands to monitor server logs in real-time, filter for specific events like WebSocket activity, or search for errors. ```bash # Watch logs tail -f logs/stepsales.log ``` ```bash # Filter for WebSocket events grep "WebSocket" logs/stepsales.log ``` ```bash # Filter for errors grep "ERROR" logs/stepsales.log ``` -------------------------------- ### qualify_lead Tool Source: https://context7.com/dsactivi-2/stepsales/llms.txt Qualifies and saves a prospect with contact information, job interests, budget, and timeline. Automatically calculates a qualification score from 0-100 based on completeness and engagement signals. ```APIDOC ## qualify_lead Tool Qualifies and saves a prospect with contact information, job interests, budget, and timeline. Automatically calculates a qualification score from 0-100 based on completeness and engagement signals. ### Usage ```python from telesales_agent import TelesalesAgent agent = TelesalesAgent() # Qualify a lead with full information result = agent.handle_tool_call("qualify_lead", { "company_name": "TechCorp GmbH", "contact_name": "Max Müller", "contact_email": "max@techcorp.de", "contact_phone": "+49301234567", "job_interests": ["Senior Developer", "DevOps Engineer"], "budget_range": "70000-90000 EUR", "timeline": "In 2 Wochen" }) print(result) # Output: # { # "success": True, # "lead_id": "LEAD-00001", # "company": "TechCorp GmbH", # "score": 100, # "message": "Lead TechCorp GmbH gespeichert" # } # Check the agent's stored qualification score print(agent.current_qualification_score) # 100 ``` ### Parameters #### Request Body - **company_name** (string) - Required - The name of the company. - **contact_name** (string) - Required - The name of the contact person. - **contact_email** (string) - Required - The email address of the contact person. - **contact_phone** (string) - Optional - The phone number of the contact person. - **job_interests** (array[string]) - Required - A list of job titles the prospect is interested in. - **budget_range** (string) - Required - The budget range for the position. - **timeline** (string) - Required - The timeframe for filling the position. ### Scoring Logic - Company name: +10 points - Contact name: +10 points - Contact email: +10 points - Job interests provided: +20 points - Budget range provided: +20 points - Timeline with "Woche" or "Monat": +30 points ``` -------------------------------- ### Identify Port Conflicts Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md List processes currently using port 8010. This command helps diagnose port conflict errors during service startup. ```bash lsof -i :8010 ``` -------------------------------- ### Run Pytest Test Suite Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Execute the project's test suite using Pytest. This command loads environment variables and runs tests quietly. ```bash set -a && source environment/.env && set +a && .venv/bin/pytest -q ``` -------------------------------- ### Run All Tests Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Executes all tests in the project using pytest. Use the -v flag for verbose output. ```bash # Run all tests pytest tests/ -v ``` -------------------------------- ### Contribute to the Repository Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Steps for contributing code changes to the StepSales agent repository, including forking, branching, committing, and creating pull requests. ```bash # Fork the repository # Create a feature branch: git checkout -b feature/improvement # Commit changes: git commit -am 'Add improvement' # Push to branch: git push origin feature/improvement # Open a Pull Request ``` -------------------------------- ### Programmatic API Access with FastAPI TestClient Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Shows how to use FastAPI's TestClient to programmatically access and test the StepSales API endpoints, including health checks and retrieving call transcripts. ```python from fastapi.testclient import TestClient from web_server import app client = TestClient(app) # Health check response = client.get("/health") print(response.json()) ``` ```python # Get call transcript response = client.get("/api/calls/session-123/transcript") print(response.json()) ``` -------------------------------- ### Async Job Search and Details Retrieval Source: https://context7.com/dsactivi-2/stepsales/llms.txt Performs an asynchronous search for job postings and retrieves detailed information for a specific job URL. Requires the 'integration' object to be available. ```python async def search_jobs(): jobs = await integration.search_jobs(["Software Engineer", "DevOps"]) for job in jobs: print(integration.format_job_for_sales(job)) # Output: # 📌 Senior Software Engineer # 🏢 TechCorp GmbH # 📍 Berlin # 💰 60.000-80.000 EUR # 🔗 https://www.stepstone.de/... asyncio.run(search_jobs()) ``` ```python # Get cached results from last search cached_jobs = integration.get_cached_jobs() ``` ```python # Get detailed job information details = await integration.get_job_details("https://www.stepstone.de/job/123") # Returns: {"description": "...", "requirements": [...], "benefits": [...]} ``` -------------------------------- ### Application Configuration and Validation Source: https://context7.com/dsactivi-2/stepsales/llms.txt Accesses and validates application configuration settings using AppConfig. Ensure environment variables are set correctly for runtime, OpenAI, Deepgram, and ElevenLabs. ```python from config.settings import AppConfig # Access configuration values print(AppConfig.runtime.host) # "0.0.0.0" print(AppConfig.runtime.port) # 8010 print(AppConfig.openai.model) # "gpt-4o" print(AppConfig.deepgram.model) # "nova-3" print(AppConfig.elevenlabs.model_id) # "eleven_multilingual_v2" # Validate all required environment variables errors = AppConfig.validate() if errors: print("Missing configuration:") for error in errors: print(f" - {error}") # Output if missing: # - TELNYX_API_KEY not set # - DEEPGRAM_API_KEY not set ``` -------------------------------- ### Convert Lead to Dictionary and Save to CRM Source: https://context7.com/dsactivi-2/stepsales/llms.txt Convert a Lead object to a dictionary format for storage and then save it to the CRM using the crm.save_lead function. The result includes success status and lead ID. ```python # Convert to dictionary for storage lead_dict = lead.to_dict() # { # "company_name": "TechCorp GmbH", # "contact_name": "Max Müller", # "contact_email": "max@techcorp.de", # "qualification_score": 100, # "created_at": "2026-04-22T14:30:00", # ... # } # Save to CRM result = crm.save_lead(lead) # {"success": True, "lead_id": "LEAD-00001", "score": 100} ``` -------------------------------- ### View Docker Container Logs Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Retrieve the last 200 lines of logs for the 'stepsales-agent' Docker container. This helps in debugging runtime failures. ```bash docker compose logs --tail=200 stepsales-agent ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Executes all tests and generates an HTML report for code coverage. This helps identify areas of the code that are not being tested. ```bash # With coverage pytest tests/ --cov=. --cov-report=html ``` -------------------------------- ### Load Environment Variables for Local Commands Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Source environment variables from a file for local execution without displaying sensitive values. Use `set -a` to export variables and `set +a` to disable export mode. ```bash set -a && source environment/.env && set +a ``` -------------------------------- ### Run Web Server Tests Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Executes only the tests related to the web server component using pytest. Use the -v flag for verbose output. ```bash # Run only web server tests pytest tests/test_web_server.py -v ``` -------------------------------- ### Search Jobs Tool Source: https://context7.com/dsactivi-2/stepsales/llms.txt Uses the search_jobs tool to find job listings on Stepstone.de. Can search with or without specifying a region. ```python from telesales_agent import TelesalesAgent agent = TelesalesAgent() # Search for jobs with specific terms and region result = agent.handle_tool_call("search_jobs", { "search_terms": ["Software Engineer", "DevOps Engineer"], "region": "Berlin" }) print(result) # Output: # { # "success": True, # "jobs_found": 2, # "jobs": [ # { # "title": "Software Engineer Position", # "company": "Beispielunternehmen GmbH", # "location": "Berlin", # "salary": "60.000 - 80.000 EUR", # "url": "https://www.stepstone.de/example" # } # ] # } # Search without region (uses default Frankfurt) result = agent.handle_tool_call("search_jobs", { "search_terms": ["Product Manager"] }) ``` -------------------------------- ### Troubleshoot Port Already in Use Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Resolve 'Address already in use' errors on port 8010. Involves modifying Docker configuration or terminating the conflicting process. ```bash # Change port in docker-compose.yml # Or kill existing process lsof -i :8010 kill -9 ``` -------------------------------- ### Lead Data Model Source: https://context7.com/dsactivi-2/stepsales/llms.txt Represents a qualified prospect with automatic scoring calculation and CRM integration. ```APIDOC ## Lead Data Model ### Description The Lead dataclass stores qualified prospect information with automatic scoring calculation. ### Fields - **company_name** (string) - The name of the company. - **contact_name** (string) - The name of the contact person. - **contact_email** (string) - The email address of the contact. - **contact_phone** (string) - The phone number of the contact. - **job_interests** (array of strings) - A list of job titles the contact is interested in. - **budget_range** (string) - The budget range for the potential deal. - **timeline** (string) - The expected timeline for the deal. - **call_id** (string) - The ID of the associated call. ### Methods - **calculate_score()**: Calculates the qualification score for the lead. - **to_dict()**: Converts the Lead object into a dictionary format. ### CRM Integration - **crm.save_lead(lead)**: Saves a Lead object to the CRM. - **Input**: `lead` (Lead object) - **Output**: `{ ``` -------------------------------- ### Run Individual Tests with Pytest Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Execute specific tests for the agent using Pytest. Useful for targeted debugging and verification. ```bash # Test agent initialization pytest tests/test_agent.py::TestTelesalesAgent::test_agent_initialization -v ``` ```bash # Test tool calls pytest tests/test_agent.py::TestTelesalesAgent::test_search_jobs_tool -v ``` ```bash # Test lead qualification pytest tests/test_agent.py::TestLead -v ``` -------------------------------- ### Connect to WebSocket for Voice Call Source: https://context7.com/dsactivi-2/stepsales/llms.txt Establish a WebSocket connection to the /ws/call/{session_id} endpoint for real-time voice communication. Handle incoming agent messages and call end events. ```javascript const ws = new WebSocket('ws://localhost:8010/ws/call/session123'); ws.onopen = () => { console.log('Connected to call session'); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'agent_message') { console.log('Agent:', data.text); // Initial greeting: "Guten Tag, hier ist Alex von Stepsales..." } if (data.type === 'call_ended') { console.log('Call summary:', data.summary); } }; ``` -------------------------------- ### Filter Logs for Tool Calls Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Extract log entries related to tool calls using `grep`. Useful for understanding agent's interaction with external tools. ```bash # Filter for tool calls grep "Tool called" logs/stepsales.log ``` -------------------------------- ### Filter Logs for Errors Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Search agent logs for specific error messages using `grep`. Helps in quickly identifying and diagnosing problems. ```bash # Filter for errors grep "ERROR" logs/stepsales.log ``` -------------------------------- ### Retrieve Qualified Leads from CRM Source: https://context7.com/dsactivi-2/stepsales/llms.txt Fetch leads from the CRM that meet a minimum qualification score using the crm.get_leads function with the filter_score_min parameter. ```python # Retrieve leads with minimum score qualified_leads = crm.get_leads(filter_score_min=50) ``` -------------------------------- ### Stop Docker Compose Services Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Stop and remove all containers, networks, and volumes defined in the Docker Compose file. ```bash docker compose down ``` -------------------------------- ### search_jobs Tool Source: https://context7.com/dsactivi-2/stepsales/llms.txt Searches for job listings on Stepstone.de based on search terms and optional region. Returns matching positions with company, location, and salary information. ```APIDOC ## search_jobs Tool Searches for job listings on Stepstone.de based on search terms and optional region. Returns matching positions with company, location, and salary information. ### Usage ```python from telesales_agent import TelesalesAgent agent = TelesalesAgent() # Search for jobs with specific terms and region result = agent.handle_tool_call("search_jobs", { "search_terms": ["Software Engineer", "DevOps Engineer"], "region": "Berlin" }) print(result) # Output: # { # "success": True, # "jobs_found": 2, # "jobs": [ # { # "title": "Software Engineer Position", # "company": "Beispielunternehmen GmbH", # "location": "Berlin", # "salary": "60.000 - 80.000 EUR", # "url": "https://www.stepstone.de/example" # } # ] # } # Search without region (uses default Frankfurt) result = agent.handle_tool_call("search_jobs", { "search_terms": ["Product Manager"] }) ``` ### Parameters #### Request Body - **search_terms** (array[string]) - Required - The terms to search for in job listings. - **region** (string) - Optional - The geographical region to search within. ``` -------------------------------- ### Web Server REST API Source: https://context7.com/dsactivi-2/stepsales/llms.txt FastAPI-based web server providing health checks, call management, and transcript retrieval endpoints. ```APIDOC ## GET /health ### Description Provides a health check status for the web server. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - The health status of the service (e.g., 'healthy'). - **service** (string) - The name of the service. - **active_calls** (integer) - The number of currently active calls. - **timestamp** (string) - The timestamp of the health check. ### Response Example ```json { "status": "healthy", "service": "stepsales-web-call", "active_calls": 0, "timestamp": "2026-04-22T14:30:00" } ``` ## POST /api/calls/{session_id}/end ### Description Ends an active call associated with a specific session. ### Method POST ### Endpoint /api/calls/{session_id}/end ### Parameters #### Path Parameters - **session_id** (string) - Required - The ID of the call session to end. ### Response #### Success Response (200) - **status** (string) - The status of the call after ending (e.g., 'ended'). - **summary** (object) - An object containing call summary details. - **call_id** (string) - The unique identifier for the call. - **session_id** (string) - The session ID of the call. - **duration_seconds** (integer) - The total duration of the call in seconds. - **transcript_lines** (integer) - The number of lines in the call transcript. ### Response Example ```json { "status": "ended", "summary": { "call_id": "abc12345", "session_id": "session123", "duration_seconds": 245, "transcript_lines": 12 } } ``` ## GET /api/calls/{session_id}/transcript ### Description Retrieves the transcript and summary for a specific call session. ### Method GET ### Endpoint /api/calls/{session_id}/transcript ### Parameters #### Path Parameters - **session_id** (string) - Required - The ID of the call session to retrieve the transcript for. ### Response #### Success Response (200) - **session_id** (string) - The session ID of the call. - **transcript** (array of objects) - An array of transcript lines. - **timestamp** (string) - The timestamp of the transcript line. - **speaker** (string) - The speaker of the line (e.g., 'Agent', 'User'). - **text** (string) - The content of the transcript line. - **summary** (object) - An object containing call summary details (structure may vary). ### Response Example ```json { "session_id": "session123", "transcript": [ {"timestamp": "2026-04-22T14:30:00", "speaker": "Agent", "text": "Guten Tag..."}, {"timestamp": "2026-04-22T14:30:15", "speaker": "User", "text": "Hallo..."} ], "summary": {} } ``` ``` -------------------------------- ### Update Audio Level Visualization Source: https://github.com/dsactivi-2/stepsales/blob/master/static/index.html Updates the microphone input level indicator and text display based on the average audio data. Requires an `update` function to be called recursively via `requestAnimationFrame` and a `isConnected` flag. ```javascript const percentage = Math.min(100, (average / 255) * 150); document.getElementById('micIndicator').style.width = percentage + '%'; document.getElementById('micLevel').textContent = Math.round(percentage) + '%'; if (isConnected) { requestAnimationFrame(update); } ``` -------------------------------- ### Inspect Docker Container Status Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Check the running status of Docker containers managed by Docker Compose. This is useful for diagnosing startup issues. ```bash docker compose ps ``` -------------------------------- ### WebSocket User Audio Message Format Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Format for sending user audio data to the server via WebSocket. Includes base64 encoded audio and an optional transcribed text. ```json { "type": "user_audio", "audio": "base64_encoded_audio", "transcript": "Transcribed text (optional)" } ``` -------------------------------- ### Check Service Health Endpoint Source: https://github.com/dsactivi-2/stepsales/blob/master/RUNBOOK.md Verify the health status of the running service by sending a request to the health endpoint. Expect a JSON response with a 'status' field set to 'healthy'. ```bash curl -fsS http://localhost:8010/health ``` -------------------------------- ### Send User Audio and Transcript via WebSocket Source: https://context7.com/dsactivi-2/stepsales/llms.txt Send user audio data (Base64 encoded) along with a text transcript to the WebSocket server. This is used for real-time interaction during a voice call. ```javascript ws.send(JSON.stringify({ type: 'user_audio', audio: btoa(audioData), // Base64 encoded audio transcript: 'Wir suchen einen Software Entwickler' })); ``` -------------------------------- ### WebSocket API Reference Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Defines the message types for real-time communication over the WebSocket connection. ```APIDOC ## WebSocket: `/ws/call/{session_id}` ### Description This endpoint facilitates real-time, bi-directional communication for live voice calls. ### Message Types #### 1. User Audio Sent from the client to the server to transmit audio data. ```json { "type": "user_audio", "audio": "base64_encoded_audio", "transcript": "Transcribed text (optional)" } ``` #### 2. Agent Message (Server Response) Sent from the server to the client, containing the agent's response. ```json { "type": "agent_message", "text": "Response from Alex" } ``` #### 3. End Call Sent to signal the termination of the call. ```json { "type": "end_call" } ``` ``` -------------------------------- ### WebSocket Agent Message Format Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Format for receiving agent responses from the server via WebSocket. Contains the text of the agent's message. ```json { "type": "agent_message", "text": "Response from Alex" } ``` -------------------------------- ### Check Agent Health Source: https://github.com/dsactivi-2/stepsales/blob/master/README.md Perform a health check on the running StepSales agent using curl. Verifies if the agent is operational and accessible. ```bash # Check if agent is running curl http://localhost:8010/health ``` -------------------------------- ### Update Call Duration Timer Source: https://github.com/dsactivi-2/stepsales/blob/master/static/index.html Calculates and formats the elapsed call time into minutes and seconds, updating the display every second. It relies on a `callStartTime` variable. ```javascript if (!callStartTime) return; const elapsed = Math.floor((Date.now() - callStartTime) / 1000); const minutes = Math.floor(elapsed / 60); const seconds = elapsed % 60; document.getElementById('duration').textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`; ``` -------------------------------- ### End Call HTTP Endpoint Source: https://github.com/dsactivi-2/stepsales/blob/master/WEB_CALL_README.md Initiate the end of a call for a specific session ID using this cURL command with a POST request. ```bash curl -X POST http://localhost:8010/api/calls/abc123/end ```