### Add and Make Example Executable Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/CONTRIBUTING.md Add new examples to the examples/ directory and make them executable. ```python # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` ```sh chmod +x examples/.py ``` -------------------------------- ### Install from Wheel File Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/CONTRIBUTING.md Install the package efficiently after building it by providing the path to the generated wheel file. ```sh pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Install Parallel SDK Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Install the Parallel SDK using pip. For optional aiohttp support, use the extra. ```bash pip install parallel-web ``` ```bash pip install parallel-web[aiohttp] ``` -------------------------------- ### Install SDK from Git Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/CONTRIBUTING.md Install the parallel-sdk-python directly from its Git repository using pip. ```sh pip install git+ssh://git@github.com/parallel-web/parallel-sdk-python.git ``` -------------------------------- ### Install and Use DefaultAioHttpClient Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/configuration.md Install the aiohttp extra for DefaultAioHttpClient and use it with AsyncParallel. The HTTP client is automatically managed by the context manager. ```bash pip install parallel-web[aiohttp] ``` ```python from parallel import DefaultAioHttpClient, AsyncParallel async def main(): async with AsyncParallel( api_key="...", http_client=DefaultAioHttpClient() ) as client: # Use client pass ``` -------------------------------- ### Install Parallel Python SDK with aiohttp Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/README.md Install the library with the aiohttp extra for improved concurrency performance in asynchronous operations. ```sh pip install parallel-web[aiohttp] ``` -------------------------------- ### Install Parallel Python SDK Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/README.md Install the library from PyPI using pip. This is the first step to using the Parallel API in your Python application. ```sh pip install parallel-web ``` -------------------------------- ### API Key Configuration Examples Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/configuration.md Demonstrates different ways to provide the API key during client initialization. The key is required unless the PARALLEL_API_KEY environment variable is set. ```python # Explicit client = Parallel(api_key="pk_abc123...") ``` ```python # From environment import os api_key = os.environ.get("PARALLEL_API_KEY") client = Parallel(api_key=api_key) ``` ```python # Automatic (if PARALLEL_API_KEY is set) client = Parallel() ``` -------------------------------- ### Example Match Conditions Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/beta-findall.md Provides an example of how to construct a list of match conditions for filtering entities. This includes conditions for industry, founding year, and country. ```python match_conditions = [ { "attribute": "industry", "condition": "equals", "value": "AI" }, { "attribute": "founded_year", "condition": "greater_than", "value": 2020 }, { "attribute": "country", "condition": "equals", "value": "USA" } ] ``` -------------------------------- ### Client Options Example Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/client.md Demonstrates how to override timeout for a specific request and create a specialized client with custom headers using `with_options` and `copy`. ```python # Override timeout for specific request client.with_options(timeout=5.0).task_run.create( input="What is Python?", processor="base", ) # Create specialized client with custom headers admin_client = client.copy( default_headers={"X-Admin-Key": "admin-secret"} ) ``` -------------------------------- ### Initializing Parallel SDK with Environment Configuration Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Initialize the `Parallel` client without arguments to automatically pick up configuration from environment variables. This simplifies setup when using environment-based configuration. ```python from parallel import Parallel # All configuration from environment client = Parallel() ``` -------------------------------- ### Synchronous Streaming Response Example Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/responses.md Provides an example of using `with_streaming_response` for a synchronous API call, demonstrating how to access headers and parse the response body iteratively. ```python # Stream task creation response with client.task_run.with_streaming_response.create( input="What is Python?", processor="base", ) as response: print(f"Status: {response.status_code}") # Read headers without reading body print(f"Content-Type: {response.headers.get('Content-Type')}") # Parse response task_run = response.parse() print(f"Task ID: {task_run.run_id}") # Stream task group events with client.task_group.with_streaming_response.events( task_group_id="group_abc123" ) as response: for line in response.iter_lines(): print(f"Event: {line}") ``` -------------------------------- ### Monitoring Web Changes with Event Streams Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Set up a monitor to track changes on the web, such as new releases or search query results. This example configures a monitor for a search query and sets up a webhook for notifications. ```python from parallel import Parallel client = Parallel(api_key="your-api-key") # Create monitor for search query monitor = client.monitor.create( type="event_stream", frequency="1d", # Daily checks settings={ "search_query": "Python 3.14 release", "objective": "Track latest Python releases" }, processor="base", webhook={ "url": "https://example.com/webhook", "headers": {"Authorization": "Bearer ..."} } ) # Poll for change events events = client.monitor.events(monitor.monitor_id) for event in events.events: if event.type == "event_stream": print(f"Change detected: {event.change_summary}") ``` -------------------------------- ### Install Development Dependencies with Pip Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/CONTRIBUTING.md Install development dependencies using pip if you are not using Rye. Ensure the Python version matches the one specified in .python-version. ```sh pip install -r requirements-dev.lock ``` -------------------------------- ### Base URL Configuration Examples Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/configuration.md Shows how to configure the base URL for API requests. This can be used to point to custom endpoints or staging environments. The URL can be set explicitly or via the PARALLEL_BASE_URL environment variable. ```python # Production (default) client = Parallel(api_key="...") ``` ```python # Custom endpoint client = Parallel( api_key="...", base_url="https://custom.example.com/api" ) ``` ```python # Testing/staging client = Parallel( api_key="...", base_url="https://staging-api.parallel.ai" ) ``` ```python # From environment import os base_url = os.environ.get("PARALLEL_BASE_URL", "https://api.parallel.ai") client = Parallel(api_key="...", base_url=base_url) ``` -------------------------------- ### Async Client with aiohttp Backend Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/README.md Instantiate the AsyncParallel client using DefaultAioHttpClient for the HTTP backend. This requires aiohttp to be installed. ```python import os import asyncio from parallel import DefaultAioHttpClient from parallel import AsyncParallel async def main() -> None: async with AsyncParallel( api_key=os.environ.get("PARALLEL_API_KEY"), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: task_run = await client.task_run.create( input="What was the GDP of France in 2023?", processor="base", ) print(task_run.interaction_id) asyncio.run(main()) ``` -------------------------------- ### AsyncAPIResponse Usage Example Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/responses.md Demonstrates how to use `AsyncAPIResponse` to make an asynchronous API call and process the response, including parsing the result. ```python import asyncio from parallel import AsyncParallel async def main(): async with AsyncParallel(api_key="...") as client: response = await client.task_run.with_raw_response.create( input="...", processor="base", ) print(response.status_code) task_run = await response.parse() print(task_run.run_id) asyncio.run(main()) ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/CONTRIBUTING.md Use this command to synchronize project dependencies after manually installing Rye. ```sh rye sync --all-features ``` -------------------------------- ### Asynchronous Streaming Response Example Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/responses.md Demonstrates how to handle asynchronous streaming responses, specifically for fetching task group events, using `async with` and `async for`. ```python import asyncio from parallel import AsyncParallel async def main(): async with AsyncParallel(api_key="...") as client: # Stream task group events async with client.task_group.with_streaming_response.events( task_group_id="group_abc123" ) as response: async for line in response.iter_lines(): print(f"Event: {line}") asyncio.run(main()) ``` -------------------------------- ### Timeout Configuration Examples Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/configuration.md Illustrates setting request timeouts for the client. You can set a uniform timeout or use `httpx.Timeout` for granular control over connect, read, and write timeouts. Timeouts can also be overridden per request or within a context manager. ```python import httpx from parallel import Parallel # Uniform timeout (30 seconds) client = Parallel(api_key="...", timeout=30.0) ``` ```python # Granular control client = Parallel( api_key="...", timeout=httpx.Timeout( timeout=60.0, # Overall timeout connect=5.0, # Connection establishment read=30.0, # Reading response write=10.0, # Writing request pool=None, # Pool timeout (not enforced if None) ) ) ``` ```python # Override per request client.task_run.create( input="...", processor="base", timeout=120.0, # 120 second timeout for this request ) ``` ```python # Context manager for scoped override fast_client = client.with_options(timeout=5.0) task = fast_client.task_run.create(input="...", processor="lite") ``` -------------------------------- ### Create and Run a Task Asynchronously Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/client.md Instantiates the AsyncParallel client, creates a task using a specified input and processor, and prints the interaction ID. Ensure you have an API key and have installed the parallel SDK. ```python import asyncio from parallel import AsyncParallel async def main(): async with AsyncParallel(api_key="your-api-key") as client: task = await client.task_run.create( input="What is Python?", processor="base", ) print(task.interaction_id) asyncio.run(main()) ``` -------------------------------- ### Start a FindAll Run Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/beta-findall.md Initiates a FindAll discovery and evaluation process. Use this to find entities based on a natural language objective and specific match conditions. The API returns immediately with a 'queued' status. ```python client = Parallel(api_key="your-api-key") run = client.beta.findall.create( objective="Find Python frameworks for web development", entity_type="framework", generator="base", match_conditions=[ { "attribute": "language", "condition": "equals", "value": "Python" }, { "attribute": "domain", "condition": "equals", "value": "web" } ], match_limit=50, metadata={"project": "framework_research"}, ) print(run.findall_id) print(run.status) # 'queued' ``` -------------------------------- ### Catch AuthenticationError Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/errors.md Example of how to catch and handle an AuthenticationError, prompting the user to check their API key or environment variable. ```python from parallel import AuthenticationError try: client = Parallel(api_key="invalid_key") task = client.task_run.create(input="...", processor="base") except AuthenticationError as e: print("Invalid API key. Check PARALLEL_API_KEY environment variable.") ``` -------------------------------- ### Perform Entity Search Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/beta-findall.md Example of how to perform a direct entity search using the client. Specify the entity type, search criteria, and an optional limit for the number of results. ```python results = client.beta.findall.entity_search( entity_type="company", search_criteria="AI startups founded in 2023", limit=20, ) ``` -------------------------------- ### Create and Wait for Task Run Result (Async) Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/task-run.md Demonstrates how to create a task run and asynchronously wait for its result using the AsyncParallel client. Ensure you have the parallel SDK installed and an API key. ```python import asyncio from parallel import AsyncParallel async def main(): async with AsyncParallel(api_key="your-api-key") as client: task = await client.task_run.create( input="What is Python?", processor="base", ) result = await client.task_run.wait_for_result(task.run_id) print(result.output) asyncio.run(main()) ``` -------------------------------- ### Batch Processing with Task Groups Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Create a task group to process a large number of tasks efficiently. This example shows how to add runs to a group, monitor progress, and retrieve results. ```python import time from parallel import Parallel client = Parallel(api_key="your-api-key") # Create batch group = client.task_group.create( metadata={"batch_id": "batch_001"} ) # Add 1000 tasks inputs = [f"Research query {i}" for i in range(1000)] response = client.task_group.add_runs( task_group_id=group.task_group_id, inputs=inputs, default_task_spec={ "output_schema": {"type": "auto"} } ) # Monitor progress while True: group_status = client.task_group.retrieve(group.task_group_id) progress = group_status.completed_runs / group_status.total_runs print(f"Progress: {progress:.1%}") if group_status.status == "completed": break time.sleep(5) # Get results runs = client.task_group.get_runs(group.task_group_id, limit=50) for run in runs.runs: if run.status == "completed": result = client.task_run.result(run.run_id) print(result.output) ``` -------------------------------- ### Create a FindAll Run Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/beta-findall.md Starts a FindAll run to discover entities matching specified criteria. Returns immediately with a 'queued' status. Progress can be tracked via polling, events, or webhooks. ```APIDOC ## POST /v1beta/findall/runs ### Description Starts a FindAll run to discover and evaluate entities that match natural language objectives and structured match conditions. ### Method POST ### Endpoint /v1beta/findall/runs ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **entity_type** (str) - Required - Type of entity to discover (e.g., "company", "person", "website"). - **generator** (Literal["base", "core", "pro", "preview"]) - Required - Generator to use. Affects quality/cost tradeoff. - **match_conditions** (Iterable[MatchConditionParam]) - Required - List of conditions entities must match. - **match_limit** (int) - Required - Max entities to find (5-1000 inclusive). May return fewer. - **objective** (str) - Required - Natural language description of what you're looking for. - **exclude_list** (Iterable[ExcludeList] | None) - Optional - Entities to exclude from results. - **metadata** (Dict[str, Union[str, float, bool]] | None) - Optional - User-provided metadata for the run. - **webhook** (WebhookParam | None) - Optional - Webhook for completion notifications. - **betas** (List[ParallelBetaParam]) - Optional - Beta features to enable. ### Request Example ```python client.beta.findall.create( objective="Find Python frameworks for web development", entity_type="framework", generator="base", match_conditions=[ { "attribute": "language", "condition": "equals", "value": "Python" }, { "attribute": "domain", "condition": "equals", "value": "web" } ], match_limit=50, metadata={"project": "framework_research"}, ) ``` ### Response #### Success Response (200) - **FindAllRun** - Object containing the run status and ID. #### Response Example ```json { "findall_id": "findall_abc123", "status": "queued" } ``` ``` -------------------------------- ### Basic Error Handling with Parallel SDK Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/errors.md Provides a fundamental example of error handling for API status and connection errors. This pattern is essential for robustly interacting with the Parallel API. ```python from parallel import Parallel, APIStatusError, APIConnectionError client = Parallel(api_key="your-api-key") try: task = client.task_run.create( input="What is Python?", processor="base", ) except APIStatusError as e: print(f"API error {e.status_code}: {e.message}") except APIConnectionError as e: print(f"Connection error: {e.message}") ``` -------------------------------- ### Performing a Research Query with Structured Output Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Create a research task with a defined output schema and wait for its result. This example demonstrates how to structure a complex query and extract specific JSON data. ```python from parallel import Parallel client = Parallel(api_key="your-api-key") # Create research task task = client.task_run.create( input="What were the key achievements of AI in 2023?", processor="pro", # Higher quality for research task_spec={ "output_schema": { "type": "object", "properties": { "achievements": { "type": "array", "items": { "type": "object", "properties": { "title": {"type": "string"}, "description": {"type": "string"}, "impact": {"type": "string"} } } }, "summary": {"type": "string"} } } }, ) # Wait for completion result = client.task_run.wait_for_result(task.run_id) # Extract structured data if result.output.type == "json": data = result.output.data for achievement in data.get("achievements", []): print(f"- {achievement['title']}: {achievement['description']}") ``` -------------------------------- ### Create, Retrieve, and Get Result of a Task Run Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Demonstrates how to create a web research task, check its status, retrieve the output, and list progress events. Use for single, discrete web research and extraction tasks. ```python # Create a task task = client.task_run.create( input="What was the GDP of France in 2023?", processor="base", # "lite", "base", "pro" ) # Check status task = client.task_run.retrieve(task.run_id) print(task.status) # queued, running, completed, failed, etc. # Get result result = client.task_run.result(task.run_id) print(result.output) # List progress events events = client.task_run.events(task.run_id) ``` -------------------------------- ### Client Initialization Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Demonstrates how to initialize the Parallel client with various configuration options. ```APIDOC ## Client Initialization ### Description Initialize the Parallel client with API key, base URL, timeout, retry settings, and default headers/query parameters. ### Code ```python from parallel import Parallel client = Parallel( api_key="your-api-key", # From PARALLEL_API_KEY env var base_url="https://api.parallel.ai", # From PARALLEL_BASE_URL env var timeout=60.0, # Request timeout in seconds max_retries=2, # Automatic retries for transient errors default_headers={"X-Custom": "..."}, default_query={"version": "v1"}, ) ``` ``` -------------------------------- ### Set up Mock Server for Tests Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/CONTRIBUTING.md Run this script to set up a mock server against the OpenAPI spec, which is required for most tests. ```sh ./scripts/mock ``` -------------------------------- ### Create and Monitor Snapshot Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/monitor.md Illustrates the process of creating a task, waiting for its result, and then setting up a snapshot monitor to track changes in the task's output. Includes configuration for frequency and processor. ```python # First, create a task task = client.task_run.create( input="Current state of AI in healthcare", processor="base", ) # Wait for completion result = client.task_run.wait_for_result(task.run_id) # Monitor the result for changes monitor = client.monitor.create( type="snapshot", frequency="6h", # Check every 6 hours settings={\"run_id\": task.run_id}, processor="lite", ) # Get snapshot change events events = client.monitor.events(monitor.monitor_id) for event in events.events: if event.type == "snapshot": print(f"Output changed: {event.summary}") ``` -------------------------------- ### Create and Manage Beta FindAll Runs Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Demonstrates how to use the Beta FindAll API to discover entities based on complex criteria, check status, retrieve results, and extend the search. Suitable for advanced entity discovery and evaluation. ```python # Create a FindAll run run = client.beta.findall.create( objective="Find Python web frameworks with good documentation", entity_type="framework", generator="base", match_conditions=[ { "attribute": "language", "condition": "equals", "value": "Python" }, { "attribute": "domain", "condition": "equals", "value": "web" }, { "attribute": "documentation_quality", "condition": "equals", "value": "excellent" } ], match_limit=50, ) # Check status run = client.beta.findall.retrieve(run.findall_id) # Get results result = client.beta.findall.result(run.findall_id) for entity in result.candidates: print(f"Entity: {entity.name}") print(f"Match score: {entity.match_score}") print(f"Reasoning: {entity.reasoning}") # Extend search for more results extended = client.beta.findall.extend( run.findall_id, additional_match_limit=50, ) ``` -------------------------------- ### Determine Installed Parallel SDK Version Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/README.md Use this snippet to check the version of the Parallel SDK installed in your Python environment at runtime. Ensure the 'parallel' library is imported. ```python import parallel print(parallel.__version__) ``` -------------------------------- ### Create and Manage Monitors Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Illustrates how to create monitors for tracking web content changes, including monitoring search queries or specific task outputs. Use for scheduled web observation and change detection. ```python # Monitor a search query monitor = client.monitor.create( type="event_stream", frequency="1d", # Check daily settings={ "search_query": "Python 3.13 release", "objective": "Track new releases" }, processor="base", ) # Monitor a task's output for changes monitor = client.monitor.create( type="snapshot", frequency="6h", settings={"run_id": "run_abc123"}, ) # Get monitor events events = client.monitor.events(monitor.monitor_id) # List all monitors monitors = client.monitor.list(limit=20) # Update monitor monitor = client.monitor.update( monitor.monitor_id, frequency="12h", ) # Delete monitor client.monitor.delete(monitor.monitor_id) ``` -------------------------------- ### Access Raw HTTP Response with `with_raw_response` Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/responses.md Use `with_raw_response` to get the raw HTTP response object, including status code and headers. Call `.parse()` on the response object to get the actual parsed response. ```python response = client.RESOURCE.with_raw_response.METHOD(...) print(response.status_code) print(response.headers) # Parse the actual response object result = response.parse() ``` ```python # Get raw response for task creation response = client.task_run.with_raw_response.create( input="What is Python?", processor="base", ) # Access HTTP metadata print(f"Status: {response.status_code}") print(f"Headers: {dict(response.headers)}") # Get the parsed TaskRun object task_run = response.parse() print(f"Run ID: {task_run.run_id}") ``` ```python import asyncio from parallel import AsyncParallel async def main(): async with AsyncParallel(api_key="...") as client: response = await client.task_run.with_raw_response.create( input="What is Python?", processor="base", ) print(f"Status: {response.status_code}") task_run = await response.parse() print(f"Run ID: {task_run.run_id}") asyncio.run(main()) ``` -------------------------------- ### Get TaskGroup Runs Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/api.md Retrieves all runs associated with a TaskGroup. ```APIDOC ## GET /v1/tasks/groups/{taskgroup_id}/runs ### Description Retrieves all runs associated with a TaskGroup. ### Method GET ### Endpoint /v1/tasks/groups/{taskgroup_id}/runs ### Parameters #### Path Parameters - **task_group_id** (string) - Required - The ID of the TaskGroup to retrieve runs for. #### Query Parameters - **params** (object) - Optional - Parameters for filtering or paginating runs. ### Response #### Success Response (200) - **TaskGroupGetRunsResponse** (object) - Response containing TaskGroup runs. ``` -------------------------------- ### Get TaskGroup Events Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/api.md Retrieves events associated with a TaskGroup. ```APIDOC ## GET /v1/tasks/groups/{taskgroup_id}/events ### Description Retrieves events associated with a TaskGroup. ### Method GET ### Endpoint /v1/tasks/groups/{taskgroup_id}/events ### Parameters #### Path Parameters - **task_group_id** (string) - Required - The ID of the TaskGroup to retrieve events for. #### Query Parameters - **params** (object) - Optional - Parameters for filtering or paginating events. ### Response #### Success Response (200) - **TaskGroupEventsResponse** (object) - Response containing TaskGroup events. ``` -------------------------------- ### Initialize Synchronous Parallel Client Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/configuration.md Instantiate the synchronous Parallel client with various configuration options. API key and base URL can be provided directly or via environment variables. ```python from parallel import Parallel client = Parallel( api_key="your-api-key", # Required or from PARALLEL_API_KEY env var base_url="https://api.parallel.ai", # Optional, from PARALLEL_BASE_URL env var timeout=60.0, # Seconds, default 60 max_retries=2, # Number of retries for transient errors default_headers={"X-Custom-Header": "value"}, # Optional headers default_query={"param": "value"}, # Optional query params http_client=None, # Optional custom httpx.Client ) ``` -------------------------------- ### Create and Poll Event Stream Monitor (Sync) Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/monitor.md Shows how to create an event stream monitor with detailed settings and then poll for events. Includes webhook configuration for notifications. ```python # Create an event stream monitor monitor = client.monitor.create( type="event_stream", frequency="1d", # Check daily settings={ "search_query": "machine learning latest developments", "objective": "Track new ML frameworks" }, processor="base", # More thorough analysis webhook={ "url": "https://example.com/webhook", "headers": {"Authorization": "Bearer token"} } ) # Poll for events events = client.monitor.events(monitor.monitor_id) for event in events.events: print(f"Change detected: {event.change_summary}") ``` -------------------------------- ### Catch NotFoundError Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/errors.md Example of how to catch and handle a NotFoundError, printing the status code from the error response. ```python from parallel import NotFoundError try: task = client.task_run.retrieve("nonexistent_run_id") except NotFoundError as e: print(f"Task not found: {e.response.status_code}") ``` -------------------------------- ### client.monitor.list Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/api.md Lists all monitors with optional filtering and pagination. This method corresponds to the GET /v1/monitors endpoint. ```APIDOC ## GET /v1/monitors ### Description Lists all monitors with optional filtering and pagination. ### Method GET ### Endpoint /v1/monitors ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for listing monitors, detailed in `src/parallel/types/monitor_list_params.py`. ### Response #### Success Response (200) - **PaginatedMonitorResponse** (object) - A paginated response containing a list of monitors, detailed in `src/parallel/types/paginated_monitor_response.py`. ``` -------------------------------- ### client.monitor.retrieve Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/api.md Retrieves a specific monitor by its ID. This method corresponds to the GET /v1/monitors/{monitor_id} endpoint. ```APIDOC ## GET /v1/monitors/{monitor_id} ### Description Retrieves a specific monitor by its ID. ### Method GET ### Endpoint /v1/monitors/{monitor_id} ### Parameters #### Path Parameters - **monitor_id** (string) - Required - The unique identifier of the monitor to retrieve. ### Response #### Success Response (200) - **Monitor** (object) - The retrieved monitor object, detailed in `src/parallel/types/monitor.py`. ``` -------------------------------- ### Catch UnprocessableEntityError Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/errors.md Example of how to catch and handle an UnprocessableEntityError, printing the error message related to invalid data. ```python from parallel import UnprocessableEntityError try: monitor = client.monitor.create( type="event_stream", frequency="invalid_format", # Should be "1h", "7d", etc. settings={"search_query": "..."}, ) except UnprocessableEntityError as e: print(f"Invalid data: {e.message}") ``` -------------------------------- ### Build Distribution Package Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/CONTRIBUTING.md Build a distributable version of the library, creating .tar.gz and .whl files in the dist/ directory. ```sh rye build ``` ```sh python -m build ``` -------------------------------- ### Catch PermissionDeniedError Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/errors.md Example of how to catch and handle a PermissionDeniedError, informing the user that the feature may not be available in their plan. ```python from parallel import PermissionDeniedError try: task = client.task_run.create( input="...", processor="pro", # May not be available on free tier ) except PermissionDeniedError as e: print("Feature not available in your plan.") ``` -------------------------------- ### Initialize Asynchronous AsyncParallel Client Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/configuration.md Instantiate the asynchronous AsyncParallel client using an async context manager. It accepts the same configuration options as the synchronous client. ```python from parallel import AsyncParallel import asyncio async def main(): async with AsyncParallel( api_key="your-api-key", # Same options as Parallel ) as client: # Use client pass asyncio.run(main()) ``` -------------------------------- ### client.beta.findall.retrieve Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/src/parallel/resources/beta/api.md Retrieves a specific FindAll run by its ID. This allows you to get the status and details of an existing run. ```APIDOC ## GET /v1beta/findall/runs/{findall_id} ### Description Retrieves a specific FindAll run by its ID. This allows you to get the status and details of an existing run. ### Method GET ### Endpoint /v1beta/findall/runs/{findall_id} ### Parameters #### Path Parameters - **findall_id** (string) - Required - The unique identifier of the FindAll run. ### Response #### Success Response (200) - **FindAllRun** (object) - The details of the requested FindAll run. ``` -------------------------------- ### Create and Retrieve Async FindAll Run Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/beta-findall.md Demonstrates how to initiate an asynchronous find all operation and then retrieve its results using the AsyncParallel client. Ensure you have your API key configured. ```python import asyncio from parallel import AsyncParallel async def main(): async with AsyncParallel(api_key="your-api-key") as client: run = await client.beta.findall.create( objective="...", entity_type="company", generator="base", match_conditions=[...], match_limit=50, ) result = await client.beta.findall.result(run.findall_id) print(result) asyncio.run(main()) ``` -------------------------------- ### Catch BadRequestError Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/errors.md Example of how to catch and handle a BadRequestError, printing the error message, status code, and response body. ```python from parallel import BadRequestError try: task = client.task_run.create( input="...", processor="invalid_processor", ) except BadRequestError as e: print(f"Bad request: {e.message}") print(f"Status: {e.status_code}") print(f"Response body: {e.body}") ``` -------------------------------- ### Create Task Run with Nested Parameters Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/README.md Demonstrates creating a task run with nested input parameters. Ensure the `parallel` library is imported. ```python from parallel import Parallel client = Parallel() task_run = client.task_run.create( input="What was the GDP of France in 2023?", processor="base", advanced_settings={}, ) print(task_run.advanced_settings) ``` -------------------------------- ### Bootstrap Development Environment with Rye Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/CONTRIBUTING.md Run this script to automatically provision a Python environment with the expected Python version using Rye. ```sh ./scripts/bootstrap ``` -------------------------------- ### Get Monitor Events Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/api.md Retrieves events for a specific monitor by its ID. Optional parameters can be passed as keyword arguments. ```python client.monitor.events(monitor_id, **params) ``` -------------------------------- ### copy / with_options Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/client.md Create a new client instance with modified options, such as API key, base URL, or timeout. ```APIDOC ## copy / with_options ### Description Create a new client instance with modified options. This method is also aliased as `with_options` for convenient inline usage. ### Method Signature ```python def copy( self, *, api_key: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, http_client: httpx.Client | None = None, max_retries: int | NotGiven = not_given, default_headers: Mapping[str, str] | None = None, set_default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, set_default_query: Mapping[str, object] | None = None, _extra_kwargs: Mapping[str, Any] = {}, ) -> Parallel ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **api_key** (str | None) - Optional - Override API key. - **base_url** (str | httpx.URL | None) - Optional - Override base URL. - **timeout** (float | Timeout | None | NotGiven) - Optional - Override timeout. Defaults to `not_given`. - **http_client** (httpx.Client | None) - Optional - Override HTTP client. - **max_retries** (int | NotGiven) - Optional - Override max retries. Defaults to `not_given`. - **default_headers** (Mapping[str, str] | None) - Optional - Merge with existing headers. - **set_default_headers** (Mapping[str, str] | None) - Optional - Replace all headers (mutually exclusive with `default_headers`). - **default_query** (Mapping[str, object] | None) - Optional - Merge with existing query parameters. - **set_default_query** (Mapping[str, object] | None) - Optional - Replace all query parameters (mutually exclusive with `default_query`). ### Returns New `Parallel` client instance with specified options merged or replaced. ### Example ```python # Override timeout for specific request client.with_options(timeout=5.0).task_run.create( input="What is Python?", processor="base", ) # Create specialized client with custom headers admin_client = client.copy( default_headers={"X-Admin-Key": "admin-secret"} ) ``` ``` -------------------------------- ### Configure Parallel Python SDK Client Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Initialize the Parallel client with API key, base URL, timeout, retries, and custom headers/query parameters. ```python from parallel import Parallel client = Parallel( api_key="your-api-key", # From PARALLEL_API_KEY env var base_url="https://api.parallel.ai", # From PARALLEL_BASE_URL env var timeout=60.0, # Request timeout in seconds max_retries=2, # Automatic retries for transient errors default_headers={"X-Custom": "..."}, default_query={"version": "v1"}, ) ``` -------------------------------- ### Get Runs from Task Group Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/task-group.md Retrieves a list of individual runs associated with a task group, with optional limit for pagination. ```APIDOC ## get_runs ### Description Retrieves runs from a task group. ### Method `get_runs` ### Parameters #### Path Parameters None #### Query Parameters - **limit** (int) - Optional - The maximum number of runs to return. ``` -------------------------------- ### Synchronous Client Initialization Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/configuration.md Initialize the synchronous Parallel client with various configuration options. The API key is required, and other parameters like base_url, timeout, max_retries, default_headers, default_query, and http_client can be customized. ```APIDOC ## Parallel (Synchronous Client) ```python from parallel import Parallel client = Parallel( api_key="your-api-key", # Required or from PARALLEL_API_KEY env var base_url="https://api.parallel.ai", # Optional, from PARALLEL_BASE_URL env var timeout=60.0, # Seconds, default 60 max_retries=2, # Number of retries for transient errors default_headers={"X-Custom-Header": "value"}, # Optional headers default_query={"param": "value"}, # Optional query params http_client=None, # Optional custom httpx.Client ) ``` ``` -------------------------------- ### Retrieve a Monitor Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/monitor.md Retrieves a specific monitor by its unique ID. This is useful for getting the current configuration and status of a single monitor. ```APIDOC ## GET /v1/monitors/{monitor_id} ### Description Retrieve a monitor by its ID. ### Method GET ### Endpoint /v1/monitors/{monitor_id} ### Parameters #### Path Parameters - **monitor_id** (str) - Required - The ID of the monitor to retrieve. #### Query Parameters - **extra_headers** (Headers | None) - Optional - Additional HTTP headers. - **extra_query** (Query | None) - Optional - Additional query parameters. - **extra_body** (Body | None) - Optional - Additional request body fields. - **timeout** (float | httpx.Timeout | None | NotGiven) - Optional - Override client-level timeout for this request. ### Response #### Success Response (200) - **Monitor** (object) - Monitor object with full configuration and status. ### Response Example { "example": "{\"type\": \"event_stream\", \"frequency\": \"1h\"}" } ### Error Handling - **NotFoundError**: If monitor_id does not exist. ``` -------------------------------- ### Create and Manage a Task Group Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Shows how to create a task group for batch execution, add multiple tasks, monitor group progress, retrieve individual runs, and stream events. Ideal for processing multiple queries efficiently. ```python # Create a group group = client.task_group.create( metadata={"project": "research_batch"} ) # Add tasks to group response = client.task_group.add_runs( task_group_id=group.task_group_id, inputs=[ "Query 1", "Query 2", "Query 3", ] ) # Monitor progress group = client.task_group.retrieve(group.task_group_id) print(f"Progress: {group.completed_runs}/{group.total_runs}") # Get individual runs runs = client.task_group.get_runs(group.task_group_id) # Stream events with client.task_group.with_streaming_response.events( task_group_id=group.task_group_id ) as response: for line in response.iter_lines(): print(line) ``` -------------------------------- ### Retrieve Task Run Result Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/task-run.md Get the final output and metadata for a completed task run. Ensure the task has finished before calling this. ```python result = client.task_run.result("run_abc123") print(result.output) # The extracted/searched data print(result.run.status) # Should be 'completed' ``` -------------------------------- ### Create and Poll Event Stream Monitor (Async) Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/monitor.md Demonstrates how to create an asynchronous event stream monitor and retrieve events. Requires an active AsyncParallel client instance. ```python import asyncio from parallel import AsyncParallel async def main(): async with AsyncParallel(api_key="your-api-key") as client: monitor = await client.monitor.create( type="event_stream", frequency="1d", settings={\"search_query\": \"Python\"}, ) events = await client.monitor.events(monitor.monitor_id) for event in events.events: print(event) asyncio.run(main()) ``` -------------------------------- ### client.monitor.events Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/api.md Retrieves events for a specific monitor by its ID, with optional filtering. This method corresponds to the GET /v1/monitors/{monitor_id}/events endpoint. ```APIDOC ## GET /v1/monitors/{monitor_id}/events ### Description Retrieves events for a specific monitor. ### Method GET ### Endpoint /v1/monitors/{monitor_id}/events ### Parameters #### Path Parameters - **monitor_id** (string) - Required - The unique identifier of the monitor whose events are to be retrieved. #### Query Parameters - **params** (object) - Optional - Parameters for filtering events, detailed in `src/parallel/types/monitor_events_params.py`. ### Response #### Success Response (200) - **PaginatedMonitorEvents** (object) - A paginated response containing a list of monitor events, detailed in `src/parallel/types/paginated_monitor_events.py`. ``` -------------------------------- ### Synchronous Task Creation and Execution Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/README.md Demonstrates synchronous usage of the Parallel SDK to create a task, wait for its result, and print the output. Requires API key for initialization. ```python from parallel import Parallel client = Parallel(api_key="your-api-key") # Create a task task = client.task_run.create( input="What is Python?", processor="base", ) # Wait for completion result = client.task_run.wait_for_result(task.run_id) print(result.output) ``` -------------------------------- ### Create Monitor Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/api.md Creates a new monitor using the client.monitor.create method. Pass parameters as keyword arguments. ```python client.monitor.create(**params) ``` -------------------------------- ### Get Runs from Task Group Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/task-group.md Retrieves a paginated list of task runs belonging to a specific task group. Use `limit` and `offset` for pagination. ```python response = client.task_group.get_runs( task_group_id="group_xyz789", limit=50, offset=0, ) for run in response.runs: print(f"{run.run_id}: {run.status}") ``` -------------------------------- ### Asynchronous Client Initialization Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/configuration.md Initialize the asynchronous Parallel client using an async context manager. It accepts the same configuration options as the synchronous client. ```APIDOC ## AsyncParallel (Asynchronous Client) ```python from parallel import AsyncParallel import asyncio async def main(): async with AsyncParallel( api_key="your-api-key", # Same options as Parallel ) as client: # Use client pass asyncio.run(main()) ``` ``` -------------------------------- ### TaskRun Create Method Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/api.md Creates a new task run using the provided parameters. This is the entry point for initiating a task. ```python client.task_run.create(**params) -> TaskRun ``` -------------------------------- ### Execute Web Search Query Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/client.md Execute a search query against web sources to retrieve structured results. The 'query' parameter is mandatory. An optional 'objective' can guide the search. ```python def search( self, *, query: str, advanced_settings: Optional[AdvancedSearchSettingsParam] | Omit = omit, objective: Optional[str] | Omit = omit, session_id: Optional[str] | Omit = omit, extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> SearchResult ``` ```python results = client.search( query="What are the latest trends in AI?", ) print(results) ``` -------------------------------- ### Retrieve FindAll Run Result Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/beta-findall.md Use this method to get the final results of a FindAll run, including matched entities and evaluation details. Requires the ID of the FindAll run. ```python result = client.beta.findall.result("findall_abc123") for candidate in result.candidates: print(f"Entity: {candidate.name}") print(f"Match score: {candidate.match_score}") print(f"Reasoning: {candidate.reasoning}") ``` -------------------------------- ### Access Raw Response Data Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/README.md Prefix HTTP method calls with `.with_raw_response.` to access the raw `APIResponse` object, including headers. Use `.parse()` to get the deserialized object. ```python from parallel import Parallel client = Parallel() response = client.task_run.with_raw_response.create( input="What was the GDP of France in 2023?", processor="base", ) print(response.headers.get('X-My-Header')) task_run = response.parse() # get the object that `task_run.create()` would have returned print(task_run.interaction_id) ``` -------------------------------- ### Configure DefaultAsyncHttpxClient Source: https://github.com/parallel-web/parallel-sdk-python/blob/main/_autodocs/configuration.md Use DefaultAsyncHttpxClient for a pre-configured async httpx.AsyncClient factory. It supports proxy configuration. ```python from parallel import DefaultAsyncHttpxClient async_client = DefaultAsyncHttpxClient( proxy="http://proxy.example.com:8080", ) ```