### Install Contextual AI Python SDK Source: https://docs.contextual.ai/user-guides/beginner-guide Installs the necessary Python SDK for interacting with the Contextual AI platform. This is a prerequisite for using the Python client to manage datastores and agents. ```shell pip install contextual-client ``` -------------------------------- ### Query Agent with Python and cURL Source: https://docs.contextual.ai/user-guides/beginner-guide Send messages to your Contextual AI agent to get answers based on your uploaded documents. This snippet shows how to initialize the client and query the agent using Python, and how to perform the same query using cURL. ```python from contextual import ContextualAI # Initialize the client with your API key contextual = ContextualAI(api_key="API_KEY") # Query the agent response = contextual.agents.query.create( agent_id=agent_id, messages=[ { "role": "user", "content": "What is the revenue of Apple?" }] ) ``` ```shell curl --request POST \ --url https://api.contextual.ai/v1/agents/{agent_id}/query \ --header 'accept: application/json' \ --header 'authorization: Bearer $API_KEY' \ --header 'content-type: application/json' \ --data ' { "stream": false, "messages": [ { "role": "user", "content": "What is the revenue of Apple?" } ] }' ``` -------------------------------- ### Install Contextual Python SDK Source: https://docs.contextual.ai/index This command installs the Contextual Python client library using pip. This is the first step to programmatically interact with the Contextual AI platform in Python. ```bash pip install contextual-client ``` -------------------------------- ### Clone and Install MCP Server Source: https://docs.contextual.ai/user-guides/mcp-server Commands to clone the Contextual AI MCP Server repository and install its dependencies using pip. This involves creating and activating a Python virtual environment before installing the package in editable mode. ```bash git clone https://github.com/ContextualAI/contextual-mcp-server.git cd contextual-mcp-server python -m venv .venv source .venv/bin/activate pip install -e . ``` -------------------------------- ### MCP Server Configuration File Example Source: https://docs.contextual.ai/user-guides/mcp-server A JSON object defining the configuration for MCP servers. This specific example sets up a server named 'ContextualAI-TechDocs' using `uv` to run the `server.py` script with specified arguments, including the project's root directory. ```json { "mcpServers": { "ContextualAI-TechDocs": { "command": "/path/to/uv", "args": [ "--directory", "${workspaceFolder}", "run", "multi-agent/server.py" ] } } } ``` -------------------------------- ### Install contextual-client with aiohttp support Source: https://docs.contextual.ai/sdks/python This command installs the contextual-client package along with the 'aiohttp' extra, which enables the use of aiohttp as the HTTP backend for the asynchronous client. This can improve concurrency performance. ```bash pip install contextual-client[aiohttp] ``` -------------------------------- ### Creating an Agent with Nested Parameters Source: https://docs.contextual.ai/sdks/python Example of creating an agent, showcasing the use of nested dictionary parameters. ```APIDOC ## POST /api/agents ### Description Creates a new agent. This example demonstrates the use of nested parameters, typed using `TypedDict`. ### Method POST ### Endpoint /api/agents ### Parameters #### Request Body - **name** (string) - Required - The name of the agent. - **agent_configs** (object) - Optional - A dictionary of configuration settings for the agent. ### Request Example ```python from contextual import ContextualAI client = ContextualAI() create_agent_output = client.agents.create( name="My New Agent", agent_configs={ "setting1": "value1" } # Example nested parameter ) print(create_agent_output.agent_configs) ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created agent. - **name** (string) - The name of the agent. - **agent_configs** (object) - The configuration settings for the agent. #### Response Example ```json { "id": "agent-456", "name": "My New Agent", "agent_configs": { "setting1": "value1" } } ``` ``` -------------------------------- ### GET /datastores Source: https://docs.contextual.ai/llms-full Retrieves a list of all Datastores. Supports cursor-based pagination for a large number of datastores. ```APIDOC ## GET /datastores ### Description Retrieve a list of `Datastores`. Performs `cursor`-based pagination if the number of `Datastores` exceeds the requested `limit`. The returned `cursor` can be passed to the next `GET /datastores` call to retrieve the next set of `Datastores`. ### Method GET ### Endpoint `/datastores` ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of datastores to return. - **cursor** (string) - Optional - The cursor for pagination, used to retrieve the next set of datastores. ### Request Example ```json { "limit": 20, "cursor": "some_cursor_string" } ``` ### Response #### Success Response (200) - **datastores** (array) - A list of datastores, each with `id` and `name`. - **next_cursor** (string) - The cursor for the next page of results. #### Response Example ```json { "datastores": [ { "id": "ds_abc123", "name": "Datastore One" }, { "id": "ds_def456", "name": "Datastore Two" } ], "next_cursor": "another_cursor_string" } ``` ``` -------------------------------- ### GET /billing/usages/earliest_date Source: https://docs.contextual.ai/api-reference/billing/get-earliest-usage-date-endpoint Retrieves the earliest recorded usage date for a given tenant. This is useful for understanding the start of billing cycles or data availability. ```APIDOC ## GET /billing/usages/earliest_date ### Description Get the earliest usage date for a tenant. ### Method GET ### Endpoint /billing/usages/earliest_date ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **date** (string or null) - The earliest usage date in 'YYYY-MM-DD' format, or null if no usage data is available. #### Response Example ```json { "date": "2023-12-25" } ``` ``` -------------------------------- ### Datastores API Source: https://docs.contextual.ai/user-guides/beginner-guide This section details how to interact with the datastores API to create and manage your data stores. ```APIDOC ## POST /v1/datastores ### Description Creates a new datastore. Datastores contain the files that your agent(s) can access. Each agent must be associated with at least one datastore. ### Method POST ### Endpoint /v1/datastores ### Parameters #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the datastore. ### Request Example ```json { "name": "Test Datastore" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the newly created datastore. #### Response Example ```json { "id": "dts_abcdef12345" } ``` ``` -------------------------------- ### Get Document Metadata Source: https://docs.contextual.ai/user-guides/beginner-guide Retrieves metadata for documents within a datastore, including their ingestion status. Useful for checking processing status after upload. ```APIDOC ## GET /v1/datastores/{datastore_id}/documents ### Description Retrieves metadata for documents in a specified datastore. ### Method GET ### Endpoint `https://api.contextual.ai/v1/datastores/{datastore_id}/documents` ### Parameters #### Path Parameters - **datastore_id** (string) - Required - The ID of the datastore to query. #### Query Parameters - **document_id** (string) - Optional - Filters results to a specific document. #### Request Body None ### Request Example ```shell curl --request GET \ --url https://api.contextual.ai/v1/datastores/{datastore_id}/documents \ --header 'accept: application/json' \ --header 'authorization: Bearer $API_KEY' ``` ### Response #### Success Response (200) - **metadata** (array) - An array of document metadata objects. Each object may contain `id` and `ingestion_job_status`. #### Response Example ```json { "metadata": [ { "id": "doc_abc123xyz", "ingestion_job_status": "completed" } ] } ``` ``` -------------------------------- ### Create Agent with Datastore (Python, cURL) Source: https://docs.contextual.ai/user-guides/beginner-guide This snippet provides instructions for creating an agent using the Contextual AI platform, linking it to one or more datastores. Both Python and cURL implementations are given. The process requires an API key and the datastore ID(s). ```python from contextual import ContextualAI # Initialize the client with your API key contextual = ContextualAI(api_key="API_KEY") # Create an agent agent = contextual.agents.create(name="Test Agent", description="Test Agent", datastore_ids=[datastore_id]) ``` ```shell curl --request POST \ --url https://api.contextual.ai/v1/agents \ --header 'accept: application/json' \ --header 'authorization: Bearer $API_KEY' \ --header 'content-type: application/json' \ --data \ '{ "name": "Test", "description": "Test Agent", "datastore_ids": [] }' ``` -------------------------------- ### Get List of Agents using Contextual AI Python SDK Source: https://docs.contextual.ai/llms-full This snippet retrieves a list of agents available for API testing using the Contextual AI Python SDK. It requires the 'contextual-client-python' library to be installed and a configured client object. The output is a list of agent objects. ```python agents = [a for a in client.agents.list()] ``` -------------------------------- ### Create Datastore using cURL Source: https://docs.contextual.ai/user-guides/beginner-guide Shows how to create a new datastore using a cURL command. This method requires specifying the API endpoint, authentication token, and the datastore name in JSON format. It's an alternative to using the Python SDK for datastore creation. ```shell curl --request POST \ --url https://api.contextual.ai/v1/datastores \ --header 'accept: application/json' \ --header 'authorization: Bearer $API_KEY' \ --header 'content-type: application/json' \ --data '{"name":"Test Datastore"}' ``` -------------------------------- ### Get API Endpoint Snowflake Query Source: https://docs.contextual.ai/user-guides/snowflake This Snowflake SQL query retrieves the backend API endpoint URL for your Contextual AI Native App instance. This URL is essential for constructing the full API endpoint for programmatic access. ```sql CALL CONTEXTUAL_NATIVE_APP.CORE.GET_API_ENDPOINT() ``` -------------------------------- ### Create Datastore using Contextual AI Python SDK Source: https://docs.contextual.ai/user-guides/beginner-guide Demonstrates how to create a new datastore using the Contextual AI Python client. This involves initializing the client with an API key and calling the datastores.create method with a desired name. The datastore ID is returned upon successful creation. ```python from contextual import ContextualAI # Initialize the client with your API key contextual = ContextualAI(api_key="API_KEY") # Create a datastore datastore = contextual.datastores.create(name="Test Datastore") ``` -------------------------------- ### Enable/Disable Multi-Turn Conversation for Contextual AI Agent Source: https://docs.contextual.ai/llms-full This snippet demonstrates how to enable or disable multi-turn conversation capabilities for a Contextual AI agent. It shows both Python SDK usage and a cURL command for API interaction. Ensure you have the Contextual AI SDK installed for the Python example. The `enable_multi_turn` parameter within `agent_configs.global_config` controls this functionality. ```python from contextual import ContextualAI client = ContextualAI(api_key=api_key) # input your key agent_id = "" # input your agent_id params = { "agent_configs": { "global_config": { "enable_multi_turn": True # Set to False to disable multiturn } } } client.agents.update(agent_id=agent_id, extra_body=params) ``` ```bash curl 'https://api.app.contextual.ai/v1/agents/{agent_id} \ --request PUT \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer $API_KEY' \ --data '{ \ "agent_configs": { \ "global_config": { \ "enable_multi_turn": true \ } \ } \ }' ``` -------------------------------- ### GET /billing/balance Source: https://docs.contextual.ai/api-reference/billing/get-balance Retrieves the remaining balance for a tenant. ```APIDOC ## GET /billing/balance ### Description Get the remaining balance for a tenant. ### Method GET ### Endpoint /billing/balance ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **balance** (number) - Balance of the user #### Response Example ```json { "balance": 123 } ``` ``` -------------------------------- ### Check Installed Contextual AI Version (Python) Source: https://docs.contextual.ai/sdks/python This snippet demonstrates how to check the currently installed version of the contextual library in a Python environment. It imports the library and prints its __version__ attribute. Ensure Python 3.8 or higher is installed. ```python import contextual print(contextual.__version__) ``` -------------------------------- ### Ingest Document Source: https://docs.contextual.ai/user-guides/beginner-guide Uploads a single document to a specified datastore. Supports PDF and other renderable formats. Processing time may vary based on document length and features. ```APIDOC ## POST /v1/datastores/{datastore_id}/documents ### Description Uploads a single document to a specified datastore. ### Method POST ### Endpoint `https://api.contextual.ai/v1/datastores/{datastore_id}/documents` ### Parameters #### Path Parameters - **datastore_id** (string) - Required - The ID of the datastore to upload the document to. #### Query Parameters None #### Request Body - **file** (file) - Required - The document file to upload (e.g., PDF). ### Request Example ```shell curl --request POST \ --url https://api.contextual.ai/v1/datastores/{datastore_id}/documents \ --header 'accept: application/json' \ --header 'authorization: Bearer $API_KEY' \ --header 'content-type: multipart/form-data' \ --form file=@'${file_path}' ``` ### Response #### Success Response (200) - **id** (string) - The ID of the uploaded document. #### Response Example ```json { "id": "doc_abc123xyz" } ``` ``` -------------------------------- ### Create Agent Source: https://docs.contextual.ai/user-guides/beginner-guide Creates a new agent associated with one or more datastores. Agents can be used to query information from the linked datastores. ```APIDOC ## POST /v1/agents ### Description Creates a new agent linked to specified datastores. ### Method POST ### Endpoint `https://api.contextual.ai/v1/agents` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the agent. - **description** (string) - Optional - A description for the agent. - **datastore_ids** (array of strings) - Required - A list of datastore IDs to associate with the agent. ### Request Example ```json { "name": "Test Agent", "description": "Test Agent", "datastore_ids": ["datastore_id_1", "datastore_id_2"] } ``` ```shell curl --request POST \ --url https://api.contextual.ai/v1/agents \ --header 'accept: application/json' \ --header 'authorization: Bearer $API_KEY' \ --header 'content-type: application/json' \ --data '{ "name": "Test Agent", "description": "Test Agent", "datastore_ids": ["datastore_id_1"] }' ``` ### Response #### Success Response (200) - **agent_id** (string) - The ID of the newly created agent. #### Response Example ```json { "agent_id": "agent_def456uvw" } ``` ``` -------------------------------- ### GET /billing/metadata Source: https://docs.contextual.ai/api-reference/billing/get-billing-metadata Retrieves the billing metadata for a tenant. This is a non-admin endpoint. ```APIDOC ## GET /billing/metadata ### Description Retrieves the billing metadata for a tenant. This is a non-admin endpoint. ### Method GET ### Endpoint /billing/metadata ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **is_low_balance** (boolean) - Whether the user is low on balance - **is_auto_top_up_enabled** (boolean) - Whether auto-top-up is enabled #### Response Example ```json { "is_low_balance": true, "is_auto_top_up_enabled": true } ``` ``` -------------------------------- ### Create Datastore using Python SDK Source: https://docs.contextual.ai/index Demonstrates how to create a new datastore using the Contextual AI Python SDK. A datastore is required to store documents that your AI agents can access. This requires initializing the client with an API key. ```python from contextual import ContextualAI # Initialize the client with your API key contextual = ContextualAI(api_key="API_KEY") # Create a datastore datastore = contextual.datastores.create(name="Test Datastore") ``` -------------------------------- ### OpenAPI Specification for Get Balance Source: https://docs.contextual.ai/api-reference/billing/get-balance The OpenAPI specification defines the GET /billing/balance endpoint. It details the request method, server URL, authentication requirements (BearerAuth), and the structure of the successful JSON response, which includes the user's balance. ```yaml paths: path: /billing/balance method: get servers: - url: https://api.contextual.ai/v1 request: security: - title: BearerAuth parameters: query: {} header: Authorization: type: http scheme: bearer cookie: {} parameters: path: {} query: {} header: {} cookie: {} body: {} response: '200': application/json: schemaArray: - type: object properties: balance: allOf: - type: number title: Balance description: Balance of the user title: BalanceResponse description: Response to GET /billing/balance request refIdentifier: '#/components/schemas/BalanceResponse' requiredProperties: - balance examples: example: value: balance: 123 description: Successful Response deprecated: false type: path components: schemas: {} ``` -------------------------------- ### Listing Agents Source: https://docs.contextual.ai/sdks/python Demonstrates how to list all agents, fetching additional pages as needed. ```APIDOC ## GET /api/agents ### Description Fetches a list of all agents. The API automatically handles pagination, fetching more pages as needed. ### Method GET ### Endpoint /api/agents ### Parameters None ### Request Example ```python from contextual import ContextualAI client = ContextualAI() all_agents = [] for agent in client.agents.list(): all_agents.append(agent) print(all_agents) ``` ### Response #### Success Response (200) - **agents** (list) - A list of agent objects. - **next_cursor** (string) - A cursor for fetching the next page of results. #### Response Example ```json { "agents": [ { "id": "agent-123", "name": "Example Agent" } ], "next_cursor": "cursor-abc" } ``` ``` -------------------------------- ### Get Auto Top Up Status (OpenAPI) Source: https://docs.contextual.ai/api-reference/billing/get-auto-top-up-status This OpenAPI specification defines the GET request for retrieving the auto top-up status. It specifies the endpoint, authentication method (Bearer Token), and the structure of the successful response, which includes whether auto top-up is enabled, the top-up amount, and the balance threshold. ```yaml paths: path: /billing/balance/auto-top-up method: get servers: - url: https://api.contextual.ai/v1 request: security: - title: BearerAuth parameters: query: {} header: Authorization: type: http scheme: bearer cookie: {} parameters: path: {} query: {} header: {} cookie: {} body: {} response: '200': application/json: schemaArray: - type: object properties: enabled: allOf: - type: boolean title: Enabled description: Whether auto top-up is enabled amount: allOf: - anyOf: - type: number - type: 'null' title: Amount description: Amount in $ to top up balance_threshold: allOf: - anyOf: - type: number - type: 'null' title: Balance Threshold description: Balance threshold in $ to trigger auto top-up title: AutoTopUpStatusResponse description: Response to GET /billing/balance/auto-top-up request refIdentifier: '#/components/schemas/AutoTopUpStatusResponse' requiredProperties: - enabled examples: example: value: enabled: true amount: 123 balance_threshold: 123 description: Successful Response deprecated: false type: path components: schemas: {} ``` -------------------------------- ### GET /parse/jobs Source: https://docs.contextual.ai/llms-full Get a list of parse jobs, sorted from most recent to oldest. Returns jobs from the last 30 days or since an optional `uploaded_after` timestamp. ```APIDOC ## GET /parse/jobs ### Description Get list of parse jobs, sorted from most recent to oldest. Returns all jobs from the last 30 days, or since the optional `uploaded_after` timestamp. ### Method GET ### Endpoint /parse/jobs ### Parameters #### Query Parameters - **uploaded_after** (timestamp) - Optional - Fetch jobs uploaded after this timestamp. ### Response #### Success Response (200) - **jobs** (array) - A list of parse job objects. - **job_id** (string) - The ID of the parse job. - **created_at** (timestamp) - The timestamp when the job was created. #### Response Example { "jobs": [ { "job_id": "job-abc-123", "created_at": "2023-10-27T10:00:00Z" } ] } ``` -------------------------------- ### Upload Document to Datastore (Python, cURL) Source: https://docs.contextual.ai/user-guides/beginner-guide This snippet demonstrates how to upload a single document to a Contextual AI datastore using both Python and cURL. It requires an API key and the datastore ID. The output includes the document ID upon successful upload. ```python from contextual import ContextualAI # Initialize the client with your API key contextual = ContextualAI(api_key="API_KEY") # Upload a document with open('file.pdf', 'rb') as f: ingestion_result = contextual.datastores.documents.ingest(datastore_id, file=f) document_id = ingestion_result.id print(f"Successfully uploaded document_id: {document_id} to datastore_id: {datastore_id}") ``` ```shell curl --request POST \ --url https://api.contextual.ai/v1/datastores/{datastore_id}/documents \ --header 'accept: application/json' \ --header 'authorization: Bearer $API_KEY' \ --header 'content-type: multipart/form-data' \ --form file=@'${file_path}' ``` -------------------------------- ### Async API Usage with aiohttp backend Source: https://docs.contextual.ai/sdks/python Shows how to use the asynchronous Contextual AI client with 'aiohttp' as the HTTP backend for potentially better performance. It initializes the client with `DefaultAioHttpClient()` and demonstrates creating an agent. Requires `contextual-client[aiohttp]` installation. ```python import asyncio from contextual import DefaultAioHttpClient from contextual import AsyncContextualAI async def main() -> None: async with AsyncContextualAI( api_key="My API Key", http_client=DefaultAioHttpClient(), ) as client: create_agent_output = await client.agents.create( name="Example", ) print(create_agent_output.id) asyncio.run(main()) ``` -------------------------------- ### Get Top Up History Source: https://docs.contextual.ai/api-reference/billing/get-top-up-history-endpoint Retrieves the paginated top-up history for a tenant. Supports filtering and pagination with limit and cursor parameters. ```APIDOC ## GET /billing/balance/top-ups ### Description Get the top-up history for a tenant. This endpoint is paginated. ### Method GET ### Endpoint /billing/balance/top-ups ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of top-ups to return. Defaults to 10, with a maximum of 50. - **cursor** (string) - Optional - A cursor to fetch the next page of results. #### Request Body This endpoint does not accept a request body. ### Request Example ```json { "example": "GET /v1/billing/balance/top-ups?limit=20&cursor=some_cursor_string" } ``` ### Response #### Success Response (200) - **top_ups** (array) - List of top-up entries. - **has_more** (boolean) - Indicates if there are more top-up entries available. - **cursor** (string | null) - A cursor for fetching the next page of results, or null if there are no more pages. #### Response Example ```json { "example": { "top_ups": [ { "amount": 123, "created_at": "2023-11-07T05:31:56Z", "description": "", "starting_balance": 123, "ending_balance": 123 } ], "has_more": true, "cursor": "" } } ``` #### Error Response (422) - **detail** (array) - A list of validation errors. #### Error Response Example ```json { "example": { "detail": [ { "loc": [ "" ], "msg": "", "type": "" } ] } } ``` ``` -------------------------------- ### GET /billing/usages/monthly Source: https://docs.contextual.ai/api-reference/billing/get-monthly-usage-endpoint Retrieves monthly usage data for a tenant. You can specify the year and month for which you want the usage data. Optionally, a resource_id can be provided to get usage data for a specific resource. ```APIDOC ## GET /billing/usages/monthly ### Description Get monthly usage data for a tenant with validation for year and month parameters. ### Method GET ### Endpoint https://api.contextual.ai/v1/billing/usages/monthly ### Parameters #### Query Parameters - **year** (integer) - Required - The year for which to retrieve usage data. Minimum value is 2025. - **month** (integer) - Required - The month for which to retrieve usage data. Must be between 1 and 12. - **resource_id** (string) - Optional - If provided, get usage data for a specific resource. Otherwise, get aggregated usage data across all resources. Must be a valid UUID. ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **usages** (array) - A list of daily usage records for the specified month and year. - **date** (string) - The date of the usage record. - **usage_type** (string) - The type of usage (e.g., QUERY_REFORMULATION_INPUT_TOKEN). - **quantity** (integer) - The quantity of usage. - **price** (number) - The price per unit of usage. #### Response Example ```json { "usages": [ { "date": "2023-12-25", "usage_type": "QUERY_REFORMULATION_INPUT_TOKEN", "quantity": 123, "price": 123 } ] } ``` #### Error Response (422) - **detail** (array) - Contains details about validation errors. - **loc** (array) - The location of the error in the request. - **msg** (string) - The error message. - **type** (string) - The type of error. ``` -------------------------------- ### POST /v1/agents/{agent_id}/query Source: https://docs.contextual.ai/user-guides/beginner-guide This endpoint allows you to send messages to your agent and receive responses based on the uploaded documents. It supports both Python client and cURL requests. ```APIDOC ## POST /v1/agents/{agent_id}/query ### Description Send messages to your agent to get responses based on the documents you've uploaded. This endpoint is crucial for interacting with your agent's knowledge base. ### Method POST ### Endpoint `/v1/agents/{agent_id}/query` ### Parameters #### Path Parameters - **agent_id** (string) - Required - The unique identifier of the agent to query. #### Query Parameters None #### Request Body - **stream** (boolean) - Optional - If set to true, the response will be streamed. Defaults to false. - **messages** (array) - Required - An array of message objects representing the conversation history. - **role** (string) - Required - The role of the message sender (e.g., 'user', 'assistant'). - **content** (string) - Required - The content of the message. ### Request Example ```json { "stream": false, "messages": [ { "role": "user", "content": "What is the revenue of Apple?" } ] } ``` ### Response #### Success Response (200) - **response** (object) - The response from the agent. - **content** (string) - The textual answer provided by the agent. - **sources** (array) - An array of sources retrieved from the datastore that are relevant to the response. - **attributions** (object) - Citations of sources to specific text spans in the response. #### Response Example ```json { "response": { "content": "Apple's revenue for the last fiscal quarter was $X billion.", "sources": [ { "id": "doc1", "text": "Apple reported Q3 revenue of $83 billion." } ], "attributions": [ { "text_span": "$X billion", "source_id": "doc1" } ] } } ``` ``` -------------------------------- ### Get Auto Top Up Status Source: https://docs.contextual.ai/api-reference/billing/get-auto-top-up-status Retrieves the current auto top-up status for a tenant, including whether it's enabled, the top-up amount, and the balance threshold. ```APIDOC ## GET /billing/balance/auto-top-up ### Description Get the auto top-up status for a tenant. ### Method GET ### Endpoint /billing/balance/auto-top-up ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **enabled** (boolean) - Whether auto top-up is enabled - **amount** (number | null) - Amount in $ to top up - **balance_threshold** (number | null) - Balance threshold in $ to trigger auto top-up #### Response Example ```json { "enabled": true, "amount": 123, "balance_threshold": 123 } ``` ``` -------------------------------- ### OpenAPI Specification for Get Top Up History Source: https://docs.contextual.ai/api-reference/billing/get-top-up-history-endpoint This OpenAPI 3.0 specification defines the 'GET /billing/balance/top-ups' endpoint. It details the request parameters (limit, cursor), authentication (BearerAuth), and response schemas for successful top-up history retrieval and validation errors. The response includes a list of top-ups, a cursor for pagination, and a boolean indicating if more data is available. ```yaml paths: path: /billing/balance/top-ups method: get servers: - url: https://api.contextual.ai/v1 request: security: - title: BearerAuth parameters: query: {} header: Authorization: type: http scheme: bearer cookie: {} parameters: path: {} query: limit: schema: - type: integer required: false title: Limit maximum: 50 default: 10 cursor: schema: - type: string required: false title: Cursor - type: 'null' required: false title: Cursor header: {} cookie: {} body: {} response: '200': application/json: schemaArray: - type: object properties: top_ups: allOf: - items: $ref: '#/components/schemas/TopUpHistoryResponse' type: array title: Top Ups description: List of top-ups has_more: allOf: - type: boolean title: Has More description: Whether there are more top-ups to fetch cursor: allOf: - anyOf: - type: string - type: 'null' title: Cursor description: Cursor for next page title: GetTopUpHistoryResponse description: Response to GET /billing/free-credit request refIdentifier: '#/components/schemas/GetTopUpHistoryResponse' requiredProperties: - top_ups - has_more examples: example: value: top_ups: - amount: 123 created_at: '2023-11-07T05:31:56Z' description: starting_balance: 123 ending_balance: 123 has_more: true cursor: description: Successful Response '422': application/json: schemaArray: - type: object properties: detail: allOf: - items: $ref: '#/components/schemas/ValidationError' type: array title: Detail title: HTTPValidationError refIdentifier: '#/components/schemas/HTTPValidationError' examples: example: value: detail: - loc: - msg: type: description: Validation Error deprecated: false type: path components: schemas: TopUpHistoryResponse: properties: amount: type: number title: Amount description: Amount of the top-up created_at: type: string format: date-time title: Created At description: Date when the top-up was created description: type: string title: Description description: Description of the top-up starting_balance: type: number title: Starting Balance description: Starting balance before the top-up ending_balance: type: number title: Ending Balance description: Ending balance after the top-up type: object required: - amount - created_at - description - starting_balance - ending_balance title: TopUpHistoryResponse description: Individual top-up entry ValidationError: properties: loc: items: anyOf: - type: string - type: integer type: array title: Location msg: type: string title: Message type: type: string title: Error Type type: object required: - loc - msg - type title: ValidationError ``` -------------------------------- ### Configure MCP Server for AI Interface Integration Source: https://docs.contextual.ai/user-guides/mcp-server Bash commands to set up the `mcp.json` configuration file for integrating the MCP server with AI clients like Cursor IDE or Claude Desktop. It includes finding the `uv` path and defining server commands and arguments. ```bash UV_PATH=$(which uv) echo $UV_PATH cat > mcp.json << EOF { "mcpServers": { "ContextualAI-TechDocs": { "command": "$UV_PATH", "args": [ "--directory", "\${workspaceFolder}", "run", "multi-agent/server.py" ] } } } EOF mkdir -p .cursor/ mv mcp.json .cursor/ ``` -------------------------------- ### Synchronous API Usage with Contextual AI Python Client Source: https://docs.contextual.ai/sdks/python Demonstrates how to initialize and use the synchronous Contextual AI client. It shows creating an agent and printing its ID. The API key can be provided directly or read from environment variables (recommended). Requires Python 3.8+. ```python import os from contextual import ContextualAI client = ContextualAI( api_key=os.environ.get("CONTEXTUAL_API_KEY"), # This is the default and can be omitted ) create_agent_output = client.agents.create( name="Example", ) print(create_agent_output.id) ``` -------------------------------- ### Logging Source: https://docs.contextual.ai/sdks/python Instructions on how to enable logging for the Contextual AI library. ```APIDOC ## Logging ### Description Enable detailed logging for the Contextual AI library using the standard Python `logging` module. ### Enabling Logging Set the environment variable `CONTEXTUAL_AI_LOG` to `info` or `debug`. ### Commands ```bash # Enable info level logging export CONTEXTUAL_AI_LOG=info # Enable debug level logging for more verbosity export CONTEXTUAL_AI_LOG=debug ``` ``` -------------------------------- ### Example QueryRequestV1 with JSON Metadata Filter Source: https://docs.contextual.ai/api-reference/agents-query/query Demonstrates an example of a `QueryRequestV1` object, which is the request body for a POST `/agents/{agent_id}/query` request. It includes the `documents_filters` field utilizing the described JSON metadata filter structure. ```json { "messages": [ { "content": "", "role": "user" } ], "stream": false, "conversation_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "llm_model_id": "", "structured_output": { "type": "JSON", "json_schema": {} }, "documents_filters": { "filters": [ { "field": "field1", "operator": "equals", "value": "value1" } ], "operator": "AND" }, "override_configuration": { "system_prompt": "", "filter_prompt": "", "model": "", "max_new_tokens": 123, "top_p": 123, "temperature": 123, "top_k_retrieved_chunks": 123, "top_k_reranked_chunks": 123, "enable_filter": true, "filter_model": "", "enable_rerank": true, "reranker": "", "lexical_alpha": 123, "semantic_alpha": 123, "rerank_instructions": "", "reranker_score_filter_threshold": 123 } } ``` -------------------------------- ### Configure MCP Server for Cursor/Claude Desktop (Bash) Source: https://docs.contextual.ai/llms-full Creates a configuration file (mcp.json) to integrate the MCP Server with AI clients like Cursor IDE and Claude Desktop. It specifies the command to run the server and its arguments, including the path to the uv executable. ```bash UV_PATH=$(which uv) cat > mcp.json << EOF { "mcpServers": { "ContextualAI-TechDocs": { "command": "$UV_PATH", "args": [ "--directory", "\${workspaceFolder}", "run", "multi-agent/server.py" ] } } } EOF mkdir -p .cursor/ mv mcp.json .cursor/ ``` -------------------------------- ### OpenAPI Specification for Billing Metadata Source: https://docs.contextual.ai/api-reference/billing/get-billing-metadata This OpenAPI specification defines the GET /billing/metadata endpoint. It details the request security, parameters, and the structure of the successful JSON response, including properties for low balance and auto top-up status. ```yaml paths: path: /billing/metadata method: get servers: - url: https://api.contextual.ai/v1 request: security: - title: BearerAuth parameters: query: {} header: Authorization: type: http scheme: bearer cookie: {} parameters: path: {} query: {} header: {} cookie: {} body: {} response: '200': application/json: schemaArray: - type: object properties: is_low_balance: allOf: - type: boolean title: Is Low Balance description: Whether the user is low on balance is_auto_top_up_enabled: allOf: - type: boolean title: Is Auto Top Up Enabled description: Whether auto top-up is enabled title: BillingMetadataResponse description: Response to GET /billing/metadata request refIdentifier: '#/components/schemas/BillingMetadataResponse' requiredProperties: - is_low_balance - is_auto_top_up_enabled examples: example: value: is_low_balance: true is_auto_top_up_enabled: true description: Successful Response deprecated: false type: path components: schemas: {} ``` -------------------------------- ### Creating a Contextual AI Client Source: https://docs.contextual.ai/llms-full Combine the API endpoint and authentication token to initialize a Python client for interacting with Contextual AI. ```APIDOC ## Creating a Contextual AI Client ### Description This example shows how to create a Python client instance for the Contextual AI API by combining the previously obtained base URL and API key (Snowflake session token). ### Method Python Script ### Endpoint N/A ### Parameters #### Request Body - **api_key** (string) - The Snowflake session token obtained from authentication. - **base_url** (string) - The full API endpoint URL (e.g., `https://xxxxx-xxxxx-xxxxx.snowflakecomputing.app/v1`). ### Request Example ```python import snowflake.connector # Assuming ContextualAI class is defined elsewhere or imported # from contextual_ai_sdk import ContextualAI SF_BASE_URL = 'xxxxx-xxxxx-xxxxx.snowflakecomputing.app' # Obtained from GET_API_ENDPOINT() BASE_URL = f'https://{SF_BASE_URL}/v1' ctx = snowflake.connector.connect( # type: ignore user="", password='', account="organization-account", session_parameters={ 'PYTHON_CONNECTOR_QUERY_RESULT_FORMAT': 'json' } ) # Obtain a session token. token_data = ctx._rest._token_request('ISSUE') # type: ignore token_extract = token_data['data']['sessionToken'] # type: ignore # Create a request to the ingress endpoint with authz. api_key = f'\"{token_extract}\"' # Initialize the client # client = ContextualAI(api_key=api_key, base_url=BASE_URL) # Now you can use the 'client' object to interact with the Contextual AI API ``` ### Response #### Success Response The `client` object is successfully initialized and ready for use. #### Response Example N/A (This is a client initialization, not an API call response) ``` -------------------------------- ### GET /workspaces/consent Source: https://docs.contextual.ai/llms-full Retrieve the current consent status for the workspace. ```APIDOC ## GET /workspaces/consent ### Description Retrieve the current consent status for the workspace. ### Method GET ### Endpoint /workspaces/consent ### Parameters (No parameters required) ### Response #### Success Response (200) - **consent_status** (boolean) - The current consent status (true for granted, false for denied). #### Response Example { "consent_status": true } ``` -------------------------------- ### Create Agent - Python Source: https://docs.contextual.ai/index Creates a new agent that can be used to query documents stored in a datastore. Initializes the ContextualAI client with an API key and specifies the agent's name, description, and associated datastore IDs. ```python from contextual import ContextualAI # Initialize the client with your API key contextual = ContextualAI(api_key="API_KEY") # Create an agent agent = contextual.agents.create(name="Test Agent", description="Test Agent", datastore_ids=[datastore_id]) ```