### Install Backend Dependencies (Ruby and Python) Source: https://github.com/syxanash/maxheadbox/blob/main/README.md Installs backend dependencies for Max Headbox, including Ruby gems and Python packages. This involves navigating to the backend directory and running bundle install and pip install. ```shell cd backend/ bundle install pip3 install -r requirements.txt ``` -------------------------------- ### Start Max Headbox (Production) Source: https://github.com/syxanash/maxheadbox/blob/main/README.md Starts the Max Headbox agent in production mode from the root of the project directory. This command initiates the application for live use. ```shell npm run start-prod ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/syxanash/maxheadbox/blob/main/README.md Installs the necessary Node.js dependencies for the Max Headbox project using npm. Requires Node Version Manager (nvm) to be set up. ```shell nvm use npm install ``` -------------------------------- ### Start Max Headbox (Development) Source: https://github.com/syxanash/maxheadbox/blob/main/README.md Starts the Max Headbox agent in development mode from the root of the project directory. This command is used for debugging and active development. ```shell npm run start-dev ``` -------------------------------- ### Get System Information (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Returns system information from the Raspberry Pi, including CPU temperature, uptime, and current date/time. An error is returned if system information retrieval fails, for example, if 'vcgencmd' is not found. ```bash curl http://192.168.0.1:4567/sysinfo # Response { "date_time": "2025-10-14 15:30:45", "cpu_temperature": "52.1", "uptime": "15:30:45 up 2 days, 4:32, 1 user, load average: 0.23, 0.31, 0.28" } # Error response { "error": "Failed to get system info: vcgencmd not found" } ``` -------------------------------- ### Run Application in Development Mode Source: https://context7.com/syxanash/maxheadbox/llms.txt This bash command starts the application in development mode with hot reloading enabled. It specifies the commands to run the frontend dev server, the transcription service (uvicorn), and the API server (ruby Sinatra). ```bash npm run start-dev # This runs: # - vite --host (frontend dev server) # - uvicorn backend.whisper_service:app --host 0.0.0.0 --port 8000 (transcription) # - ruby backend/server.rb -o 0.0.0.0 (API server) ``` -------------------------------- ### GET /sysinfo Source: https://context7.com/syxanash/maxheadbox/llms.txt Returns system information including CPU temperature, uptime, and current date/time from the Raspberry Pi. ```APIDOC ## GET /sysinfo ### Description Returns system information including CPU temperature, uptime, and current date/time from the Raspberry Pi. ### Method GET ### Endpoint /sysinfo ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://192.168.0.1:4567/sysinfo ``` ### Response #### Success Response (200) - **date_time** (string) - Current date and time. - **cpu_temperature** (string) - Current CPU temperature. - **uptime** (string) - System uptime information. #### Response Example ```json { "date_time": "2025-10-14 15:30:45", "cpu_temperature": "52.1", "uptime": "15:30:45 up 2 days, 4:32, 1 user, load average: 0.23, 0.31, 0.28" } ``` #### Error Response - **error** (string) - Error message if system info retrieval fails. #### Error Response Example ```json { "error": "Failed to get system info: vcgencmd not found" } ``` ``` -------------------------------- ### Create Frontend Tools for Note Management (Save and Get) Source: https://context7.com/syxanash/maxheadbox/llms.txt Defines multiple related frontend tools within a single module for note management. This module exports an array of tool objects, each with a name, parameters, description, and an asynchronous execution function. It includes functions for saving note content via a POST request and retrieving all saved notes via a GET request to the backend. ```javascript // src/tools/notes.js import config from '../config.js'; const saveNoteExecution = async (parameter) => { const formData = new URLSearchParams(); formData.append('note', parameter); const noteResponse = await fetch(`${config.BACKEND_URL}/save-note`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: formData.toString() }); if (!noteResponse.ok) { throw new Error(`HTTP error! status: ${noteResponse.status}`); } const responseData = await noteResponse.json(); return responseData.message; }; const getNotesExecution = async () => { const notesResponse = await fetch(`${config.BACKEND_URL}/notes`, { method: "GET" }); if (!notesResponse.ok) { throw new Error(`HTTP error! status: ${notesResponse.status}`); } const responseData = await notesResponse.json(); return `Notes: "${responseData.text}" `; }; export default [ { name: 'save_note', params: 'noteText', description: 'save notes content on file.', execution: saveNoteExecution }, { name: 'get_notes', params: undefined, description: 'get all notes previously saved on file.', execution: getNotesExecution }, ]; ``` -------------------------------- ### GET /wiki/:topic Source: https://context7.com/syxanash/maxheadbox/llms.txt Retrieves a Wikipedia summary for a given topic via a backend proxy. ```APIDOC ## GET /wiki/:topic ### Description Retrieves a Wikipedia summary for a given topic via a backend proxy. ### Method GET ### Endpoint /wiki/:topic ### Parameters #### Path Parameters - **topic** (string) - Required - The topic for which to retrieve the Wikipedia summary. #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://192.168.0.1:4567/wiki/raspberry-pi ``` ### Response #### Success Response (200) - **summary** (string) - The Wikipedia summary for the specified topic. #### Response Example ```json { "summary": "Raspberry Pi is a series of small single-board computers..." } ``` ``` -------------------------------- ### Start Audio Recording (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Initiates audio recording with automatic silence detection. Records voice input to a WAV file and triggers transcription upon detecting silence. The API returns a success message and the path to the saved recording. ```bash curl -X POST http://192.168.0.1:4567/start_recording # Response { "message": "Recording started.", "filename": "recording.wav", "filepath": "/dev/shm/whisper_recordings/recording.wav" } # After silence detected, WebSocket event is sent: { "event": "recording_finished", "message": "Recording stopped.", "output": "what is the weather in paris" } ``` -------------------------------- ### Get Weather Information (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Fetches current weather data for a specified city using the Open-Meteo API. The response includes details like temperature, description, and wind speed. An error response is provided if the city is not found. ```bash curl http://192.168.0.1:4567/weather/paris # Response { "weather": "City: Paris\nTemperature: 18.5°C\nFeels Like: 17.2°C\nDescription: Partly cloudy\nWind Speed: 15 km/h\nHumidity: 65%\nIs Day: Yes" } # Error response { "error": "City 'xyz' not found." } ``` -------------------------------- ### GET /notes Source: https://context7.com/syxanash/maxheadbox/llms.txt Retrieves all saved notes from the notes file. ```APIDOC ## GET /notes ### Description Retrieves all saved notes from the notes file. ### Method GET ### Endpoint /notes ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://192.168.0.1:4567/notes ``` ### Response #### Success Response (200) - **text** (string) - The content of the notes file. #### Response Example (with notes) ```json { "text": "Remember to water the plants\nBuy groceries tomorrow\n" } ``` #### Response Example (when empty) ```json { "text": "No notes found." } ``` ``` -------------------------------- ### Get System Info via Ruby Route Source: https://context7.com/syxanash/maxheadbox/llms.txt This Ruby route uses Open3 to execute system commands on a Raspberry Pi, capturing CPU temperature and system uptime. It returns the data in JSON format. Errors during execution are caught and returned as a JSON error message. ```ruby # backend/notions/sysinfo.rb get '/sysinfo' do date_time = Time.now.strftime('%Y-%m-%d %H:%M:%S') cpu_temp_out, status = Open3.capture2('vcgencmd measure_temp') cpu_temperature = status.success? ? cpu_temp_out.match(/[0-9.]+/)[0] : 'N/A' uptime_out, status = Open3.capture2('uptime') uptime = status.success? ? uptime_out.strip : 'N/A' return { date_time: date_time, cpu_temperature: cpu_temperature, uptime: uptime }.to_json rescue StandardError => e return { error: "Failed to get system info: #{e.message}" }.to_json end ``` -------------------------------- ### GET /weather/:city Source: https://context7.com/syxanash/maxheadbox/llms.txt Fetches current weather data for a specified city using the Open-Meteo API. ```APIDOC ## GET /weather/:city ### Description Fetches current weather data for a specified city using the Open-Meteo API. ### Method GET ### Endpoint /weather/:city ### Parameters #### Path Parameters - **city** (string) - Required - The name of the city for which to fetch weather data. #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://192.168.0.1:4567/weather/paris ``` ### Response #### Success Response (200) - **weather** (string) - A formatted string containing weather details (City, Temperature, Feels Like, Description, Wind Speed, Humidity, Is Day). #### Response Example ```json { "weather": "City: Paris\nTemperature: 18.5°C\nFeels Like: 17.2°C\nDescription: Partly cloudy\nWind Speed: 15 km/h\nHumidity: 65%\nIs Day: Yes" } ``` #### Error Response - **error** (string) - Error message if the city is not found. #### Error Response Example ```json { "error": "City 'xyz' not found." } ``` ``` -------------------------------- ### Get Wikipedia Summary (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Retrieves a summary of a given topic from Wikipedia. This is achieved by the backend proxying requests to Wikipedia. The response contains a JSON object with the summary text. ```bash curl http://192.168.0.1:4567/wiki/raspberry-pi # Response { "summary": "Raspberry Pi is a series of small single-board computers..." } ``` -------------------------------- ### GET /is_recording Source: https://context7.com/syxanash/maxheadbox/llms.txt Checks the current recording status and returns the active file path if recording. ```APIDOC ## GET /is_recording ### Description Checks the current recording status and returns the active file path if recording. ### Method GET ### Endpoint /is_recording ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://192.168.0.1:4567/is_recording ``` ### Response #### Success Response (200) - **message** (string) - Status of the recording ('recording' or 'idle'). - **current_file** (string) - The path of the currently recording file (only present if status is 'recording'). #### Response Example (when recording) ```json { "message": "recording", "current_file": "/dev/shm/whisper_recordings/recording.wav" } ``` #### Response Example (when idle) ```json { "message": "idle" } ``` ``` -------------------------------- ### Transcribe Audio File (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Transcribes audio files using the faster-whisper model. This endpoint is typically called internally by the backend. It requires the file path as input and returns the transcribed text with start and end times. Error handling for file not found is included. ```bash curl -X POST http://localhost:8000/transcribe \ -H "Content-Type: application/json" \ -d '{"file_path": "/dev/shm/whisper_recordings/recording.wav"}' # Response [ { "start": 0.0, "end": 2.5, "text": "what is the weather in paris" } ] # Error response { "error": "File not found at path: /path/to/file.wav" } ``` -------------------------------- ### Clone Max Headbox Repository Source: https://github.com/syxanash/maxheadbox/blob/main/README.md Clones the Max Headbox repository from GitHub and navigates into the project directory. This is the first step in setting up the project. ```shell git clone https://github.com/syxanash/maxheadbox.git cd maxheadbox ``` -------------------------------- ### Run Application in Production Mode Source: https://context7.com/syxanash/maxheadbox/llms.txt This bash command builds and serves the optimized production bundle of the application. It includes commands for building the frontend, serving the production build, running the transcription service, and the API server. ```bash npm run start-prod # This runs: # - vite build (build frontend) # - vite preview (serve production build) # - uvicorn backend.whisper_service:app --host 0.0.0.0 --port 8000 # - ruby backend/server.rb -o 0.0.0.0 ``` -------------------------------- ### Download Ollama Models Source: https://context7.com/syxanash/maxheadbox/llms.txt This command-line snippet shows how to pull specific models from Ollama, including 'gemma3:1b' for conversation and 'qwen3:1.7b' for agent/tool calling. ```bash ollama pull gemma3:1b # Conversation model ollama pull qwen3:1.7b # Agent/tool calling model ``` -------------------------------- ### Frontend Configuration (JavaScript) Source: https://context7.com/syxanash/maxheadbox/llms.txt This JavaScript configuration file reads environment variables (prefixed with VITE_) to set up the backend, WebSocket, and Ollama URLs for the frontend. It also includes a fullscreen setting. ```javascript // src/config.js export default { BACKEND_URL: import.meta.env.VITE_BACKEND_URL, WEBSOCKET_URL: import.meta.env.VITE_WEBSOCKET_URL, OLLAMA_URL: import.meta.env.VITE_OLLAMA_URL, FULLSCREEN: true }; ``` -------------------------------- ### Run Individual Services Source: https://context7.com/syxanash/maxheadbox/llms.txt This section provides bash commands to run individual services of the application separately, useful for debugging or custom configurations. It includes commands for the frontend, backend API, whisper service, and the wake word listener. ```bash # Frontend only npm run dev # Backend only npm run start-backend # Whisper service only npm run start-whisper-service # Wake word listener (spawned automatically by app) python3 backend/awaker.py ``` -------------------------------- ### Create a New Tool in JavaScript Source: https://github.com/syxanash/maxheadbox/blob/main/README.md Defines the structure for creating a new tool in JavaScript for Max Headbox. Tools require a name, parameters, description, and an execution function. Frontend tools may need backend API handlers. ```javascript // Example structure for a tool export default { name: "tool_name", parameters: { /* parameters */ }, describe: "A brief description of the tool.", execute: async (params) => { // Execution logic } } ``` -------------------------------- ### Configure Environment Variables (.env) Source: https://github.com/syxanash/maxheadbox/blob/main/README.md Sets up essential environment variables in the .env file for Max Headbox, including backend URL, WebSocket URL, and Ollama URL. Allows customization for different network configurations and recording directories. ```env VITE_BACKEND_URL=http://192.168.0.1:4567 VITE_WEBSOCKET_URL=ws://192.168.0.1:4567 VITE_OLLAMA_URL=http://192.168.0.1:11434 RECORDINGS_DIR="~/Desktop/whisper_recordings" ``` -------------------------------- ### Frontend Environment Configuration (.env) Source: https://context7.com/syxanash/maxheadbox/llms.txt This .env file configures the backend, WebSocket, and Ollama URLs for the frontend application. It also specifies the directory for recordings. ```bash # .env VITE_BACKEND_URL=http://192.168.0.1:4567 VITE_WEBSOCKET_URL=ws://192.168.0.1:4567 VITE_OLLAMA_URL=http://192.168.0.1:11434 RECORDINGS_DIR=/dev/shm/whisper_recordings ``` -------------------------------- ### Create a Single Frontend Tool for Weather Information Source: https://context7.com/syxanash/maxheadbox/llms.txt Defines a single frontend tool module for fetching weather data. This tool exports an object containing its name, parameters, description, and an asynchronous execution function. The execution function takes a city name as input, fetches weather data from a backend API, and returns a formatted string with the weather information. ```javascript // src/tools/weather.js import config from '../config.js'; const name = 'get_weather'; const params = 'city'; const description = 'return the weather for a certain city.'; const execution = async (parameter) => { const city = parameter; const backendResponse = await fetch(`${config.BACKEND_URL}/weather/${city}`, { method: "GET" }); if (!backendResponse.ok) { throw new Error(`HTTP error! status: ${backendResponse.status}`); } const weatherData = await backendResponse.json(); const weather = weatherData.weather; return `Here is the weather data: ${weather}`; }; export default { name, params, description, execution }; ``` -------------------------------- ### Implement a Dynamic Tool Processor for Executing Frontend Tools Source: https://context7.com/syxanash/maxheadbox/llms.txt Provides functionality to dynamically load and process frontend tools. The `getToolsList` function uses `import.meta.glob` to discover tool modules and aggregates them into a map. The `processTool` function takes a tool object, finds the corresponding tool in the map, and executes its associated function with the provided parameter, returning the result. ```javascript // src/toolProcessor.js const toolModules = import.meta.glob('./tools/*.js', { eager: true }); export const getToolsList = () => { const toolsList = Object.values(toolModules).reduce((acc, module) => { if (Array.isArray(module.default)) { module.default.forEach(tool => { if (tool.name && tool.execution) { acc[tool.name] = { name: tool.name, execution: tool.execution, params: tool.params, description: tool.description, }; } }); } else if (module.default?.name && module.default?.execution) { acc[module.default.name] = module.default; } return acc; }, {}); return toolsList; }; export const processTool = async (tool) => { const parameter = tool.parameter || ''; const functionName = tool.function || ''; const toolsMap = getToolsList(); const matchingTool = toolsMap[functionName]; if (matchingTool) { const toolFunction = matchingTool.execution; const result = await toolFunction(parameter); return result; } return undefined; }; ``` -------------------------------- ### POST /spawn-listener Source: https://context7.com/syxanash/maxheadbox/llms.txt Spawns the wake word detection process that listens for the 'max' activation phrase. ```APIDOC ## POST /spawn-listener ### Description Spawns the wake word detection process that listens for the "max" activation phrase. ### Method POST ### Endpoint /spawn-listener ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X POST http://192.168.0.1:4567/spawn-listener ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "listener spawned" } ``` ``` -------------------------------- ### Configure Ollama Service to Expose Network Source: https://github.com/syxanash/maxheadbox/blob/main/README.md Configures the Ollama service to be accessible over the network by setting the OLLAMA_HOST environment variable to 0.0.0.0. This involves editing the systemd service file and restarting the service. ```shell sudo systemctl edit ollama.service [Service] Environment="OLLAMA_HOST=0.0.0.0" sudo systemctl daemon-reload && sudo systemctl restart ollama ``` -------------------------------- ### POST /start_recording Source: https://context7.com/syxanash/maxheadbox/llms.txt Initiates audio recording with automatic silence detection. Records voice input to a WAV file and automatically triggers transcription when silence is detected. ```APIDOC ## POST /start_recording ### Description Initiates audio recording with automatic silence detection. Records voice input to a WAV file and automatically triggers transcription when silence is detected. ### Method POST ### Endpoint /start_recording ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X POST http://192.168.0.1:4567/start_recording ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. - **filename** (string) - The name of the recording file. - **filepath** (string) - The full path to the recording file. #### Response Example ```json { "message": "Recording started.", "filename": "recording.wav", "filepath": "/dev/shm/whisper_recordings/recording.wav" } ``` #### WebSocket Event (after silence detected) - **event** (string) - Indicates the event type. - **message** (string) - Confirmation message. - **output** (string) - The transcribed text from the recording. #### WebSocket Event Example ```json { "event": "recording_finished", "message": "Recording stopped.", "output": "what is the weather in paris" } ``` ``` -------------------------------- ### Configure Ollama Service for Network Access Source: https://context7.com/syxanash/maxheadbox/llms.txt These bash commands demonstrate how to edit the Ollama systemd service file to expose Ollama to the network by setting OLLAMA_HOST to 0.0.0.0. It includes steps to reload the daemon and restart the service. ```bash # Edit systemd service sudo systemctl edit ollama.service # Add configuration [Service] Environment="OLLAMA_HOST=0.0.0.0" # Restart service sudo systemctl daemon-reload && sudo systemctl restart ollama ``` -------------------------------- ### Ruby Sinatra Weather Tool Backend Source: https://context7.com/syxanash/maxheadbox/llms.txt This Ruby Sinatra application provides a backend route to fetch weather data for a given city. It utilizes the Open-Meteo API for geocoding and weather forecasting. The route handles city name encoding, API requests, error handling for not found cities, and returns weather information in JSON format. ```ruby # backend/notions/weather.rb require 'sinatra' require 'net/http' require 'uri' require 'json' def fetch_json(url) uri = URI.parse(url) response = Net::HTTP.get_response(uri) unless response.is_a?(Net::HTTPSuccess) return nil end JSON.parse(response.body) rescue StandardError => e puts "Error: #{e.message}" nil end get '/weather/:city' do content_type :json city_name = URI.encode_www_form_component(params[:city]) geocoding_url = "https://geocoding-api.open-meteo.com/v1/search?name=#{city_name}" location_data = fetch_json(geocoding_url) unless location_data && location_data['results'] && !location_data['results'].empty? status 404 return { error: "City '#{params[:city]}' not found." }.to_json end latitude = location_data['results'][0]['latitude'] longitude = location_data['results'][0]['longitude'] display_city = location_data['results'][0]['name'] weather_forecast_url = "https://api.open-meteo.com/v1/forecast?latitude=#{latitude}&longitude=#{longitude}¤t=temperature_2m,weather_code,wind_speed_10m,relative_humidity_2m,apparent_temperature,is_day&temperature_unit=celsius&wind_speed_unit=kmh&timezone=auto" weather_data = fetch_json(weather_forecast_url) current_weather = weather_data['current'] temperature = current_weather['temperature_2m'] wind_speed = current_weather['wind_speed_10m'] recap_string = <<~WEATHER_STRING City: #{display_city} Temperature: #{temperature}°C Wind Speed: #{wind_speed} km/h WEATHER_STRING { weather: recap_string.strip }.to_json end ``` -------------------------------- ### Pull Ollama Language Models Source: https://github.com/syxanash/maxheadbox/blob/main/README.md Pulls specific language models (gemma3:1b and qwen3:1.7b) using Ollama. This is required for the LLM Agent's functionality. ```shell ollama pull gemma3:1b ollama pull qwen3:1.7b ``` -------------------------------- ### Spawn Wake Word Listener (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Spawns the wake word detection process. This process actively listens for the activation phrase 'max'. A success message is returned upon spawning. ```bash curl -X POST http://192.168.0.1:4567/spawn-listener # Response { "message": "listener spawned" } ``` -------------------------------- ### POST /save-note Source: https://context7.com/syxanash/maxheadbox/llms.txt Appends a note to the notes file on the Raspberry Pi filesystem. ```APIDOC ## POST /save-note ### Description Appends a note to the notes file on the Raspberry Pi filesystem. ### Method POST ### Endpoint /save-note ### Parameters #### Query Parameters None #### Request Body - **note** (string) - Required - The note content to append. ### Request Example ```bash curl -X POST http://192.168.0.1:4567/save-note \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "note=Remember to water the plants" ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "successfully saved the note!" } ``` ``` -------------------------------- ### Execute Shell Command via Backend API (JavaScript) Source: https://github.com/syxanash/maxheadbox/blob/main/src/tools/shell.txt This snippet defines a JavaScript module that executes a shell command by sending it to a backend API. It expects the backend URL from a configuration object and returns the command's output. Error handling is included for the HTTP request. ```javascript // yeah I'm know this is dangerous but it was fun to try! import config from '../config.js'; const name = 'shell'; const params = 'shellCommand'; const description = 'executes a shell command in the terminal and gives back the result'; const execution = async (parameter) => { const backendResponse = await fetch(`${config.BACKEND_URL}/shell`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ command: parameter }), }); if (!backendResponse.ok) { throw new Error(`HTTP error! status: ${backendResponse.status}`); } const commandOutput = await backendResponse.json(); const outputText = commandOutput.message; return `Output for "${parameter}": "${outputText}".`; }; export default { name, params, description, execution }; ``` -------------------------------- ### JavaScript Agent Loop for Sequential Tool Calls Source: https://context7.com/syxanash/maxheadbox/llms.txt This JavaScript code defines an agent loop that breaks down complex user requests into sequential tool calls. It manages tool execution, accumulates results, and continues until a completion condition is met. It utilizes the ollama library for model interactions and includes a guard to prevent infinite loops. ```javascript // src/App.jsx const agentRequest = async (userInput) => { let toolLoopGuard = 0; let toolResult = undefined; let cumulativeResult = ''; globalAgentChatRef.current = [{ role: 'user', content: userInput }]; while (toolLoopGuard < 5) { toolLoopGuard++; const response = await ollama.chat({ model: 'qwen3:1.7b', messages: [ { role: 'user', content: SystemPrompt.agent.promptText }, ...globalAgentChatRef.current ], stream: false, keep_alive: -1, format: { type: "object", properties: { function: { type: "string" }, describe: { type: "string" }, parameter: { type: "string" } }, required: ["function", "describe", "parameter"] } }); const toolCallMessage = response.message; globalAgentChatRef.current.push(toolCallMessage); const toolContent = JSON.parse(toolCallMessage.content); const functionName = toolContent?.function; if (functionName.includes('finished')) { console.log("✅ Task finished."); break; } toolResult = await processTool(toolContent); if (toolResult !== undefined) { cumulativeResult += `Task ${toolLoopGuard} result: "${toolResult}"\n`; } globalAgentChatRef.current.push({ role: 'user', content: `Task ${toolLoopGuard} - function "${functionName}", result: "${toolResult}". If the list of tasks I've asked is finished call finished(), otherwise continue calling a new function...` }); } // Pass cumulative results to conversation model const conversationPrompt = `User asked: ${userInput}.\n${cumulativeResult}, communicate the results with the user.`; processConversation(conversationPrompt, 'user'); }; ``` -------------------------------- ### Save a Note (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Appends a note to a file on the Raspberry Pi's filesystem. The note content is sent as form-urlencoded data in the POST request. A success message is returned upon successful saving. ```bash curl -X POST http://192.168.0.1:4567/save-note \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "note=Remember to water the plants" # Response { "message": "successfully saved the note!" } ``` -------------------------------- ### Retrieve All Notes (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Retrieves all saved notes from the notes file. The response contains a 'text' field with the concatenated notes, or a 'No notes found.' message if the file is empty. ```bash curl http://192.168.0.1:4567/notes # Response with notes { "text": "Remember to water the plants\nBuy groceries tomorrow\n" } # Response when empty { "text": "No notes found." } ``` -------------------------------- ### POST /transcribe Source: https://context7.com/syxanash/maxheadbox/llms.txt Transcribes audio files using the faster-whisper model. This endpoint is typically called internally by the backend. ```APIDOC ## POST /transcribe ### Description Transcribes audio files using the faster-whisper model. This endpoint is typically called internally by the backend. ### Method POST ### Endpoint /transcribe ### Parameters #### Query Parameters None #### Request Body - **file_path** (string) - Required - The absolute path to the audio file to transcribe. ### Request Example ```bash curl -X POST http://localhost:8000/transcribe \ -H "Content-Type: application/json" \ -d '{"file_path": "/dev/shm/whisper_recordings/recording.wav"}' ``` ### Response #### Success Response (200) - **start** (number) - The start time of the transcribed segment in seconds. - **end** (number) - The end time of the transcribed segment in seconds. - **text** (string) - The transcribed text. #### Response Example ```json [ { "start": 0.0, "end": 2.5, "text": "what is the weather in paris" } ] ``` #### Error Response - **error** (string) - Error message indicating the file was not found. #### Error Response Example ```json { "error": "File not found at path: /path/to/file.wav" } ``` ``` -------------------------------- ### Establish WebSocket Connection for Real-time Notifications Source: https://context7.com/syxanash/maxheadbox/llms.txt Establishes a persistent WebSocket connection to a specified server endpoint for receiving real-time event notifications. It includes a message handler to parse incoming JSON data and log it to the console. Supported event types include wake word reception, processing of recordings, completion of recordings with transcriptions, and recording errors. ```javascript const ws = new WebSocket('ws://192.168.0.1:4567/ws'); ws.onmessage = (event) => { const message = JSON.parse(event.data); console.log(message); }; // Event types received: // { "event": "wake_word_received" } // { "event": "process_recording" } // { "event": "recording_finished", "message": "Recording stopped.", "output": "transcribed text" } // { "event": "recording_error", "error": "error message" } ``` -------------------------------- ### POST /wake Source: https://context7.com/syxanash/maxheadbox/llms.txt Triggers a wake word event and kills the listener process. Called by the wake word detection script. ```APIDOC ## POST /wake ### Description Triggers a wake word event and kills the listener process. Called by the wake word detection script. ### Method POST ### Endpoint /wake ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X POST http://192.168.0.1:4567/wake ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "wake word received" } ``` #### WebSocket Event - **event** (string) - Indicates the event type. #### WebSocket Event Example ```json { "event": "wake_word_received" } ``` ``` -------------------------------- ### POST /clear-notes Source: https://context7.com/syxanash/maxheadbox/llms.txt Deletes all content from the notes file. ```APIDOC ## POST /clear-notes ### Description Deletes all content from the notes file. ### Method POST ### Endpoint /clear-notes ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X POST http://192.168.0.1:4567/clear-notes ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating notes were cleared. #### Response Example ```json { "message": "Notes cleared successfully." } ``` ``` -------------------------------- ### Check Recording Status (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Checks the current recording status. Returns a 'recording' message along with the active file path if a recording is in progress, or an 'idle' message if no recording is active. ```bash curl http://192.168.0.1:4567/is_recording # Response when recording { "message": "recording", "current_file": "/dev/shm/whisper_recordings/recording.wav" } # Response when idle { "message": "idle" } ``` -------------------------------- ### Clear All Notes (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Deletes all content from the notes file, effectively clearing all saved notes. This is a POST request with no body required. ```bash curl -X POST http://192.168.0.1:4567/clear-notes ``` -------------------------------- ### Stop Audio Recording (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Manually stops an active recording session. This is done by sending a SIGINT signal to the recording process. An error is returned if no recording is currently in progress. ```bash curl -X POST http://192.168.0.1:4567/stop_recording # Response { "message": "Manual stop initiated." } # Error if no recording active { "error": "No recording is currently in progress." } ``` -------------------------------- ### POST /stop_recording Source: https://context7.com/syxanash/maxheadbox/llms.txt Manually stops an active recording session by sending SIGINT to the recording process. ```APIDOC ## POST /stop_recording ### Description Manually stops an active recording session by sending SIGINT to the recording process. ### Method POST ### Endpoint /stop_recording ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X POST http://192.168.0.1:4567/stop_recording ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Manual stop initiated." } ``` #### Error Response (if no recording active) - **error** (string) - Error message indicating no recording is in progress. #### Error Response Example ```json { "error": "No recording is currently in progress." } ``` ``` -------------------------------- ### Trigger Wake Word Event (Bash) Source: https://context7.com/syxanash/maxheadbox/llms.txt Triggers a wake word event and terminates the listener process. This endpoint is invoked by the wake word detection script. It returns a confirmation message and sends a WebSocket event to connected clients. ```bash curl -X POST http://192.168.0.1:4567/wake # Response { "message": "wake word received" } # Sends WebSocket event to all connected clients { "event": "wake_word_received" } ``` -------------------------------- ### JavaScript Conversation Processing with Emotional Reactions Source: https://context7.com/syxanash/maxheadbox/llms.txt This JavaScript function processes conversation inputs using a language model to generate natural language responses. It also incorporates emotional reactions, defined by an enum of feelings. The function streams the response and updates the UI accordingly, managing chat history and application status. ```javascript // src/App.jsx const processConversation = async (userInput, inputRole = 'user') => { globalMessagesRef.current.push({ role: inputRole, content: userInput }); const payload = { model: 'gemma3:1b', messages: [ { role: 'user', content: SystemPrompt.conversation.promptText }, ...globalMessagesRef.current ], stream: true, keep_alive: -1, format: { type: "object", properties: { message: { type: "string" }, feeling: { type: "string", enum: ["laugh", "happy", "interested", "sad", "confused", "excited", "bored", "surprised", "sarcastic", "proud", "vomit"] } }, required: ["message", "feeling"] } }; let aggregatedResponse = { role: "assistant", content: "" }; const response = await ollama.chat(payload); await utils.processStreamResponse( response, setBackendResponse, setReaction, () => { setAppStatus(APP_STATUS.SPEAKING); setFinishedStreaming(false); }, (chunk) => { aggregatedResponse.content += chunk; }, () => { setFinishedStreaming(true); } ); globalMessagesRef.current.push(aggregatedResponse); await spawnListener(); setAppStatus(APP_STATUS.IDLE); }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.