### Install Dependencies and Run Tests Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/README.md Install development dependencies using either `uv` or `pip`, then execute the test suite. This is for manual testing setups. ```bash uv sync --dev ``` ```bash pip install -e ".[dev]" ``` ```bash pytest tests/ -v ``` -------------------------------- ### Start mock server manually Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/mockserver/README.md Starts the server using either the Go toolchain or Docker. ```shell go run . ``` ```shell docker build -t mockserver . docker run -i -p 18080:18080 -t --rm mockserver ``` -------------------------------- ### Install SDK with uv Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Install the package using the uv package manager. ```bash uv add youdotcom ``` -------------------------------- ### Install SDK with Poetry Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Install the package using the Poetry dependency manager. ```bash poetry add youdotcom ``` -------------------------------- ### Start Mock Server Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/README.md Manually start the mock server for testing purposes. Ensure you are in the `tests/mockserver` directory before running. ```bash cd tests/mockserver go run . ``` -------------------------------- ### Install SDK with PIP Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Install the package using the standard pip package manager. ```bash pip install youdotcom ``` -------------------------------- ### Install You.com SDK Source: https://context7.com/youdotcom-oss/youdotcom-python-sdk/llms.txt Commands to install the SDK using common Python package managers. ```bash # Using pip pip install youdotcom # Using uv (recommended for speed) uv add youdotcom # Using poetry poetry add youdotcom ``` -------------------------------- ### Initialize SDK Client Source: https://context7.com/youdotcom-oss/youdotcom-python-sdk/llms.txt Examples for basic and advanced client initialization, including custom retry configurations and timeouts. ```python import os from youdotcom import You # Basic initialization with API key from environment with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: # Use the SDK here pass # Advanced initialization with custom configuration from youdotcom.utils import BackoffStrategy, RetryConfig with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), server_url="https://api.you.com", # Optional: override default server retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), timeout_ms=60000, # 60 second timeout ) as you: # Use the SDK with custom configuration pass ``` -------------------------------- ### Start Mock Server for Testing Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Run this command to start the local mock server. This is essential for troubleshooting connection errors and for running tests in an isolated environment. ```bash cd tests/mockserver go run main.go ``` -------------------------------- ### Example Test Case with SDK Call Measurement Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md This Python example demonstrates how to add a new test case using the `measure_sdk_call` helper. It includes setting up the HTTP client, creating a You.com client instance, defining the call to be measured, and recording the metrics. ```python def test_search_with_new_filter(self, server_url, api_key, iterations, show_detailed): """Test description.""" client = create_test_http_client("get_/v1/search") with You(server_url=server_url, client=client, api_key_auth=api_key) as you: def call(): you.search.unified(query="test", new_filter="value") metrics = measure_sdk_call(call, client, iterations, "Search: new filter") ALL_METRICS.append(metrics) if show_detailed: print_detailed_metrics(metrics) ``` -------------------------------- ### Initialize ResponseStarting model Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/data.md Represents the starting response state. ```python value: models.ResponseStarting = /* values here */ ``` -------------------------------- ### Check Python Version and Install SDK Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/MIGRATION.md Ensure your Python version is 3.10 or later before installing or upgrading the You.com Python SDK. ```bash python --version # must be 3.10 or later pip install "youdotcom>=2.3.0" ``` -------------------------------- ### CI/CD Performance Test Setup Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Integrate this command into your CI pipeline for automated performance testing. It uses a mock server, specifies iterations, and sets the output format to CSV. ```bash # Add to your CI pipeline PERF_TEST_TARGET=mock \ PERF_TEST_ITERATIONS=10 \ PERF_OUTPUT_FORMAT=csv \ pytest tests/test_performance.py -v --tb=short ``` -------------------------------- ### Test Against Custom Server Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Configure and run performance tests against a custom server by setting the TEST_SERVER_URL environment variable. This example also specifies the mock target, which might be used for specific testing configurations. ```bash # Test against custom server TEST_SERVER_URL=http://localhost:8080 \ PERF_TEST_TARGET=mock \ pytest tests/test_performance.py -v ``` -------------------------------- ### Synchronous Research Operation with API Key Authentication Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md This example demonstrates a synchronous research query using the SDK. Authentication is handled via the YOU_API_KEY_AUTH environment variable. ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.research(input="Which global cities improved air quality the most over the past 10 years, and what measurable actions contributed?", research_effort=models.ResearchEffort.LITE) # Handle response print(res) ``` -------------------------------- ### Fields Overview Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/agentrunsresponseoutput.md This section details the various fields available in the YouDotCom Python SDK, their data types, whether they are required, and provides a brief description and example for each. ```APIDOC ## Fields Overview This section details the various fields available in the YouDotCom Python SDK, their data types, whether they are required, and provides a brief description and example for each. ### Fields Table | Field | Type | Required | Description | Example | |---|---|---|---|---| | [Field Name] | [Data Type] | [Required/Optional] | [Description of the field's purpose and usage] | [Example value for the field] | *Note: Replace `[Field Name]`, `[Data Type]`, `[Required/Optional]`, `[Description of the field's purpose and usage]`, and `[Example value for the field]` with the actual details from the SDK documentation.* ``` -------------------------------- ### Enable Detailed Performance Metrics Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Run performance tests with detailed metrics enabled to get a breakdown per test case. This requires setting the PERF_DETAILED environment variable. ```bash PERF_DETAILED=true pytest tests/test_performance.py::TestSearchPerformance::test_search_basic -v ``` -------------------------------- ### Perform Unified Search with You.com Python SDK Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/search/README.md Use this snippet to get unified search results from web and news sources. Ensure your YOU_API_KEY_AUTH environment variable is set. ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.search.unified(query="Your query", count=10, language=models.Language.EN) # Handle response print(res) ``` -------------------------------- ### GET /v1/search Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/search/README.md Returns a list of unified search results from web and news sources, optimized for LLM consumption. ```APIDOC ## GET /v1/search ### Description This endpoint returns LLM-ready web results based on a user's query. It uses a classification mechanism to return relevant web results and news. ### Method GET ### Endpoint /v1/search ### Parameters #### Query Parameters - **query** (string) - Required - The search query string. - **count** (integer) - Optional - The number of results to return. - **language** (enum) - Optional - The language of the results (e.g., models.Language.EN). ### Request Example ```python res = you.search.unified(query="Your query", count=10, language=models.Language.EN) ``` ### Response #### Success Response (200) - **res** (object) - A collection of unified search results. ``` -------------------------------- ### Supported Data Types Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/loc.md The YouDotCom Python SDK supports basic data types like strings and integers. Below are examples of how to declare and use them. ```APIDOC ## Supported Types ### `str` This section describes the usage of string types. #### Code Example ```python value: str = /* values here */ ``` ### `int` This section describes the usage of integer types. #### Code Example ```python value: int = /* values here */ ``` ``` -------------------------------- ### Run SDK with uvx Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Execute the SDK in a Python shell using uvx. ```shell uvx --from youdotcom python ``` -------------------------------- ### Run Live API Tests Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/README.md Execute live tests against the actual You.com API by providing your API key. This requires setting the `YOU_API_KEY_AUTH` environment variable. ```bash YOU_API_KEY_AUTH="your-api-key" pytest tests/test_live.py -v ``` -------------------------------- ### Configure server logging level Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/mockserver/README.md Enables debug logging for the mock server during startup. ```shell # via `go run` go run . -log-level=DEBUG # via `docker run` docker run -i -p 18080:18080 -t --rm mockserver -log-level=DEBUG ``` -------------------------------- ### Run All Performance Tests Against Mock Server Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Execute all performance tests using the mock server for fast and consistent results. Increase iterations for better statistics. ```bash pytest tests/test_performance.py -v ``` ```bash PERF_TEST_ITERATIONS=20 pytest tests/test_performance.py -v ``` -------------------------------- ### Initialize ResponseOutputItemDone model Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/data.md Represents a response indicating an output item is complete. ```python value: models.ResponseOutputItemDone = /* values here */ ``` -------------------------------- ### Handle YouError Exceptions Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Catch and process YouError exceptions, which are the base class for all HTTP error responses from the SDK. This example shows how to access common error properties and check for specific error types. ```python import os from youdotcom import You, errors, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = None try: res = you.research(input="Which global cities improved air quality the most over the past 10 years, and what measurable actions contributed?", research_effort=models.ResearchEffort.LITE) # Handle response print(res) except errors.YouError as e: # The base class for HTTP error responses print(e.message) print(e.status_code) print(e.body) print(e.headers) print(e.raw_response) # Depending on the method different errors may be thrown if isinstance(e, errors.ResearchUnauthorizedError): print(e.data.detail) # Optional[str] ``` -------------------------------- ### Initialize ResponseOutputContentFull model Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/data.md Represents a response containing full output content. ```python value: models.ResponseOutputContentFull = /* values here */ ``` -------------------------------- ### Initialize ResponseDone model Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/data.md Represents the final completion response. ```python value: models.ResponseDone = /* values here */ ``` -------------------------------- ### Configure Retries for a Single API Call Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Override the default retry strategy for a specific API call by providing a RetryConfig object. This example demonstrates setting a custom backoff strategy for the research operation. ```python import os from youdotcom import You, models from youdotcom.utils import BackoffStrategy, RetryConfig with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.research( input="Which global cities improved air quality the most over the past 10 years, and what measurable actions contributed?", research_effort=models.ResearchEffort.LITE, retries=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), ) # Handle response print(res) ``` -------------------------------- ### Configure Custom Async Client Source: https://context7.com/youdotcom-oss/youdotcom-python-sdk/llms.txt Use this pattern to inject custom headers or timeout settings into the You.com SDK's asynchronous client. ```python async_client = httpx.AsyncClient( headers={"x-custom-header": "someValue"}, timeout=30.0, ) you_async = You( api_key_auth="your-api-key", async_client=async_client, ) ``` -------------------------------- ### Run Quick Performance Check (Development) Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Use this command for a fast check during development. It runs a single iteration of a specific performance test. ```bash # Quick check during development (fast, 1 iteration) PERF_TEST_ITERATIONS=1 pytest tests/test_performance.py -k "search_basic" -v ``` -------------------------------- ### Run Performance Tests Against Custom Server Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Execute performance tests against a custom server. Requires setting the target, server URL, API key, and desired number of iterations. ```bash PERF_TEST_TARGET=custom \ PERF_TEST_SERVER_URL=https://api.example.com \ PERF_TEST_API_KEY=your_api_key_here \ PERF_TEST_ITERATIONS=10 \ pytest tests/test_performance.py -v ``` -------------------------------- ### Configure Custom HTTP Client Headers Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Pass a pre-configured httpx.Client instance to the SDK to apply custom headers to all requests. ```python from youdotcom import You import httpx http_client = httpx.Client(headers={"x-custom-header": "someValue"}) s = You(client=http_client) ``` -------------------------------- ### Initialize ResponseOutputTextDelta model Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/data.md Represents a delta update for text output. ```python value: models.ResponseOutputTextDelta = /* values here */ ``` -------------------------------- ### Run Custom Agent (Streaming) Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/runs/README.md Execute queries using a user-configured Custom agent in streaming mode. Requires the agent's unique ID. Ensure the YOU_API_KEY_AUTH environment variable is set. ```python import os from youdotcom import You with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.agents.runs.create(request={ "agent": "63773261-b4de-4d8f-9dfd-cff206a5cb51", "input": "Tell me about the history of Paris", "stream": True, }) with res as event_stream: for event in event_stream: # handle event print(event, flush=True) ``` -------------------------------- ### SDK Configuration and Error Handling Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/search/README.md Details regarding the optional server URL configuration and the standard error responses returned by the SDK. ```APIDOC ## SDK Configuration ### Parameters - **server_url** (str) - Optional - An optional server URL to use (e.g., http://localhost:8080). ### Response - **models.SearchResponse** - The standard response model for search operations. ### Errors | Error Type | Status Code | Content Type | | --- | --- | --- | | errors.SearchUnauthorizedError | 401 | application/json | | errors.SearchForbiddenError | 403 | application/json | | errors.SearchInternalServerError | 500 | application/json | | errors.YouDefaultError | 4XX, 5XX | */* | ``` -------------------------------- ### Run Express Agent (Streaming) Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/runs/README.md Execute queries with an Express agent in streaming mode. This is suitable for faster responses and can include web search tools. Ensure the YOU_API_KEY_AUTH environment variable is set. ```python import os from youdotcom import You with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.agents.runs.create(request={ "agent": "express", "input": "Analyze the economic impact of renewable energy adoption", "stream": True, "tools": [ { "type": "web_search", }, ], }) with res as event_stream: for event in event_stream: # handle event print(event, flush=True) ``` -------------------------------- ### ResponseStarting Event Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/responsestarting.md Details regarding the ResponseStarting SSE event structure. ```APIDOC ## ResponseStarting Event ### Description SSE event signifying the response is starting. ### Fields - **seq_id** (int) - Required - N/A - **type** (Literal["response.starting"]) - Required - N/A ### Response Example { "seq_id": 1, "type": "response.starting" } ``` -------------------------------- ### ComputeTool Configuration Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/computetool.md Details the mandatory fields required to initialize the ComputeTool agent. ```APIDOC ## ComputeTool Configuration ### Description Defines the mandatory configuration required to utilize the compute agent functionality. ### Parameters #### Request Body - **type** (Literal["compute"]) - Required - Setting this value to "compute" is mandatory to use the compute agent. ``` -------------------------------- ### Run Custom Agent (Batch) Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/runs/README.md Execute queries using a user-configured Custom agent in batch mode. Requires the agent's unique ID. Ensure the YOU_API_KEY_AUTH environment variable is set. ```python import os from youdotcom import You with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.agents.runs.create(request={ "agent": "63773261-b4de-4d8f-9dfd-cff206a5cb51", "input": "What is the capital of France?", "stream": False, }) with res as event_stream: for event in event_stream: # handle event print(event, flush=True) ``` -------------------------------- ### Configure Custom HTTP Client Source: https://context7.com/youdotcom-oss/youdotcom-python-sdk/llms.txt Inject a custom httpx client to manage advanced network requirements like custom headers, timeouts, or proxies. ```python from youdotcom import You import httpx # Custom sync client with headers http_client = httpx.Client( headers={"x-custom-header": "someValue"}, timeout=30.0, ) you = You( api_key_auth="your-api-key", client=http_client, ) ``` -------------------------------- ### Server URL Configuration Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Learn how to override the default server URL globally during client initialization or on a per-operation basis. ```APIDOC ## Server Selection ### Global Override Pass the `server_url` parameter when initializing the `You` client. ```python with You(server_url="https://api.you.com", api_key_auth="...") as you: # ... ``` ### Per-Operation Override Pass the `server_url` parameter directly to the specific method call. ```python res = you.search.unified(query="...", server_url="https://ydc-index.io") ``` ``` -------------------------------- ### Run Express Agent (Batch) Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/runs/README.md Execute queries with an Express agent in batch mode. This is suitable for straightforward requests where immediate full responses are needed. Ensure the YOU_API_KEY_AUTH environment variable is set. ```python import os from youdotcom import You with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.agents.runs.create(request={ "agent": "express", "input": "What is the capital of France?", "stream": False, }) with res as event_stream: for event in event_stream: # handle event print(event, flush=True) ``` -------------------------------- ### Initialize ResponseOutputItemAdded model Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/data.md Represents a response indicating an output item has been added. ```python value: models.ResponseOutputItemAdded = /* values here */ ``` -------------------------------- ### SDK Configuration Parameters Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/search/README.md Details regarding the optional configuration parameters for livecrawl formats and retry logic within the SDK. ```APIDOC ## SDK Configuration Parameters ### Description This section outlines the optional configuration parameters available for customizing the behavior of the You.com Python SDK. ### Parameters - **livecrawl_formats** (Optional[models.SearchLivecrawlFormats]) - Optional - Indicates the format of the livecrawled content. - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ``` -------------------------------- ### Create standalone script with uv Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Define a standalone Python script with embedded dependencies using uv. ```python #!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.10" # dependencies = [ # "youdotcom", # ] # /// from youdotcom import You sdk = You( # SDK arguments ) # Rest of script here... ``` -------------------------------- ### Run All Tests with Cleanup Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/README.md Execute the automated test script and clean up the virtual environment afterward. This ensures a fresh environment for the next test run. ```bash ./scripts/run_tests.sh --cleanup ``` ```bash ./scripts/run_tests.sh -c ``` -------------------------------- ### Set API Key for Custom Server Tests Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Export your actual API key as an environment variable before running performance tests against a custom server to resolve authentication errors. ```bash export PERF_TEST_API_KEY=your_actual_api_key pytest tests/test_performance.py -v ``` -------------------------------- ### Run tests via script Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/mockserver/README.md Executes the automated test suite from the project root. ```shell ./scripts/run_tests.sh ``` -------------------------------- ### Handle streaming responses in SDK 1.x Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/CHANGELOG.md Legacy approach using a helper function to process streaming responses. ```python res = you.agents.runs.create(agent=AgentType.EXPRESS, input="...", stream=True) stream_text_tokens(res) # Helper function handled everything ``` -------------------------------- ### Run Full Regression Performance Test Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Execute this command for a comprehensive regression test before a release. It runs multiple iterations for statistical significance. ```bash # Full regression test before release (comprehensive) PERF_TEST_ITERATIONS=20 pytest tests/test_performance.py -v ``` -------------------------------- ### Agent Configuration Parameters Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/advancedagentrunsrequest.md Details regarding the stream and tools parameters used to configure agent behavior. ```APIDOC ## Agent Configuration Parameters ### Description Configure the agent's response streaming behavior and available toolset. ### Parameters #### Request Body - **stream** (bool) - Optional - Must be set to true to stream the agent response, or false to return the full response after completion. - **tools** (List[models.Tool]) - Optional - The advanced agent accepts either 'compute' or 'research' tools. 'compute' enables a Python code interpreter for data analysis and math. 'research' enables iterative web searching and reporting. ``` -------------------------------- ### Initialize ResponseCreated model Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/data.md Represents the initial creation response from the API. ```python value: models.ResponseCreated = /* values here */ ``` -------------------------------- ### Run All Tests Except Live Tests Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/README.md Execute all tests in the suite while explicitly skipping the live API tests. This is useful for running tests in environments without an API key. ```bash pytest tests/ --ignore=tests/test_live.py -v ``` -------------------------------- ### Generate Webpage Content (HTML/Markdown) Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/contentssdk/README.md Use this snippet to fetch the HTML or Markdown content of specified URLs. Ensure your API key is set in the environment variable YOU_API_KEY_AUTH. The crawl timeout can be adjusted. ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.contents.generate(urls=[ "https://www.you.com", ], formats=[ models.ContentsFormats.HTML, models.ContentsFormats.MARKDOWN, ], crawl_timeout=10) # Handle response print(res) ``` ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.contents.generate(urls=[ "https://www.you.com", ], formats=[ models.ContentsFormats.HTML, models.ContentsFormats.MARKDOWN, ], crawl_timeout=10) # Handle response print(res) ``` ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.contents.generate(urls=[ "https://www.you.com", ], formats=[ models.ContentsFormats.HTML, models.ContentsFormats.MARKDOWN, ], crawl_timeout=10) # Handle response print(res) ``` ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.contents.generate(urls=[ "https://www.you.com", ], formats=[ models.ContentsFormats.HTML, models.ContentsFormats.MARKDOWN, ], crawl_timeout=10) # Handle response print(res) ``` ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.contents.generate(urls=[ "https://www.you.com", ], formats=[ models.ContentsFormats.HTML, models.ContentsFormats.MARKDOWN, ], crawl_timeout=10) # Handle response print(res) ``` ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.contents.generate(urls=[ "https://www.you.com", ], formats=[ models.ContentsFormats.HTML, models.ContentsFormats.MARKDOWN, ], crawl_timeout=10) # Handle response print(res) ``` -------------------------------- ### Run Individual Performance Test Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Execute a single, specific performance test case by providing its full path. ```bash pytest tests/test_performance.py::TestSearchPerformance::test_search_with_livecrawl_markdown -v ``` -------------------------------- ### Run Advanced Agent (Batch) Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/runs/README.md Execute complex queries with an Advanced agent using batch mode. Supports multi-turn reasoning and tool usage, including research tools with configurable search effort and report verbosity. Ensure the YOU_API_KEY_AUTH environment variable is set. ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.agents.runs.create(request={ "agent": "advanced", "input": "You are a biologist studying the impacts of microplastics. Explain what microplastics are to a group of engineers, explain the impacts of microplastics on the body, and what the common sources and dosages of microplastics are. Highlight what a safe dosage might be and how to achieve it", "stream": False, "tools": [ { "type": "research", "search_effort": models.SearchEffort.AUTO, "report_verbosity": models.ReportVerbosity.MEDIUM, }, ], }) with res as event_stream: for event in event_stream: # handle event print(event, flush=True) ``` -------------------------------- ### Run Advanced Agent (Streaming) Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/runs/README.md Execute complex queries with an Advanced agent in streaming mode. This allows for real-time processing of multi-turn reasoning and tool usage. Ensure the YOU_API_KEY_AUTH environment variable is set. ```python import os from youdotcom import You with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.agents.runs.create(request={ "agent": "advanced", "input": "Analyze the economic impact of renewable energy adoption", "stream": True, "tools": [ { "type": "web_search", }, ], }) with res as event_stream: for event in event_stream: # handle event print(event, flush=True) ``` -------------------------------- ### Initialize ResearchTool model Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/tool.md Assign a value to the ResearchTool model type. ```python value: models.ResearchTool = /* values here */ ``` -------------------------------- ### Perform research with You SDK Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/you/README.md Executes a research query using the You client. Requires an API key provided via the YOU_API_KEY_AUTH environment variable. ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.research(input="", research_effort=models.ResearchEffort.STANDARD) # Handle response print(res) ``` -------------------------------- ### Manage SDK Resources with Context Managers Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Use the context manager pattern to ensure HTTP connections are properly closed in long-lived applications. ```python import os from youdotcom import You def main(): with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: # Rest of application here... # Or when using async: async def amain(): async with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: # Rest of application here... ``` -------------------------------- ### POST /agents/runs Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/runs/README.md Executes an agent run request using the You.com Python SDK. ```APIDOC ## POST /agents/runs ### Description Executes an agent run request. ### Parameters #### Request Body - **request** (models.AgentsRunsRequest) - Required - The request object to use for the request. - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Response - **Response Type** (models.AgentsRunsResponse) - The response object returned upon success. ### Errors - **400** - errors.AgentRuns400ResponseError (application/json) - **401** - errors.AgentRuns401ResponseError (application/json) - **422** - errors.AgentRuns422ResponseError (application/json) - **4XX, 5XX** - errors.YouDefaultError (*/*) ``` -------------------------------- ### Fields Overview Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/researchrequest.md This section details the various fields available in the YouDotCom Python SDK, their data types, whether they are required, and a description of their purpose. ```APIDOC ## Fields Overview This section details the various fields available in the YouDotCom Python SDK, their data types, whether they are required, and a description of their purpose. ### Fields Table | Field | Type | Required | Description | |---|---|---|---| | [Field Name] | [Data Type] | [Required/Optional] | [Description of the field's purpose and usage] | **Note:** Replace `[Field Name]`, `[Data Type]`, `[Required/Optional]`, and `[Description of the field's purpose and usage]` with the actual details from the SDK documentation. ``` -------------------------------- ### Fields Overview Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/advancedagentrunsrequest.md This section details the various fields available for use within the YouDotCom Python SDK. Each field is described with its type, whether it is required, and a brief explanation of its purpose. ```APIDOC ## Fields Overview This section details the various fields available for use within the YouDotCom Python SDK. Each field is described with its type, whether it is required, and a brief explanation of its purpose. ### Fields Table | Field | Type | Required | Description | Example | |---|---|---|---|---| ``` -------------------------------- ### Search Parameters: Freshness and Offset Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/search/README.md Details on how to specify the freshness of search results and control pagination using the offset parameter. ```APIDOC ## Search Parameters ### Freshness - **freshness** (Optional[models.SearchFreshness]) - Specifies the freshness of the results to return. Provide either one of `day`, `week`, `month`, `year`, or a date range string in the format `YYYY-MM-DDtoYYYY-MM-DD`. When your search query includes a temporal keyword and you also set a freshness parameter, the search will use the broader (i.e., less restrictive) of the two timeframes. For example, if you use `query=news+this+week&freshness=month`, the results will use a freshness of month. ### Offset (Pagination) - **offset** (Optional[int]) - Indicates the `offset` for pagination. The `offset` is calculated in multiples of `count`. For example, if `count = 5` and `offset = 1`, results 5–10 will be returned. Range `0 ≤ offset ≤ 9`. ``` -------------------------------- ### Handle streaming responses in SDK 2.0 Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/CHANGELOG.md Modern approach using typed event classes and a context manager for granular control over streaming events. ```python from youdotcom.models import ( ResponseCreated, ResponseStarting, ResponseOutputTextDelta, ResponseOutputContentFull, ResponseDone, ) response = you.agents.runs.create( request=ExpressAgentRunsRequest(input="...", stream=True) ) with response as stream: for chunk in stream: event = chunk.data if isinstance(event, ResponseCreated): print(f"Started: {event.seq_id}") elif isinstance(event, ResponseOutputTextDelta): print(event.response.delta, end="", flush=True) elif isinstance(event, ResponseOutputContentFull): # Handle web search results, etc. for result in event.response.full: print(f"Source: {result.url}") elif isinstance(event, ResponseDone): print(f"\nCompleted in {event.response.run_time_ms}ms") ``` -------------------------------- ### API Key Authentication Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/security.md Information on how to use API keys for authentication. ```APIDOC ## API Key Authentication ### Description This section describes the fields related to API key authentication. ### Fields #### Request Body - **api_key_auth** (Optional[str]) - Optional - Used for API key authentication. ``` -------------------------------- ### Invoke Custom Agent by UUID Source: https://context7.com/youdotcom-oss/youdotcom-python-sdk/llms.txt Executes a pre-configured agent created in the You.com UI. Requires a valid agent UUID. ```python import os from youdotcom import You from youdotcom.models import CustomAgentRunsRequest with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: # Replace with your actual custom agent UUID custom_agent_id = "63773261-b4de-4d8f-9dfd-cff206a5cb51" request = CustomAgentRunsRequest( agent=custom_agent_id, input="What is the capital of France?", stream=False, ) try: results = you.agents.runs.create(request=request) print(results) except Exception as e: print(f"Error: {e}") print("Note: Make sure to use a valid custom agent ID") ``` -------------------------------- ### Perform Multi-Step Research Source: https://context7.com/youdotcom-oss/youdotcom-python-sdk/llms.txt Synchronous and asynchronous methods for executing complex research queries with configurable effort levels. ```python import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: # Perform research with configurable effort levels res = you.research( input="Which global cities improved air quality the most over the past 10 years, and what measurable actions contributed?", research_effort=models.ResearchEffort.DEEP, # Options: LITE, STANDARD, DEEP, EXHAUSTIVE ) # Access the research output print("Research Answer:") print(res.output.content) # Access cited sources if res.output.sources: print(f"\nSources ({len(res.output.sources)}):") for source in res.output.sources: print(f" - {source.title or 'Untitled'}: {source.url}") # Async version import asyncio async def async_research(): async with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = await you.research_async( input="What are the latest advances in quantum computing?", research_effort=models.ResearchEffort.STANDARD, ) print(res.output.content) asyncio.run(async_research()) ``` -------------------------------- ### Export Performance Results to CSV Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/tests/PERFORMANCE_TESTING.md Run performance tests and export the results in CSV format for further analysis. The output file will be named 'performance_results.csv'. ```bash PERF_OUTPUT_FORMAT=csv pytest tests/test_performance.py -v # Creates: performance_results.csv ``` -------------------------------- ### Enable SDK Debug Logging Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Inject a standard Python logger into the SDK to capture request and response details. ```python from youdotcom import You import logging logging.basicConfig(level=logging.DEBUG) s = You(debug_logger=logging.getLogger("youdotcom")) ``` -------------------------------- ### Perform Research with the Research API Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/CHANGELOG.md Use the research method to synthesize multi-step, cited answers. Requires the You client and ResearchEffort configuration. ```python from youdotcom import You from youdotcom.models import ResearchEffort you = You() res = you.research( input="What are the latest advances in quantum computing?", research_effort=ResearchEffort.DEEP, ) print(res.output.content) for source in res.output.sources: print(f" - {source.title or 'Untitled'}: {source.url}") ``` -------------------------------- ### POST /v1/agents/runs Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/sdks/runs/README.md Execute queries using You.com's AI agents. This endpoint supports three agent types: Express, Advanced, and Custom. The response format depends on the `stream` parameter, providing either a complete JSON payload or Server-Sent Events (SSE). ```APIDOC ## POST /v1/agents/runs ### Description Execute queries using You.com's AI agents. This endpoint supports three agent types: Express, Advanced, and Custom. The response format depends on the `stream` parameter, providing either a complete JSON payload or Server-Sent Events (SSE). ### Method POST ### Endpoint /v1/agents/runs ### Parameters #### Request Body - **agent** (string) - Required - The type of agent to use. Can be 'express', 'advanced', or a custom agent ID. - **input** (string) - Required - The query or prompt to send to the agent. - **stream** (boolean) - Optional - If true, the response will be streamed using Server-Sent Events (SSE). If false, a complete JSON payload is returned. - **tools** (array) - Optional - A list of tools to be used by the agent. Each tool object should have a `type` field (e.g., 'research', 'web_search') and can include additional parameters like `search_effort` or `report_verbosity`. ### Request Example ```json { "agent": "advanced", "input": "Explain the impacts of microplastics on the body.", "stream": false, "tools": [ { "type": "research", "search_effort": "auto", "report_verbosity": "medium" } ] } ``` ### Response #### Success Response (200) - **response** (object or string) - The agent's response. If `stream` is false, this will be a JSON object. If `stream` is true, this will be a stream of Server-Sent Events. #### Response Example ```json { "output": "Microplastics are tiny plastic particles that can have various impacts on the human body..." } ``` ``` -------------------------------- ### Data Models Overview Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/data.md A collection of response models representing different states and content types in the SDK data stream. ```APIDOC ## Data Models ### models.ResponseCreated Represents the initial creation state of a response. ### models.ResponseStarting Indicates the start of the response processing. ### models.ResponseOutputItemAdded Represents an item being added to the output stream. ### models.ResponseOutputContentFull Contains the full content of an output item. ### models.ResponseOutputItemDone Indicates that a specific output item has been completed. ### models.ResponseOutputTextDelta Represents a incremental text update (delta) in the output stream. ### models.ResponseDone Indicates the final completion of the response process. ``` -------------------------------- ### Input Types Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/input2.md This section describes the supported types for input values, which are crucial for various SDK operations. ```APIDOC ## Input Types This section details the supported data types for input values within the You.com Python SDK. ### Supported Types #### `str` This type represents string inputs. ```python value: str = /* values here */ ``` #### `models.ResearchInput` This type represents inputs using the `ResearchInput` model from the SDK's models module. ```python value: models.ResearchInput = /* values here */ ``` ``` -------------------------------- ### Consolidate Model Imports Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/CHANGELOG.md Update imports to use the new youdotcom.models namespace instead of typesafe_models. ```python from youdotcom.types.typesafe_models import ( AgentType, SearchEffort, Verbosity, Country, Freshness, LiveCrawl, Format, ) ``` ```python from youdotcom.models import ( ExpressAgentRunsRequest, AdvancedAgentRunsRequest, SearchEffort, ReportVerbosity, Country, Freshness, LiveCrawl, ContentsFormat, ) ``` -------------------------------- ### Agent Runs Request Models Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/agentsrunsrequest.md Definitions for the various request models used to initiate agent runs within the SDK. ```APIDOC ## Agent Runs Request Models ### Description These models define the parameters required to send a query to an agent. The SDK supports three distinct request types based on the agent configuration. ### Supported Models - **models.ExpressAgentRunsRequest**: Used for standard express agent interactions. - **models.AdvancedAgentRunsRequest**: Used for advanced agent configurations. - **models.CustomAgentRunsRequest**: Used for custom agent implementations. ### Usage Example ```python # Example instantiation for an Express Agent request value: models.ExpressAgentRunsRequest = /* values here */ ``` ``` -------------------------------- ### ExpressAgentRunsRequest Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/expressagentrunsrequest.md Documentation for the ExpressAgentRunsRequest endpoint. ```APIDOC ## ExpressAgentRunsRequest ### Description This endpoint is used to initiate or manage express agent runs within the You.com SDK. ### Endpoint /express-agent-runs ``` -------------------------------- ### SearchFreshness Configuration Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/searchfreshness.md Details on how to specify the freshness of search results using the models.Freshness type or a string date range. ```APIDOC ## SearchFreshness Parameter ### Description Specifies the freshness of the results to return. When a temporal keyword is present in the query alongside this parameter, the search uses the broader of the two timeframes. ### Supported Types - **models.Freshness**: Enum-like values ('day', 'week', 'month', 'year'). - **str**: Custom date range string in the format 'YYYY-MM-DDtoYYYY-MM-DD'. ``` -------------------------------- ### Initialize ComputeTool model Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/tool.md Assign a value to the ComputeTool model type. ```python value: models.ComputeTool = /* values here */ ``` -------------------------------- ### Perform Synchronous Research Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/USAGE.md Uses the You client to execute a research query synchronously. Requires an API key provided via the YOU_API_KEY_AUTH environment variable. ```python # Synchronous Example import os from youdotcom import You, models with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.research(input="Which global cities improved air quality the most over the past 10 years, and what measurable actions contributed?", research_effort=models.ResearchEffort.LITE) # Handle response print(res) ``` -------------------------------- ### Output Types Reference Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/type.md Defines the supported output types for SDK responses, including message answers and web search results. ```APIDOC ## Output Types ### Description The SDK categorizes output into specific types based on the nature of the response. These types determine how the data should be parsed or displayed. ### Supported Types - **message.answer** (String) - Used for standard text responses. - **web_search.results** (String) - Used for output containing web links. This type is triggered when using the `research` tool or the express agent with `web_search` enabled. ### Constants | Name | Value | | --- | --- | | MESSAGE_ANSWER | message.answer | | WEB_SEARCH_RESULTS | web_search.results | ``` -------------------------------- ### LiveCrawl Type for SearchLivecrawl Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/searchlivecrawl.md Use models.LiveCrawl to specify sections for live crawling. Replace /* values here */ with your desired configuration. ```python value: models.LiveCrawl = /* values here */ ``` -------------------------------- ### Configure Automatic Retries Source: https://context7.com/youdotcom-oss/youdotcom-python-sdk/llms.txt Implement exponential backoff for transient failures globally or on a per-request basis using RetryConfig and BackoffStrategy. ```python import os from youdotcom import You, models from youdotcom.utils import BackoffStrategy, RetryConfig # Global retry configuration with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), retry_config=RetryConfig( "backoff", BackoffStrategy( initial_interval=1, # Initial wait time in ms max_interval=50, # Max wait time in ms exponent=1.1, # Exponential backoff factor max_elapsed_time=100, # Max total retry time in ms ), False, # retry_connection_errors ), ) as you: res = you.research( input="What is quantum computing?", research_effort=models.ResearchEffort.LITE, ) print(res.output.content) # Per-request retry configuration with You( api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.research( input="What is machine learning?", research_effort=models.ResearchEffort.LITE, retries=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), ) print(res.output.content) ``` -------------------------------- ### Search Query Parameters Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/searchrequest.md Details regarding the parameters used to execute a search query through the You.com SDK. ```APIDOC ## Search Query Parameters ### Description Defines the parameters required to perform a search request, including the query string and result count configuration. ### Parameters #### Request Body - **query** (str) - Required - The search query used to retrieve relevant results from the web. You can also include search operators to refine your search. - **count** (int) - Optional - Specifies the maximum number of search results to return per section (the sections are web and news). ``` -------------------------------- ### Override Server URL Per-Client Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Sets a custom base URL for all requests by passing the server_url parameter during client initialization. ```python import os from youdotcom import You, models with You( server_url="https://api.you.com", api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.research(input="Which global cities improved air quality the most over the past 10 years, and what measurable actions contributed?", research_effort=models.ResearchEffort.LITE) # Handle response print(res) ``` -------------------------------- ### Configure Default Retries for the Entire SDK Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/README.md Set a default retry strategy for all supported operations when initializing the You object. This ensures consistent retry behavior across multiple API calls. ```python import os from youdotcom import You, models from youdotcom.utils import BackoffStrategy, RetryConfig with You( retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), api_key_auth=os.getenv("YOU_API_KEY_AUTH", ""), ) as you: res = you.research(input="Which global cities improved air quality the most over the past 10 years, and what measurable actions contributed?", research_effort=models.ResearchEffort.LITE) # Handle response print(res) ``` -------------------------------- ### Express Agent Request Configuration Source: https://github.com/youdotcom-oss/youdotcom-python-sdk/blob/main/docs/models/expressagentrunsrequest.md Details the mandatory and optional fields required to interface with the Express agent. ```APIDOC ## Express Agent Configuration ### Description Defines the parameters required to initiate a request to the You.com Express agent. ### Parameters #### Request Body - **agent** (Literal["express"]) - Required - Setting this value to "express" is mandatory to use the express agent. - **input** (str) - Required - The question you'd like to ask the agent. - **stream** (bool) - Optional - Must be set to `true` when you want to stream the express agent response as it's being generated, and `false` when you want the response to return after the agent has finished. ### Request Example { "agent": "express", "input": "What are some great recipes I can make in under half an hour", "stream": true } ```