### Use Legacy HumeVoiceClient Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Example demonstrating how to use the legacy `HumeVoiceClient` and retrieve configuration details after installing the legacy package. ```python from hume.legacy import HumeVoiceClient, VoiceConfig client = HumeVoiceClient("") config = client.empathic_voice.configs.get_config_version( id = "id", version = 1 ) ``` -------------------------------- ### Install Legacy SDK Package Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Install the legacy package extra for continued functionality. If using EVI's microphone utilities, install the 'microphone' extra as well. Change import statements to `from hume.legacy`. ```bash pip install "hume[legacy]" ``` ```bash pip install "hume[microphone]" ``` -------------------------------- ### Start Expression Measurement Job - Hosted File Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Use this snippet to start an expression measurement job for hosted files. It requires initializing an `AsyncHumeClient`, defining file URLs, configuring models, and then starting the job. Note that `await_complete()` and `download_predictions()` have been removed and require manual implementation for polling and retrieval. ```python from hume import AsyncHumeClient from hume.expression_measurement.batch import Face, Models async def main(): # Initialize an authenticated client client = AsyncHumeClient(api_key=) # Define the URL(s) of the files you would like to analyze job_urls = ["https://hume-tutorials.s3.amazonaws.com/faces.zip"] # Create configurations for each model you would like to use (blank = default) face_config = Face() # Create a Models object models_chosen = Models(face=face_config) # Start an inference job and print the job_id job_id = await client.expression_measurement.batch.start_inference_job( urls=job_urls, models=models_chosen ) # Await the completion of the inference job await poll_for_completion(client, job_id, timeout=120) # After the job is over, access its predictions job_predictions = await client.expression_measurement.batch.get_job_predictions( id=job_id ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Hume Python SDK Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Install the Hume Python SDK using pip, poetry, or uv. This is the first step to integrating Hume APIs into your Python application. ```sh pip install hume # or poetry add hume # or uv add hume ``` -------------------------------- ### Start Expression Measurement Job - Local File Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Use this snippet to start an expression measurement job for local files. It involves opening local files in binary read mode, creating a stringified configuration object, and then starting the job using `start_inference_job_from_local_file`. Manual implementation for polling and prediction retrieval is necessary as `await_complete()` and `download_predictions()` are removed. ```python from hume import AsyncHumeClient from hume.expression_measurement.batch import Face, Models from hume.expression_measurement.batch.types import InferenceBaseRequest async def main(): # Initialize an authenticated client client = AsyncHumeClient(api_key=HUME_API_KEY) # Define the filepath(s) of the file(s) you would like to analyze local_filepaths = [open("faces.zip", mode="rb")] # Create configurations for each model you would like to use (blank = default) face_config = Face() # Create a Models object models_chosen = Models(face=face_config) # Create a stringified object containing the configuration stringified_configs = InferenceBaseRequest(models=models_chosen) # Start an inference job and print the job_id job_id = await client.expression_measurement.batch.start_inference_job_from_local_file( json=stringified_configs, file=local_filepaths) # Await the completion of the inference job await poll_for_completion(client, job_id, timeout=120) # After the job is over, access its predictions job_predictions = await client.expression_measurement.batch.get_job_predictions( id=job_id ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Start Batch Inference Job from Local File Source: https://context7.com/humeai/hume-python-sdk/llms.txt Uploads a local media file and starts a batch inference job. Allows specifying model configurations, such as enabling face expression measurement. ```python from hume import HumeClient from hume.expression_measurement.batch.types import InferenceBaseRequest, Models, Face client = HumeClient(api_key="YOUR_API_KEY") with open("video.mp4", "rb") as f: job_id = client.expression_measurement.batch.start_inference_job_from_local_file( file=[("video.mp4", f, "video/mp4")], json=InferenceBaseRequest( models=Models(face=Face()), ), ) print(f"Job ID: {job_id}") ``` -------------------------------- ### Start EVI Chat with Callbacks (Asynchronous) Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Initialize an asynchronous client, define WebSocket connection options, and connect with custom callback functions for EVI chat. Requires importing AsyncHumeClient and ChatConnectOptions. ```python from hume.client import AsyncHumeClient from hume.empathic_voice.chat.socket_client import ChatConnectOptions async def main() -> None: # Initialize the asynchronous client, authenticating with your API key client = AsyncHumeClient(api_key=) # Define options for the WebSocket connection, such as an EVI config id and a secret key for token authentication options = ChatConnectOptions(config_id=, secret_key=) # Open the WebSocket connection with the configuration options and the interface's handlers async with client.empathic_voice.chat.connect_with_callbacks( options=options, on_open=, on_message=, on_close=, on_error= ) as socket: # ... if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Legacy SDK EVI Chat Example Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Connect and stream EVI over the device's microphone and speakers using the legacy HumeVoiceClient and MicrophoneInterface. ```python from hume import HumeVoiceClient, MicrophoneInterface import asyncio async def main() -> None: # Connect and authenticate with Hume client = HumeVoiceClient() # Start streaming EVI over your device's microphone and speakers async with client.connect() as socket: await MicrophoneInterface.start(socket) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### MicrophoneInterface.start — Live Microphone Input to EVI Source: https://context7.com/humeai/hume-python-sdk/llms.txt Enables live audio streaming from a device microphone to an active EVI WebSocket session. This interface handles audio configuration, streams microphone audio to EVI, and plays back EVI's audio responses. It requires the `microphone` extra to be installed (`pip install hume[microphone]`). ```APIDOC ## MicrophoneInterface.start — Live Microphone Input to EVI `MicrophoneInterface` connects a device microphone to an active EVI WebSocket session, handling audio configuration (sample rate, channels, encoding), streaming microphone audio to EVI, and playing back EVI's audio response. Requires the `microphone` extra (`pip install hume[microphone]`). ```python import asyncio import os from hume import AsyncHumeClient, MicrophoneInterface from hume.empathic_voice.chat.audio.asyncio_utilities import Stream client = AsyncHumeClient(api_key=os.getenv("HUME_API_KEY")) async def main(): async with client.empathic_voice.chat.connect( config_id="your-config-uuid", ) as socket: # byte_stream carries EVI's audio output to the microphone interface byte_stream = Stream() async def handle_messages(): async for message in socket: if hasattr(message, "type") and message.type == "audio_output": await byte_stream.put(bytes.fromhex(message.data)) elif hasattr(message, "type") and message.type == "assistant_end": await byte_stream.aclose() break await asyncio.gather( handle_messages(), MicrophoneInterface.start( socket=socket, byte_stream=byte_stream, allow_user_interrupt=True, ), ) asyncio.run(main()) ``` ``` -------------------------------- ### expression_measurement.batch.start_inference_job_from_local_file Source: https://context7.com/humeai/hume-python-sdk/llms.txt Uploads local media files and starts a batch inference job to measure expressions. The `json` parameter allows specifying model configurations. ```APIDOC ## expression_measurement.batch.start_inference_job_from_local_file — Batch Inference from Local Files Uploads local media files and starts a batch inference job to measure expressions. The `json` parameter allows specifying model configurations. ```python from hume import HumeClient from hume.expression_measurement.batch.types import InferenceBaseRequest, Models, Face client = HumeClient(api_key="YOUR_API_KEY") with open("video.mp4", "rb") as f: job_id = client.expression_measurement.batch.start_inference_job_from_local_file( file=[("video.mp4", f, "video/mp4")], json=InferenceBaseRequest( models=Models(face=Face()), ), ) print(f"Job ID: {job_id}") ``` ``` -------------------------------- ### Start Batch Inference Job from URLs Source: https://context7.com/humeai/hume-python-sdk/llms.txt Starts an asynchronous batch inference job to measure expressions from media files specified by URLs. Notifies via email upon completion if `notify` is set to True. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") job_id = client.expression_measurement.batch.start_inference_job( urls=["https://hume-tutorials.s3.amazonaws.com/faces.zip"], notify=True, # email notification on completion ) print(f"Job started: {job_id}") ``` -------------------------------- ### Submit Expression Measurement Job with Legacy SDK Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Example of submitting a job for expression measurement using the legacy Hume SDK, including model configuration and awaiting results. ```python from hume import HumeBatchClient from hume.models.config import FaceConfig from hume.models.config import ProsodyConfig client = HumeBatchClient() urls = ["https://hume-tutorials.s3.amazonaws.com/faces.zip"] face_config = FaceConfig() prosody_config = ProsodyConfig() job = client.submit_job(urls, [face_config, prosody_config]) print(job) print("Running...") result = job.await_complete() job_predictions = client.get_job_predictions(job_id = job.id) ``` -------------------------------- ### expression_measurement.batch.start_inference_job Source: https://context7.com/humeai/hume-python-sdk/llms.txt Starts an asynchronous batch inference job to measure expressions (face, prosody, language, NER) from URLs pointing to media files. Returns a job ID string. ```APIDOC ## expression_measurement.batch.start_inference_job — Start a Batch Inference Job Starts an asynchronous batch inference job to measure expressions (face, prosody, language, NER) from URLs pointing to media files. Returns a job ID string. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") job_id = client.expression_measurement.batch.start_inference_job( urls=["https://hume-tutorials.s3.amazonaws.com/faces.zip"], notify=True, # email notification on completion ) print(f"Job started: {job_id}") ``` ``` -------------------------------- ### Live Microphone Input to EVI Source: https://context7.com/humeai/hume-python-sdk/llms.txt Integrates a device microphone with an active EVI WebSocket session using `MicrophoneInterface`. Handles audio configuration, streams microphone audio to EVI, and plays back EVI's audio response. Requires the `microphone` extra (`pip install hume[microphone]`). ```python import asyncio import os from hume import AsyncHumeClient, MicrophoneInterface from hume.empathic_voice.chat.audio.asyncio_utilities import Stream client = AsyncHumeClient(api_key=os.getenv("HUME_API_KEY")) async def main(): async with client.empathic_voice.chat.connect( config_id="your-config-uuid", ) as socket: # byte_stream carries EVI's audio output to the microphone interface byte_stream = Stream() async def handle_messages(): async for message in socket: if hasattr(message, "type") and message.type == "audio_output": await byte_stream.put(bytes.fromhex(message.data)) elif hasattr(message, "type") and message.type == "assistant_end": await byte_stream.aclose() break await asyncio.gather( handle_messages(), MicrophoneInterface.start( socket=socket, byte_stream=byte_stream, allow_user_interrupt=True, ), ) asyncio.run(main()) ``` -------------------------------- ### EVI WebSocket on_message Handler Example Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide A callback function to process various WebSocket message types from EVI, including metadata, chat messages, audio output, and errors. Handles SubscribeEvent messages. ```python async def on_message(message: SubscribeEvent): """Callback function to handle a WebSocket message event. Args: data (SubscribeEvent): This represents any type of message that is received through the EVI WebSocket, formatted in JSON. See the full list of messages in the API Reference [here](https://dev.hume.ai/reference/empathic-voice-interface-evi/chat/chat#receive). """ # Create an empty dictionary to store expression inference scores scores = {} if message.type == "chat_metadata": message_type = message.type.upper() chat_id = message.chat_id chat_group_id = message.chat_group_id text = f"<{message_type}> Chat ID: {chat_id}, Chat Group ID: {chat_group_id}" elif message.type in ["user_message", "assistant_message"]: role = message.message.role.upper() message_text = message.message.content text = f"{role}: {message_text}" if message.from_text is False: scores = dict(message.models.prosody.scores) elif message.type == "audio_output": message_str: str = message.data message_bytes = base64.b64decode(message_str.encode("utf-8")) await self.byte_strs.put(message_bytes) return elif message.type == "error": error_message: str = message.message error_code: str = message.code raise ApiError(f"Error ({error_code}): {error_message}") # ApiError is also an imported type else: message_type = message.type.upper() text = f"<{message_type}>" print(text) ``` -------------------------------- ### Initializing the SDK Source: https://context7.com/humeai/hume-python-sdk/llms.txt Demonstrates how to initialize both synchronous and asynchronous Hume clients, including options for custom timeouts, base URLs, and httpx clients. ```APIDOC ## Initializing the SDK The top-level synchronous and asynchronous clients are the entry points for all SDK interactions. Both accept an API key, optional timeout, custom base URL or environment, and a custom `httpx` client for advanced proxy/transport scenarios. ```python import asyncio import httpx from hume.client import HumeClient, AsyncHumeClient from hume import HumeClientEnvironment # --- Synchronous client (default production environment) --- client = HumeClient(api_key="YOUR_API_KEY") # --- Async client --- async_client = AsyncHumeClient(api_key="YOUR_API_KEY") # --- Custom timeout (20 seconds globally) --- client_with_timeout = HumeClient(api_key="YOUR_API_KEY", timeout=20.0) # --- Custom base URL (e.g., for a proxy or staging environment) --- staging_client = HumeClient( api_key="YOUR_API_KEY", base_url="https://staging.api.hume.ai", ) # --- Custom httpx client (proxy support) --- proxy_client = HumeClient( api_key="YOUR_API_KEY", http_client=httpx.Client( proxies="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) # Namespace access client.empathic_voice # EVI APIs client.tts # Text-to-speech APIs client.expression_measurement # Expression measurement APIs ``` ``` -------------------------------- ### Initialize HumeClient and AsyncHumeClient Source: https://context7.com/humeai/hume-python-sdk/llms.txt Initialize the synchronous and asynchronous clients with an API key. Custom configurations for timeout, base URL, and HTTP client are also demonstrated. ```python import asyncio import httpx from hume.client import HumeClient, AsyncHumeClient from hume import HumeClientEnvironment # --- Synchronous client (default production environment) --- client = HumeClient(api_key="YOUR_API_KEY") # --- Async client --- async_client = AsyncHumeClient(api_key="YOUR_API_KEY") # --- Custom timeout (20 seconds globally) --- client_with_timeout = HumeClient(api_key="YOUR_API_KEY", timeout=20.0) # --- Custom base URL (e.g., for a proxy or staging environment) --- staging_client = HumeClient( api_key="YOUR_API_KEY", base_url="https://staging.api.hume.ai", ) # --- Custom httpx client (proxy support) --- proxy_client = HumeClient( api_key="YOUR_API_KEY", http_client=httpx.Client( proxies="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) # Namespace access client.empathic_voice # EVI APIs client.tts # Text-to-speech APIs client.expression_measurement # Expression measurement APIs ``` -------------------------------- ### Initialize HumeClient and List Configurations Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Initialize the synchronous HumeClient with your API key and demonstrate calling the list_configs method for Empathic Voice. ```python from hume.client import HumeClient client = HumeClient(api_key="YOUR_API_KEY") client.empathic_voice.configs.list_configs() ``` -------------------------------- ### List Tools with Pagination Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Demonstrates how to list tools using the HumeClient and iterate through the results, handling pagination automatically. ```APIDOC ## List Tools with Pagination ### Description This example shows how to use the `list_tools` method from the `empathic_voice.tools` module to retrieve a list of tools. The results are paginated, and the SDK provides a generator (`SyncPager`) to handle this automatically. ### Method `client.empathic_voice.tools.list_tools()` ### Usage ```python from hume.client import HumeClient client = HumeClient(api_key="YOUR_API_KEY") # Iterate through all tools, handling pagination automatically for tool in client.empathic_voice.tools.list_tools(): print(tool) ``` ### Iterating Page-by-Page ### Description This example demonstrates how to iterate through the paginated results page by page, allowing for more control over data retrieval. ### Method `client.empathic_voice.tools.list_tools().iter_pages()` ### Usage ```python # Iterate through pages of tools for page in client.empathic_voice.tools.list_tools().iter_pages(): print(page.items) ``` ### Manual Pagination ### Description This example shows how to manually control pagination by fetching one page at a time using the `next_page()` method. ### Method `pager.next_page()` ### Usage ```python pager = client.empathic_voice.tools.list_tools() # Get the first page print(pager.items) # Get the second page pager = pager.next_page() print(pager.items) ``` ``` -------------------------------- ### List EVI Configurations (Synchronous) Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Authenticate and list EVI configurations using the synchronous HumeClient. ```python from hume.client import HumeClient # authenticate the synchronous client client = HumeClient(api_key=) # list your configs client.empathic_voice.configs.list_configs() ``` -------------------------------- ### Custom HTTP Client Configuration Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Demonstrates how to provide a custom `httpx.Client` instance to the `HumeClient` for advanced use cases like proxy support. ```APIDOC ## Custom HTTP Client Configuration ### Description Allows customization of the underlying HTTP client (httpx) for specific needs such as configuring proxies or custom transports. ### Method `HumeClient(http_client=httpx.Client(...))` ### Usage ```python import httpx from hume.client import HumeClient client = HumeClient( http_client=httpx.Client( proxies="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` ``` -------------------------------- ### Sync Pager: List Configurations Item by Item Source: https://context7.com/humeai/hume-python-sdk/llms.txt Demonstrates iterating through configurations one by one using a synchronous pager. Set `page_size` to control the number of items fetched per request. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") for config in client.empathic_voice.configs.list_configs(page_size=10): print(config.name) ``` -------------------------------- ### Download Job Predictions via Direct API Call Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Fetch job predictions by making a direct GET request to the Hume AI API. Ensure you replace placeholders with your actual job ID and API key. ```python import requests import json # Define the URL and headers url = "https://api.hume.ai/v0/batch/jobs//predictions" headers = { "X-Hume-Api-Key": "" } # Make the GET request response = requests.get(url, headers=headers) # Check if the request was successful if response.status_code == 200: # Parse the JSON response data = response.json() # Write the JSON data to a file with open("predictions.json", "w") as file: json.dump(data, file, indent=2) print("Response has been written to 'predictions.json'.") else: print(f"Failed to fetch data. Status code: {response.status_code}") print(response.text) ``` -------------------------------- ### Instantiate AsyncHumeClient and Access Namespaces Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Instantiate the new asynchronous base client and access the Expression Measurement and Empathic Voice Interface API namespaces. ```python from hume.client import AsyncHumeClient # base synchronous client client = AsyncHumeClient(api_key = ) # Expression Measurement (Batch) client.expression_measurement.batch # Expression Measurement (Streaming) client.expression_measurement.streaming # Empathic Voice Interface client.empathic_voice. ``` -------------------------------- ### Manually Paginate Through Tools Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Manually fetch pages of results. Allows for explicit control over pagination. Requires an initialized HumeClient. ```python pager = client.empathic_voice.tools.list_tools() # First page print(pager.items) # Second page pager = pager.next_page() print(pager.items) ``` -------------------------------- ### Iterate Through Paginated Tools Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Use this method to iterate through all tools, handling pagination automatically. Requires an initialized HumeClient. ```python from hume.client import HumeClient client = HumeClient(api_key="YOUR_API_KEY") for tool in client.empathic_voice.tools.list_tools(): print(tool) ``` -------------------------------- ### Create EVI Configuration Source: https://context7.com/humeai/hume-python-sdk/llms.txt Use this to create a new EVI configuration. Specify the name, EVI version, prompt, voice, language model, and event messages. ```python from hume import HumeClient from hume.empathic_voice import ( PostedConfigPromptSpec, PostedEventMessageSpec, PostedEventMessageSpecs, PostedLanguageModel, VoiceName, ) client = HumeClient(api_key="YOUR_API_KEY") config = client.empathic_voice.configs.create_config( name="Weather Assistant Config", evi_version="3", prompt=PostedConfigPromptSpec(id="your-prompt-uuid", version=0), voice=VoiceName(provider="HUME_AI", name="Ava Song"), language_model=PostedLanguageModel( model_provider="ANTHROPIC", model_resource="claude-3-7-sonnet-latest", temperature=1.0, ), event_messages=PostedEventMessageSpecs( on_new_chat=PostedEventMessageSpec(enabled=False, text=""), on_inactivity_timeout=PostedEventMessageSpec(enabled=False, text=""), on_max_duration_timeout=PostedEventMessageSpec(enabled=False, text=""), ), ) print(f"Created config ID: {config.id}") ``` -------------------------------- ### Initialize AsyncHumeClient and Make Non-blocking Calls Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Initialize the asynchronous HumeClient with your API key and demonstrate making non-blocking API calls within an async function. Requires Python 3.7+. ```python import asyncio from hume.client import AsyncHumeClient client = AsyncHumeClient(api_key="YOUR_API_KEY") async def main() -> None: await client.empathic_voice.configs.list_configs() asyncio.run(main()) ``` -------------------------------- ### Connect to EVI via WebSocket (Async) Source: https://context7.com/humeai/hume-python-sdk/llms.txt Establishes an asynchronous WebSocket connection to EVI using `AsyncHumeClient`. Supports the same parameters as the sync version and integrates with `asyncio`. Use `config_id` to apply a saved EVI configuration or `resumed_chat_group_id` to resume a previous conversation. ```python import asyncio import os from hume import AsyncHumeClient from hume.empathic_voice.types import UserInput client = AsyncHumeClient(api_key=os.getenv("HUME_API_KEY")) async def main(): async with client.empathic_voice.chat.connect( config_id="your-config-uuid", resumed_chat_group_id="previous-chat-group-id", # resume prior session ) as socket: await socket.send_publish(UserInput(text="What's the weather like?")) async for message in socket: print(f"Message type: {type(message).__name__}") if hasattr(message, "type") and message.type == "assistant_end": break asyncio.run(main()) ``` -------------------------------- ### Use Custom HTTP Client Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Provide a custom httpx client to the HumeClient for advanced configurations like proxies or custom transports. ```python import httpx from hume.client import HumeClient client = HumeClient( http_client=httpx.Client( proxies="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Connect to EVI via WebSocket (Sync) Source: https://context7.com/humeai/hume-python-sdk/llms.txt Opens a synchronous WebSocket connection to EVI. Use `config_id` to apply a saved EVI configuration or `resumed_chat_group_id` to resume a previous conversation. Handles sending user text input and receiving audio output, saving it to a file. ```python from hume.client import HumeClient from hume.empathic_voice.types import AudioInput, UserInput from hume.core.api_error import ApiError import base64 client = HumeClient(api_key="YOUR_API_KEY") with client.empathic_voice.chat.connect( config_id="your-config-uuid", config_version=1, verbose_transcription=True, ) as socket: # Send a text user input from hume.empathic_voice.types import UserInput socket.send_publish(UserInput(text="Hello, how are you today?")) # Receive and process messages for message in socket: msg_type = message.type if hasattr(message, "type") else type(message).__name__ print(f"Received: {msg_type}") # AssistantMessage, AudioOutput, ChatMetadata, etc. if hasattr(message, "type") and message.type == "audio_output": audio_bytes = base64.b64decode(message.data) with open("response.wav", "wb") as f: f.write(audio_bytes) break ``` -------------------------------- ### Iterate Through Pages of Tools Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Iterate through paginated results page by page. Useful for processing data in chunks. Requires an initialized HumeClient. ```python for page in client.empathic_voice.tools.list_tools().iter_pages(): print(page.items) ``` -------------------------------- ### Create EVI System Prompt Source: https://context7.com/humeai/hume-python-sdk/llms.txt Create a new system prompt for EVI. The `text` field uses XML-like tags to define the assistant's role and instructions. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") prompt = client.empathic_voice.prompts.create_prompt( name="Weather Assistant Prompt", text=( "You are an AI weather assistant providing users with accurate and " "up-to-date weather information. Respond to user queries concisely and clearly. " "Use simple language and avoid technical jargon. Provide temperature, precipitation, " "wind conditions, and any weather alerts. Include helpful tips if severe weather " "is expected." ), version_description="Initial version of the weather assistant prompt.", ) print(f"Prompt ID: {prompt.id}, version: {prompt.version}") ``` -------------------------------- ### Download Job Artifacts with HumeClient Source: https://context7.com/humeai/hume-python-sdk/llms.txt Uses a synchronous convenience method to download and write job artifacts directly to a file. This method is part of the `BatchClientWithUtils`. ```python from hume import HumeClient sync_client = HumeClient(api_key="YOUR_API_KEY") sync_client.expression_measurement.batch.get_and_write_job_artifacts( id="your-job-id", file_name="artifacts.zip", ) ``` -------------------------------- ### Connect to Expression Measurement WebSocket Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Establish a WebSocket connection for real-time expression measurement. Requires an AsyncHumeClient and an API key. ```python import os from hume import AsyncHumeClient client = AsyncHumeClient(api_key=os.getenv("HUME_API_KEY")) async with client.expression_measurement.stream.connect() as hume_socket: print(await hume_socket.get_job_details()) ``` -------------------------------- ### Configuring Request Options: Retries Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Illustrates how to configure automatic retries with exponential backoff for specific requests using `RequestOptions`. ```APIDOC ## Configuring Request Options: Retries ### Description The Hume SDK supports automatic retries with exponential backoff for retriable HTTP status codes (408, 409, 429, 5xx). You can configure the maximum number of retry attempts for a specific request. ### Method `client.expression_measurement.batch.get_job_predictions(..., request_options=RequestOptions(max_retries=5))` ### Usage ```python from hume.client import HumeClient from hume.core import RequestOptions client = HumeClient(...) # Override retries for a specific method to allow up to 5 attempts client.expression_measurement.batch.get_job_predictions( ..., # Other method arguments request_options=RequestOptions(max_retries=5) ) ``` ``` -------------------------------- ### empathic_voice.prompts.create_prompt Source: https://context7.com/humeai/hume-python-sdk/llms.txt Creates a new EVI system prompt that defines the assistant's behavior and persona using XML-like `` tags. Includes an optional version description. ```APIDOC ## empathic_voice.prompts.create_prompt — Create an EVI System Prompt Creates a system prompt that shapes EVI's behavior and persona. The `text` field uses XML-like `` tags to define the assistant's role and instructions. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") prompt = client.empathic_voice.prompts.create_prompt( name="Weather Assistant Prompt", text=( "You are an AI weather assistant providing users with accurate and " "up-to-date weather information. Respond to user queries concisely and clearly. " "Use simple language and avoid technical jargon. Provide temperature, precipitation, " "wind conditions, and any weather alerts. Include helpful tips if severe weather " "is expected." ), version_description="Initial version of the weather assistant prompt.", ) print(f"Prompt ID: {prompt.id}, version: {prompt.version}") ``` ``` -------------------------------- ### empathic_voice.configs.create_config Source: https://context7.com/humeai/hume-python-sdk/llms.txt Creates a new EVI configuration with specified voice, language model, prompt, and event settings. Returns the created configuration object. ```APIDOC ## empathic_voice.configs.create_config — Create an EVI Configuration Creates a new EVI configuration with a voice, language model, prompt, tools, event messages, and other settings. Returns the created `ReturnConfig` object. ```python from hume import HumeClient from hume.empathic_voice import ( PostedConfigPromptSpec, PostedEventMessageSpec, PostedEventMessageSpecs, PostedLanguageModel, VoiceName, ) client = HumeClient(api_key="YOUR_API_KEY") config = client.empathic_voice.configs.create_config( name="Weather Assistant Config", evi_version="3", prompt=PostedConfigPromptSpec(id="your-prompt-uuid", version=0), voice=VoiceName(provider="HUME_AI", name="Ava Song"), language_model=PostedLanguageModel( model_provider="ANTHROPIC", model_resource="claude-3-7-sonnet-latest", temperature=1.0, ), event_messages=PostedEventMessageSpecs( on_new_chat=PostedEventMessageSpec(enabled=False, text=""), on_inactivity_timeout=PostedEventMessageSpec(enabled=False, text=""), on_max_duration_timeout=PostedEventMessageSpec(enabled=False, text=""), ), ) print(f"Created config ID: {config.id}") ``` ``` -------------------------------- ### Legacy SDK: Expression Measurement Stream Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide This snippet demonstrates expression measurement using the legacy Hume Python SDK. It uses different import paths and configuration objects compared to the new SDK. ```python import asyncio from hume import HumeStreamClient from hume.models.config import LanguageConfig samples = [ "Mary had a little lamb,", "Its fleece was white as snow." "Everywhere the child went," "The little lamb was sure to go." ] async def main(): client = HumeStreamClient("") config = LanguageConfig() async with client.connect([config]) as socket: for sample in samples: result = await socket.send_text(sample) emotions = result["language"]["predictions"][0]["emotions"] print(emotions) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### List and Retrieve EVI Prompts Source: https://context7.com/humeai/hume-python-sdk/llms.txt List all available prompts (paginated) or retrieve a specific version of a prompt using its UUID and version number. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") # List all prompts, latest versions only for prompt in client.empathic_voice.prompts.list_prompts(page_size=5): print(f" {prompt.name} — v{prompt.version} (id={prompt.id})") # Retrieve a specific version specific = client.empathic_voice.prompts.get_prompt_version( id="your-prompt-uuid", version=0, ) print(f"Prompt text preview: {specific.text[:80]}...") ``` -------------------------------- ### Client Usage: Sync vs. Async Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Illustrates invalid usage of a synchronous client for asynchronous operations and valid usage of an asynchronous client for both asynchronous and synchronous operations. Awaiting asynchronous methods is required when using an async client. ```python from hume.client import HumeClient, AsyncHumeClient # INVALID: using a synchronous client for asynchronous behavior client = HumeClient(api_key = ) # Using the asynchronous connect method with a sync client will cause an error async with client.empathic_voice.chat.connect() as socket: # ... # VALID: using an asynchronous client for asynchronous behavior async_client = AsyncHumeClient(api_key = ) # Using the async connect method with an async client will work properly async with async_client.empathic_voice.chat.connect() as socket: # ... # VALID: using an asynchronous client for synchronous behavior async_client = AsyncHumeClient(api_key = ) # Using the configs.list_configs() method with an async client print(await client.empathic_voice.configs.list_configs()) ``` -------------------------------- ### Configuring Request Options: Timeouts Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Explains how to set request timeouts at the client level or override them for individual requests using `RequestOptions`. ```APIDOC ## Configuring Request Options: Timeouts ### Description Requests have a default timeout of 60 seconds. This can be configured globally for the client or overridden for individual requests using `RequestOptions`. ### Method `HumeClient(timeout=20.0)` and `RequestOptions(timeout_in_seconds=20)` ### Usage ```python from hume.client import HumeClient from hume.core import RequestOptions # Configure all requests to time out after 20 seconds client = HumeClient(timeout=20.0) # Override timeout for a specific method to 20 seconds client.expression_measurement.batch.get_job_predictions( ..., # Other method arguments request_options=RequestOptions(timeout_in_seconds=20) ) ``` ``` -------------------------------- ### List EVI Configurations Source: https://context7.com/humeai/hume-python-sdk/llms.txt Retrieves a paginated list of saved EVI configurations. By default, only the latest version of each config is returned. Use `restrict_to_most_recent=False` to retrieve all versions. Supports filtering by name. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") # Iterate all config items transparently (pagination handled automatically) for config in client.empathic_voice.configs.list_configs(page_size=10): print(f"Config: {config.name} (id={config.id}, version={config.version})") # Page-by-page iteration pager = client.empathic_voice.configs.list_configs(page_size=5) first_page = pager.items print(first_page) second_pager = pager.next_page() print(second_pager.items) ``` -------------------------------- ### List Tools with empathic_voice.tools.list_tools (Paginated) Source: https://context7.com/humeai/hume-python-sdk/llms.txt Retrieve a paginated list of user-defined tools. Supports both item-level and page-level iteration. Filters to the most recent version of each tool by default. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") # Item-level iteration for tool in client.empathic_voice.tools.list_tools(page_size=10): print(f"Tool: {tool.name} (id={tool.id})") # Page-level iteration for page in client.empathic_voice.tools.list_tools(page_size=5).iter_pages(): print(f"Page has {len(page.items)} items") for t in page.items: print(f" {t.name}") ``` -------------------------------- ### Create a User-Defined Tool with empathic_voice.tools.create_tool Source: https://context7.com/humeai/hume-python-sdk/llms.txt Use this function to create custom tools that EVI can invoke. The 'parameters' field requires a JSON Schema string to describe the tool's arguments. ```python import json from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") tool = client.empathic_voice.tools.create_tool( name="get_current_weather", description="Get the current weather for a given location.", parameters=json.dumps({ "type": "object", "properties": { "location": { "type": "string", "description": "City and state, e.g. 'San Francisco, CA'", }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], }, }, "required": ["location"], }), fallback_content="I'm unable to retrieve weather information right now.", ) print(f"Tool ID: {tool.id}") ``` -------------------------------- ### Download Job Artifacts with Async Stream Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Use aiofiles to simplify writing async streams of bytes to a file, demonstrated here for downloading job artifacts from the Expression Measurement API. ```python import aiofiles from hume import AsyncHumeClient client = AsyncHumeClient() async with aiofiles.open('artifacts.zip', mode='wb') as file: async for chunk in client.expression_measurement.batch.get_job_artifacts(id="my-job-id"): await file.write(chunk) ``` -------------------------------- ### WebSocket Stream for Expression Measurement Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Shows how to establish a WebSocket connection for real-time expression measurement using the AsyncHumeClient. ```APIDOC ## WebSocket Stream for Expression Measurement ### Description This example demonstrates how to connect to the expression measurement WebSocket stream using `AsyncHumeClient`. Model configuration is sent with each payload, not at connection time. ### Method `client.expression_measurement.stream.connect()` ### Usage ```python import os from hume import AsyncHumeClient client = AsyncHumeClient(api_key=os.getenv("HUME_API_KEY")) async with client.expression_measurement.stream.connect() as hume_socket: # Get job details from the socket print(await hume_socket.get_job_details()) # Model configuration (e.g., face, language, prosody) is sent per payload # via send_publish(), send_text(), or send_file() ``` ``` -------------------------------- ### Streaming Expression Measurement via WebSocket Source: https://context7.com/humeai/hume-python-sdk/llms.txt Opens a WebSocket connection to Hume's real-time Expression Measurement streaming API for continuous analysis of audio/video/text data. Requires an API key and a sample audio file. ```python import asyncio import os from hume import AsyncHumeClient client = AsyncHumeClient(api_key=os.getenv("HUME_API_KEY")) async def main(): async with client.expression_measurement.stream.connect() as hume_socket: # Get details about the current job/connection details = await hume_socket.get_job_details() print(f"Connection details: {details}") # Send a file for real-time analysis (model config per payload) with open("audio_sample.wav", "rb") as f: audio_bytes = f.read() result = await hume_socket.send_file( file=audio_bytes, models={"prosody": {}}, ) print(f"Predictions: {result}") asyncio.run(main()) ``` -------------------------------- ### Sync Pager: Manual Page Navigation Source: https://context7.com/humeai/hume-python-sdk/llms.txt Shows how to manually navigate through pages of results using a synchronous pager. The `next_page()` method fetches the subsequent page of items. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") pager = client.empathic_voice.tools.list_tools(page_size=5) print("Page 1:", [t.name for t in pager.items]) pager = pager.next_page() print("Page 2:", [t.name for t in pager.items]) ``` -------------------------------- ### New SDK: Expression Measurement Stream Source: https://github.com/humeai/hume-python-sdk/wiki/Python-SDK-Migration-Guide Use this snippet for expression measurement with the new asynchronous Hume Python SDK. It requires importing specific classes for configuration and stream options. ```python import asyncio from hume import AsyncHumeClient from hume.expression_measurement.stream import Config from hume.expression_measurement.stream.socket_client import StreamConnectOptions from hume.expression_measurement.stream.types import StreamLanguage samples = [ "Mary had a little lamb,", "Its fleece was white as snow." "Everywhere the child went," "The little lamb was sure to go." ] async def main(): client = AsyncHumeClient(api_key="") model_config = Config(language=StreamLanguage()) stream_options = StreamConnectOptions(config=model_config) async with client.expression_measurement.stream.connect(options=stream_options) as socket: for sample in samples: result = await socket.send_text(sample) print(result.language.predictions[0]['emotions']) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Download Job Artifacts with AsyncHumeClient Source: https://context7.com/humeai/hume-python-sdk/llms.txt Streams the artifacts ZIP file for a completed inference job as a byte iterator using an async client. Use `get_and_write_job_artifacts` for a convenience method that writes to disk directly. ```python import aiofiles import asyncio from hume import AsyncHumeClient client = AsyncHumeClient(api_key="YOUR_API_KEY") # Async streaming write async def download_artifacts(job_id: str, output_path: str = "artifacts.zip"): async with aiofiles.open(output_path, mode="wb") as f: async for chunk in client.expression_measurement.batch.get_job_artifacts( id=job_id ): await f.write(chunk) print(f"Artifacts saved to {output_path}") asyncio.run(download_artifacts("your-job-id")) ``` -------------------------------- ### empathic_voice.configs.list_configs — List EVI Configurations Source: https://context7.com/humeai/hume-python-sdk/llms.txt Retrieves a paginated list of saved EVI configurations. By default, only the most recent version of each configuration is returned. To fetch all versions, set `restrict_to_most_recent=False`. This method also supports filtering configurations by name. ```APIDOC ## empathic_voice.configs.list_configs — List EVI Configurations Returns a paginated list of saved EVI configurations. By default only the latest version of each config is returned. Use `restrict_to_most_recent=False` to retrieve all versions. Supports filtering by name. ```python from hume import HumeClient client = HumeClient(api_key="YOUR_API_KEY") # Iterate all config items transparently (pagination handled automatically) for config in client.empathic_voice.configs.list_configs(page_size=10): print(f"Config: {config.name} (id={config.id}, version={config.version})") # Page-by-page iteration pager = client.empathic_voice.configs.list_configs(page_size=5) first_page = pager.items print(first_page) second_pager = pager.next_page() print(second_pager.items) ``` ``` -------------------------------- ### Access Namespaced APIs Source: https://github.com/humeai/hume-python-sdk/blob/main/README.md Demonstrates how to access different Hume APIs (empathic voice, tts, expression measurement) through their respective namespaces on the HumeClient. ```python from hume.client import HumeClient client = HumeClient(api_key="YOUR_API_KEY") client.empathic_voice. # APIs specific to Empathic Voice client.tts. # APIs specific to Text-to-speech client.expression_measurement. # APIs specific to Expression Measurement ``` -------------------------------- ### Per-Request Configuration with RequestOptions Source: https://context7.com/humeai/hume-python-sdk/llms.txt Shows how to use `RequestOptions` to override default retry counts and timeouts for individual API calls. ```APIDOC ## RequestOptions — Per-Request Configuration `RequestOptions` allows overriding the default retry count and timeout on a per-call basis. This is useful for long-running inference jobs or calls that need stricter time limits. ```python from hume.client import HumeClient from hume.core import RequestOptions client = HumeClient(api_key="YOUR_API_KEY") # Override retries and timeout for one specific call result = client.expression_measurement.batch.get_job_predictions( id="my-job-id", request_options=RequestOptions( max_retries=5, timeout_in_seconds=30, ), ) ``` ```