### AsyncGovernanceClient Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Demonstrates listing organizations and users, and creating an API key using the asynchronous governance client. Ensure you have the 'air' library installed and an API key. ```python import asyncio from air import AsyncAIRefinery async def main(): client = AsyncAIRefinery(api_key="sk-...") # List organizations orgs = await client.governance.organizations.list() for org in orgs.data: print(f"Organization: {org.name}") # List users users = await client.governance.users.list() for user in users.data: print(f"User: {user.email}") # Create API key new_key = await client.governance.api_keys.create( name="my-app-key", description="API key for my application" ) print(f"Created key: {new_key.id}") asyncio.run(main()) ``` -------------------------------- ### GovernanceClient Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Demonstrates listing organizations and retrieving a user by email using the synchronous governance client. Ensure you have the 'air' library installed and an API key. ```python from air import AIRefinery def main(): client = AIRefinery(api_key="sk-...") # List organizations orgs = client.governance.organizations.list() for org in orgs.data: print(f"Organization: {org.name}") # Get user by email user = client.governance.users.get_by_email("user@example.com") print(f"User ID: {user.id}") main() ``` -------------------------------- ### Synchronous Text-to-Speech Synthesis Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AudioClient.md Demonstrates how to use the synchronous `create` method to synthesize speech from text and save the audio to a file. Ensure you have the `air` library installed and an API key. ```python from air import AIRefinery client = AIRefinery(api_key="sk-...") audio_bytes = client.audio.speech.create( model="azure/tts", input="Hello, this is a test of text-to-speech synthesis.", voice="en-US-JennyNeural", response_format="mp3", speed=1.0 ) # Save to file with open("output.mp3", "wb") as f: f.write(audio_bytes) ``` -------------------------------- ### Sync Client Usage Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/INDEX.md Illustrates how to initialize and use the synchronous Airefinery client. Use this if non-blocking operations are not required. ```python # Sync (if needed) from air import AIRefinery client = AIRefinery(api_key="sk-...") result = client.chat.completions.create(...) ``` -------------------------------- ### Async Client Usage Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/INDEX.md Shows how to initialize and use the asynchronous Airefinery client. This is the recommended approach for non-blocking operations. ```python # Async (recommended) import asyncio from air import AsyncAIRefinery async def main(): client = AsyncAIRefinery(api_key="sk-...") result = await client.chat.completions.create(...) asyncio.run(main()) ``` -------------------------------- ### Asynchronous Text-to-Speech Synthesis Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AudioClient.md Shows how to perform asynchronous speech synthesis using `AsyncAIRefinery`. This example requires `asyncio` and demonstrates saving the generated audio to a file. ```python import asyncio from air import AsyncAIRefinery async def main(): client = AsyncAIRefinery(api_key="sk-...") audio_bytes = await client.audio.speech.create( model="azure/tts", input="Hello, how are you?", voice="en-US-AriaNeural" ) with open("output.mp3", "wb") as f: f.write(audio_bytes) asyncio.run(main()) ``` -------------------------------- ### Example: Using AsyncKnowledgeClient for Graph Operations Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/KnowledgeClient.md Demonstrates how to initialize the AsyncKnowledgeClient and obtain a knowledge graph client for asynchronous operations. ```python import asyncio from air import AsyncAIRefinery async def main(): client = AsyncAIRefinery(api_key="sk-...") graph_client = await client.knowledge.get_graph() # Use graph_client for knowledge graph operations asyncio.run(main()) ``` -------------------------------- ### Example: Synchronous Document Processing with KnowledgeClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/KnowledgeClient.md Shows how to initialize the synchronous KnowledgeClient and use its document_processing attribute to parse documents. ```python from air import AIRefinery def main(): client = AIRefinery(api_key="sk-...") # Document processing (sync) response = client.knowledge.document_processing.parse_documents( file_path="/path/to/document.pdf", model="knowledge/document-parser" ) print(response) main() ``` -------------------------------- ### AIRefinery Client Usage Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AIRefinery.md Demonstrates how to use the AIRefinery client for chat completions, generating embeddings, and listing available models. Ensure you have the 'air' library installed and replace 'sk-...' with your actual API key. ```python from air import AIRefinery def main(): client = AIRefinery(api_key="sk-...") # Chat completions response = client.chat.completions.create( model="openai/gpt-oss-120b", messages=[{"role": "user", "content": "Hello"}] ) print(response.choices[0].message.content) # Embeddings embeddings = client.embeddings.create( model="intfloat/e5-mistral-7b-instruct", input=["Hello world"] ) print(embeddings.data[0].embedding[:5]) # Models list models = client.models.list() for model in models.data: print(f"- {model.id}") main() ``` -------------------------------- ### Install AI Refinery SDK Source: https://github.com/accenture/airefinery-sdk/blob/main/README.md Install the AI Refinery SDK using pip. Ensure you are using Python 3.12 or later. ```bash pip install airefinery-sdk ``` -------------------------------- ### Python Client Setup and Execution Source: https://github.com/accenture/airefinery-sdk/blob/main/README.md Instantiate an AsyncAIRefinery client, create a project using a YAML configuration, and run the project in interactive mode. This code defines a simple agent and sets up the client to interact with the AI Refinery service. ```python import asyncio import os from air import AsyncAIRefinery API_KEY =str(os.getenv("AIREFINERY_API_KEY")) async def simple_agent(query: str): prompt = "You are an AI assistant that helps users navigate their projects." client = AsyncAIRefinery(api_key=API_KEY) response = await client.chat.completions.create( messages=[{"role": "user", "content": prompt}], model="openai/gpt-oss-120b", ) return response.choices[0].message.content async def distiller_client_test(): client = AsyncAIRefinery(api_key=API_KEY) project_name = "my_first_project" # upload your config file to register a new distiller project client.distiller.create_project(config_path="example.yaml", project=project_name) # Define a mapping between your custom agent to Callable. # When the custom agent is summoned by the super agent / orchestrator, # distiller-sdk will run the custom agent and send its response back to the # multi-agent system. executor_dict = { "Assistant Agent": simple_agent, } async with client.distiller( project=project_name, uuid="test_user", executor_dict=executor_dict, ) as dc: responses = await dc.query("Hello") async for response in responses: print(response["content"]) if __name__ == "__main__": asyncio.run(distiller_client_test()) ``` -------------------------------- ### AsyncImagesClient Generate Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/ImagesClient.md Example of using the asynchronous AsyncImagesClient to generate images. It uses asyncio to run the async 'generate' method and prints the URLs of the generated images. ```python import asyncio from air import AsyncAIRefinery async def main(): client = AsyncAIRefinery(api_key="sk-...") response = await client.images.generate( prompt="A futuristic city at night with neon lights", model="black-forest-labs/FLUX.1-schnell", n=2 ) for i, image in enumerate(response.data): print(f"Image {i+1}: {image.url}") asyncio.run(main()) ``` -------------------------------- ### Asynchronous OCR Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/DocumentAnalysisClient.md Demonstrates how to perform asynchronous Optical Character Recognition (OCR) using the AsyncAIRefinery client. This example shows how to process an image file and print detected text with confidence scores. ```python import asyncio from air import AsyncAIRefinery async def main(): client = AsyncAIRefinery(api_key="sk-...") response = await client.document_analysis.ocr( image_path="/path/to/invoice.png", model="paddlex/PP-OCRv5_server" ) for result in response.results: print(f"{result.text} (confidence: {result.score:.2f})") asyncio.run(main()) ``` -------------------------------- ### Get SDK Version Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Import and print the SDK version. This is useful for debugging and verifying the installed SDK. ```python from air import __version__ print(__version__) # "1.31.3" ``` -------------------------------- ### ImagesClient Generate Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/ImagesClient.md Example of using the synchronous ImagesClient to generate an image with specified prompt, model, size, and count. It iterates through the response to print image URLs and check for base64 data. ```python from air import AIRefinery client = AIRefinery(api_key="sk-...") response = client.images.generate( prompt="A serene landscape with mountains and a lake at sunset", model="black-forest-labs/FLUX.1-schnell", n=1, size="1024x1024" ) for image in response.data: print(f"Image URL: {image.url}") if image.b64_json: print(f"Base64 data available: {len(image.b64_json)} chars") ``` -------------------------------- ### Create Audio Transcription (Async) Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AudioClient.md This example shows how to perform audio transcription asynchronously using `AsyncAIRefinery`. This is useful for I/O-bound operations to avoid blocking the event loop. ```python import asyncio from air import AsyncAIRefinery async def main(): client = AsyncAIRefinery(api_key="sk-...") response = await client.audio.transcriptions.create( model="openai/whisper-1", file="meeting_recording.m4a", language="en" ) print(response.text) asyncio.run(main()) ``` -------------------------------- ### Integrate PostgresAPI with Distiller Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/PostgresAPI.md Shows how to use PostgresAPI within a Distiller executor to allow agents to interact with databases. This example defines a database agent and then uses it within an AsyncAIRefinery client. ```python import asyncio from air import AsyncAIRefinery, PostgresAPI async def database_agent(query: str) -> str: db = PostgresAPI(db_config={ "host": "localhost", "port": 5432, "database": "analytics", "user": "analyst", "password": "pass" }) results, success = await db.execute_query(query) if success: return f"Query returned {len(results)} rows" else: return f"Query failed: {results}" async def main(): client = AsyncAIRefinery(api_key="sk-...") async with client.distiller( project="analytics", uuid="user-1", executor_dict={"DatabaseAgent": database_agent} ) as dc: responses = await dc.query("How many active users do we have?") async for response in responses: print(response["content"]) asyncio.run(main()) ``` -------------------------------- ### AsyncAIRefinery Usage Example Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AIRefinery.md Demonstrates common asynchronous operations using the AsyncAIRefinery client, including chat completions, embeddings generation, and image generation. Ensure the client is initialized with a valid API key. ```python import asyncio from air import AsyncAIRefinery async def main(): client = AsyncAIRefinery(api_key="sk-...") # Chat completions response = await client.chat.completions.create( model="openai/gpt-oss-120b", messages=[{"role": "user", "content": "Hello"}] ) print(response.choices[0].message.content) # Embeddings embeddings = await client.embeddings.create( model="intfloat/e5-mistral-7b-instruct", input=["Hello world"] ) print(embeddings.data[0].embedding[:5]) # Image generation images = await client.images.generate( model="black-forest-labs/FLUX.1-schnell", prompt="A sunset over mountains" ) print(images.data[0].url) asyncio.run(main()) ``` -------------------------------- ### Use Chat, Embeddings, and Image Generation Clients Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/INDEX.md Demonstrates how to use the chat completions, text embeddings, and image generation sub-clients with the asynchronous AI Refinery client. This example shows basic usage for each feature. ```python import asyncio async def main(): # Chat response = await client.chat.completions.create( model="openai/gpt-oss-120b", messages=[{"role": "user", "content": "Hello"}] ) print(response.choices[0].message.content) # Embeddings embeddings = await client.embeddings.create( model="intfloat/e5-mistral-7b-instruct", input=["Hello world"] ) print(embeddings.data[0].embedding[:5]) # Images images = await client.images.generate( model="black-forest-labs/FLUX.1-schnell", prompt="A sunset" ) print(images.data[0].url) asyncio.run(main()) ``` -------------------------------- ### Use Distiller with Custom Agents Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/INDEX.md Demonstrates how to use the Distiller client with custom agents for multi-agent processing. Ensure you have the 'air' library installed and an API key configured. ```python import asyncio from air import AsyncAIRefinery async def my_agent(query: str) -> str: return f"Processed: {query}" async def main(): client = AsyncAIRefinery(api_key="sk-...") async with client.distiller( project="my-agents", uuid="user-1", executor_dict={"CustomAgent": my_agent} ) as dc: responses = await dc.query("Hello") async for msg in responses: print(msg["content"]) asyncio.run(main()) ``` -------------------------------- ### Project Execution Commands Source: https://github.com/accenture/airefinery-sdk/blob/main/README.md Execute your AI Refinery project by navigating to the project directory and running the Python script. These commands initiate the project on the AI Refinery™ server and start your Distiller client. ```cmd cd sdk-project/ python example.py ``` -------------------------------- ### FineTuningClient.get Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/OtherClients.md Get details of a specific fine-tuning job using its job ID. Optional timeout and extra headers can be provided. ```APIDOC ## FineTuningClient.get ### Description Get details of a specific fine-tuning job. ### Method GET ### Endpoint /v1/fine-tuning/jobs/{job_id} ### Parameters #### Path Parameters - **job_id** (str) - Yes - Fine-tuning job ID. #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **id** (str) - The ID of the fine-tune job. - **status** (str) - The status of the fine-tune job. #### Response Example ```json { "id": "ftjob-12345", "status": "succeeded" } ``` ``` -------------------------------- ### Create Audio Transcription (Single File) Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AudioClient.md Use this snippet to transcribe a single audio file. Ensure you have the AIRefinery SDK installed and your API key configured. The `language` parameter is optional but recommended for accuracy. ```python from air import AIRefinery client = AIRefinery(api_key="sk-...") # Single file response = client.audio.transcriptions.create( model="openai/whisper-1", file="audio.mp3", language="en" ) print(f"Transcription: {response.text}") ``` -------------------------------- ### AIRefinery Client Initialization Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/INDEX.md Demonstrates how to initialize the asynchronous AIRefinery client with an API key. ```APIDOC ## Initialize a Client ```python from air import AsyncAIRefinery client = AsyncAIRefinery(api_key="sk-...") ``` ``` -------------------------------- ### Initialize Client with Custom Base URL Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Illustrates initializing the AsyncAIRefinery client, which will use the AIR_BASE_URL environment variable if set, otherwise it falls back to the default. ```python from air import AsyncAIRefinery client = AsyncAIRefinery(api_key="sk-...") ``` -------------------------------- ### Get API Key Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Retrieves details of a specific API key using its ID. ```APIDOC ## get api key ### Description Retrieve an API key by ID. ### Method GET ### Endpoint /organizations/{org_id}/api-keys/{key_id} ### Parameters #### Path Parameters - **org_id** (str) - Yes - The ID of the organization. - **key_id** (str) - Yes - API key ID. #### Query Parameters - **timeout** (int | None) - No - Timeout in seconds for the request. - **extra_headers** (dict | None) - No - Additional headers to send with the request. ### Response #### Success Response (200) - **APIKey**: The API key object. #### Response Example ```json { "id": "key-abc", "name": "prod-integration", "description": "API key for production services" } ``` ``` -------------------------------- ### Get User by Email Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Retrieves a specific user's details using their email address. ```APIDOC ## get user by email ### Description Retrieve a user by email address. ### Method GET ### Endpoint /organizations/{org_id}/users?email={email} ### Parameters #### Path Parameters - **org_id** (str) - Yes - The ID of the organization. #### Query Parameters - **email** (str) - Yes - User email address. - **timeout** (int | None) - No - Timeout in seconds for the request. - **extra_headers** (dict | None) - No - Additional headers to send with the request. ### Response #### Success Response (200) - **User**: The user object if found. #### Response Example ```json { "id": "user-123", "email": "user@example.com", "name": "John Doe" } ``` #### Success Response (404) - **None**: Returned if the user is not found. ``` -------------------------------- ### Initialize Client with API Key Environment Variable Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Demonstrates how to retrieve the API key from the AIREFINERY_API_KEY environment variable and use it to initialize the AsyncAIRefinery client. ```python import os from air import AsyncAIRefinery api_key = os.getenv("AIREFINERY_API_KEY") client = AsyncAIRefinery(api_key=api_key) ``` -------------------------------- ### Initialize AsyncGovernanceClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Initializes the asynchronous governance client. Use this for asynchronous operations. Requires an API key. ```python class AsyncGovernanceClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, ): ``` -------------------------------- ### Get User by ID Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Retrieves a specific user's details using their unique user ID. ```APIDOC ## get user by id ### Description Retrieve a user by ID. ### Method GET ### Endpoint /organizations/{org_id}/users/{user_id} ### Parameters #### Path Parameters - **org_id** (str) - Yes - The ID of the organization. - **user_id** (str) - Yes - User ID. #### Query Parameters - **timeout** (int | None) - No - Timeout in seconds for the request. - **extra_headers** (dict | None) - No - Additional headers to send with the request. ### Response #### Success Response (200) - **User**: The user object. #### Response Example ```json { "id": "user-123", "email": "user@example.com", "name": "John Doe" } ``` ``` -------------------------------- ### Initialize Client with Default Headers Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Illustrates initializing the AsyncAIRefinery client with default_headers. These headers will be included in every request made by the client. ```python from air import AsyncAIRefinery client = AsyncAIRefinery( api_key="sk-...", default_headers={ "X-Client-Version": "1.2.3", "X-Request-Source": "my-app" } ) # These headers are included in every request response = await client.chat.completions.create( model="openai/gpt-oss-120b", messages=[...] ) ``` -------------------------------- ### Using ChatClient and AsyncChatClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/ChatClient.md Demonstrates how to instantiate and use both synchronous and asynchronous chat clients to create chat completions. Ensure you have the necessary imports for both client types and asyncio if using the async client. ```python from air.chat import ChatClient, AsyncChatClient # Sync sync_client = ChatClient(api_key="sk-...") response = sync_client.completions.create( model="openai/gpt-oss-120b", messages=[...] ) # Async import asyncio async_client = AsyncChatClient(api_key="sk-...") response = await async_client.completions.create( model="openai/gpt-oss-120b", messages=[...] ) ``` -------------------------------- ### AIRefinery Sub-client Usage Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/INDEX.md Shows examples of using sub-clients for Chat Completions, Embeddings, and Image Generation with the AIRefinery SDK. ```APIDOC ## Use a Sub-client ```python import asyncio async def main(): # Chat response = await client.chat.completions.create( model="openai/gpt-oss-120b", messages=[{"role": "user", "content": "Hello"}] ) print(response.choices[0].message.content) # Embeddings embeddings = await client.embeddings.create( model="intfloat/e5-mistral-7b-instruct", input=["Hello world"] ) print(embeddings.data[0].embedding[:5]) # Images images = await client.images.generate( model="black-forest-labs/FLUX.1-schnell", prompt="A sunset" ) print(images.data[0].url) asyncio.run(main()) ``` ``` -------------------------------- ### Configure PostgreSQL Connection with Dictionary Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Set up a PostgreSQL connection by providing a dictionary containing database credentials and host information to `PostgresAPI`. ```python db_config = { "host": "db.example.com", # Hostname or IP "port": 5432, # Port number (default: 5432) "database": "myapp", # Database name "user": "db_user", # Username "password": "db_password" # Password } from air import PostgresAPI db = PostgresAPI(db_config=db_config) ``` -------------------------------- ### Initialize KnowledgeClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/KnowledgeClient.md Constructor for the synchronous client. Use this for document processing services. ```python class KnowledgeClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, ): ``` -------------------------------- ### Initialize GovernanceClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Initializes the synchronous governance client. Use this for synchronous operations. Requires an API key. ```python class GovernanceClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, ): ``` -------------------------------- ### Initialize Client with Explicit Base URL Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Shows how to initialize the AsyncAIRefinery client by explicitly providing the base_url parameter, overriding any environment variable settings. ```python from air import AsyncAIRefinery client = AsyncAIRefinery( api_key="sk-...", base_url="https://api.example.com" ) ``` -------------------------------- ### Get Async Knowledge Graph Client Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/KnowledgeClient.md Retrieves an async-safe client for knowledge graph operations. This method is part of the AsyncKnowledgeClient. ```python async def get_graph() -> KnowledgeGraphClient: ``` -------------------------------- ### AsyncDocumentAnalysisClient Initialization Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/DocumentAnalysisClient.md Shows how to initialize the asynchronous client for document analysis operations. Requires an API key and optionally accepts a base URL. ```python class AsyncDocumentAnalysisClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, ): ``` -------------------------------- ### Audio Client Initialization Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AudioClient.md Initializes synchronous and asynchronous audio clients. These clients aggregate text-to-speech and transcription sub-clients. ```python class AsyncAudio: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, **kwargs ): self.speech = AsyncTTSClient(...) self.transcriptions = AsyncASRClient(...) class Audio: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, **kwargs ): self.speech = TTSClient(...) self.transcriptions = ASRClient(...) ``` -------------------------------- ### FineTuningClient.create Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/OtherClients.md Create a fine-tuning job to adapt a model to your data. Requires specifying the base model, training file, and optionally a validation file and hyperparameters. ```APIDOC ## FineTuningClient.create ### Description Create a fine-tuning job to adapt a model to your data. ### Method POST ### Endpoint /v1/fine-tuning/jobs ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model** (str) - Yes - Base model to fine-tune. - **training_file** (str) - Yes - Path to JSONL training data file. - **validation_file** (str | None) - No - Path to JSONL validation data file. - **hyperparameters** (dict | None) - No - Fine-tuning hyperparameters (learning_rate, epochs, etc.). - **timeout** (float | None) - No - Request timeout in seconds. - **extra_headers** (dict[str, str] | None) - No - Per-request headers. ### Request Example ```json { "model": "openai/gpt-oss-120b", "training_file": "training_data.jsonl", "validation_file": "validation_data.jsonl", "hyperparameters": { "learning_rate": 0.0001, "epochs": 3 } } ``` ### Response #### Success Response (200) - **id** (str) - The ID of the fine-tune job. - **status** (str) - The status of the fine-tune job. #### Response Example ```json { "id": "ftjob-12345", "status": "pending" } ``` ``` -------------------------------- ### Initialize PostgresAPI Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/PostgresAPI.md Initialize the PostgreSQL API with database configuration. The configuration dictionary must include host, port, database, user, and password. ```python class PostgresAPI: def __init__(self, db_config: dict) -> None: ``` ```python from air import PostgresAPI db_config = { "host": "db.example.com", "port": 5432, "database": "myapp", "user": "db_user", "password": "db_password" } db = PostgresAPI(db_config=db_config) ``` -------------------------------- ### Initialize AsyncModelsClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/ModelsClient.md Instantiate the asynchronous client for listing models. Similar to the synchronous client, it requires an API key and supports optional base URL and default headers. ```python class AsyncModelsClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, ): ``` -------------------------------- ### Initialize AIRefinery Client Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AIRefinery.md Instantiates the AIRefinery client with an API key. This client aggregates various AI service sub-clients. ```python class AIRefinery: def __init__( self, api_key: str | TokenProvider, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, **kwargs ) -> None: ``` -------------------------------- ### Handle HTTPError from Governance Client Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/errors.md This example shows how to catch and handle standard HTTP errors raised by the `requests` library when interacting with the governance client. It prints the status code and response text for debugging API issues. ```python from air import AIRefinery import requests client = AIRefinery(api_key="sk-...") try: orgs = client.governance.organizations.list() except requests.HTTPError as e: print(f"API error {e.response.status_code}: {e.response.text}") ``` -------------------------------- ### Initialize Client with Token Provider Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Demonstrates initializing the AsyncAIRefinery client with a custom TokenProvider object, which is useful for dynamic token retrieval like rotating keys or OAuth tokens. ```python from air import AsyncAIRefinery from air.auth import TokenProvider # Token provider (useful for rotating keys, OAuth tokens, etc.) class MyTokenProvider(TokenProvider): def token(self) -> str: return fetch_fresh_token() async def token_async(self) -> str: return await fetch_fresh_token_async() client = AsyncAIRefinery(api_key=MyTokenProvider()) ``` -------------------------------- ### List Organizations (Sync and Async) Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Shows how to list organizations using both the synchronous and asynchronous governance clients. The asynchronous version requires 'await'. ```python # Sync orgs = client.governance.organizations.list() # Async orgs = await client.governance.organizations.list() ``` -------------------------------- ### KnowledgeClient Constructor Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/KnowledgeClient.md Initializes the synchronous client for knowledge services. It requires an API key and optionally accepts a base URL and default headers. ```APIDOC ## KnowledgeClient Constructor ### Description Initializes the synchronous client for knowledge services including document processing. It requires an API key and optionally accepts a base URL and default headers. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **api_key** (`str | TokenProvider`) - Required - API credential. - **base_url** (`str`) - Optional - API endpoint. Defaults to `https://api.airefinery.accenture.com`. - **default_headers** (`dict[str, str] | None`) - Optional - Headers for all requests. Defaults to None. ``` -------------------------------- ### AsyncGovernanceClient Initialization Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Initializes the asynchronous governance client. This client aggregates sub-clients for various resource types. ```APIDOC ## AsyncGovernanceClient ### Description Asynchronous governance client aggregating sub-clients for different resource types. ### Parameters #### Parameters - **api_key** (str | TokenProvider) - Required - API credential. - **base_url** (str) - Optional - API endpoint. Defaults to `https://api.airefinery.accenture.com`. - **default_headers** (dict[str, str] | None) - Optional - Headers for all requests. Defaults to None. ``` -------------------------------- ### FineTuningClient.list Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/OtherClients.md List all fine-tuning jobs. This method can accept optional timeout and extra headers. ```APIDOC ## FineTuningClient.list ### Description List all fine-tuning jobs. ### Method GET ### Endpoint /v1/fine-tuning/jobs ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **data** (list) - A list of fine-tune jobs. - **id** (str) - The ID of the fine-tune job. - **status** (str) - The status of the fine-tune job. #### Response Example ```json { "data": [ { "id": "ftjob-12345", "status": "succeeded" } ] } ``` ``` -------------------------------- ### Initialize Client with String API Key Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Initializes the AsyncAIRefinery client using a raw API key string for authentication. This key is placed in the Authorization: Bearer header. ```python from air import AsyncAIRefinery # String API key client = AsyncAIRefinery(api_key="sk-...") ``` -------------------------------- ### Initialize DocumentAnalysisClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/DocumentAnalysisClient.md Instantiates the synchronous client for document analysis operations. Requires an API key and optionally accepts a base URL. ```python class DocumentAnalysisClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, ): ``` -------------------------------- ### Initialize ModelsClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/ModelsClient.md Instantiate the synchronous client for querying models. Requires an API key and optionally accepts a base URL and default headers. ```python class ModelsClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, ): ``` -------------------------------- ### Create Knowledge Graph Project Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/KnowledgeClient.md Asynchronously creates a new knowledge graph project. Requires a dictionary containing the knowledge graph configuration. ```python async def create_project(graph_config: dict) -> GraphProject: # ... implementation details ... ``` -------------------------------- ### Initialize AsyncAIRefinery Client Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AIRefinery.md Shows how to initialize the asynchronous AIRefinery client with an API key. This client aggregates all service sub-clients under a single interface for asynchronous operations. ```python class AsyncAIRefinery: def __init__( self, api_key: str | TokenProvider, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, **kwargs ) -> None: ``` -------------------------------- ### Initialize Async Distiller with Project and UUID Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Use the `client.distiller` context manager to initialize a distiller session with a project name and a unique user identifier. ```python import asyncio from air import AsyncAIRefinery async def main(): client = AsyncAIRefinery(api_key="sk-...") async with client.distiller( project="my-agent-system", uuid="user-1" ) as dc: responses = await dc.query("Hello") asyncio.run(main()) ``` -------------------------------- ### ImagesClient Initialization Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/ImagesClient.md Initializes the synchronous ImagesClient with API key and optional base URL or default headers. ```python class ImagesClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, ): ``` -------------------------------- ### Initialize AsyncEmbeddingsClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/EmbeddingsClient.md Instantiate the asynchronous client for creating text embeddings. Similar to the synchronous client, it requires an API key and can be configured with a base URL and default headers. ```python class AsyncEmbeddingsClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, ): ... ``` -------------------------------- ### GovernanceClient Initialization Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/GovernanceClient.md Initializes the synchronous governance client. This client aggregates sub-clients for various resource types. ```APIDOC ## GovernanceClient ### Description Synchronous governance client aggregating sub-clients. ### Parameters #### Parameters - **api_key** (str | TokenProvider) - Required - API credential. - **base_url** (str) - Optional - API endpoint. Defaults to `https://api.airefinery.accenture.com`. - **default_headers** (dict[str, str] | None) - Optional - Headers for all requests. Defaults to None. **Note**: Parameters are the same as `AsyncGovernanceClient`. ``` -------------------------------- ### Authenticate with Token Provider Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/INDEX.md Demonstrates authentication using a custom token provider for dynamic token retrieval. Implement the 'token' and 'token_async' methods to fetch tokens as needed. ```python from air import AsyncAIRefinery from air.auth import TokenProvider class MyTokenProvider(TokenProvider): def token(self) -> str: return get_fresh_token() async def token_async(self) -> str: return await get_fresh_token_async() client = AsyncAIRefinery(api_key=MyTokenProvider()) ``` -------------------------------- ### Initialize AsyncDistillerClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/DistillerClient.md Initializes the asynchronous client for AI Refinery's Distiller framework. Requires an API key and optionally accepts a base URL and other configuration parameters. ```python class AsyncDistillerClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, **kwargs ) -> None: ``` -------------------------------- ### create_project Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/KnowledgeClient.md Creates a new knowledge graph project with the specified configuration. This is an async-only operation. ```APIDOC ## create_project(graph_config: dict) -> GraphProject ### Description Create a knowledge graph project. ### Method Signature ```python async def create_project(graph_config: dict) -> GraphProject: ``` ### Parameters #### Path Parameters - **graph_config** (dict) - Yes - Knowledge graph configuration. ### Returns - `GraphProject`: Created graph project. ``` -------------------------------- ### Create Project Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/DistillerClient.md Creates a new distiller project using either a YAML config file or a JSON configuration dictionary. Returns True on success, False otherwise. ```APIDOC ## create_project ### Description Create a distiller project from YAML or JSON config. ### Parameters - **project** (str) - Required - Project name (alphanumeric, hyphens, underscores). - **config_path** (str | None) - Optional - Path to YAML config file. - **json_config** (dict | None) - Optional - JSON config dict. ### Returns - **bool**: True if successful, False otherwise. ### Raises - **ValueError**: Neither config_path nor json_config provided. - **ProjectCreationError**: Server returns error or invalid response. ### Example ```python import asyncio async def main(): client = AsyncAIRefinery(api_key="sk-...") success = client.distiller.create_project( project="my-agent-system", config_path="config.yaml" ) print("Project created" if success else "Failed") asyncio.run(main()) ``` ``` -------------------------------- ### AsyncKnowledgeClient Constructor Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/KnowledgeClient.md Initializes the asynchronous client for knowledge services. It requires an API key and optionally accepts a base URL and default headers. ```APIDOC ## AsyncKnowledgeClient Constructor ### Description Initializes the asynchronous client for knowledge services including knowledge graph operations. It requires an API key and optionally accepts a base URL and default headers. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **api_key** (`str | TokenProvider`) - Required - API credential. - **base_url** (`str`) - Optional - API endpoint. Defaults to `https://api.airefinery.accenture.com`. - **default_headers** (`dict[str, str] | None`) - Optional - Headers for all requests. Defaults to None. ``` -------------------------------- ### List Traces with TracesClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/OtherClients.md List traces for debugging and observability. Instantiate the AIRefinery client with your API key to use this method. ```python from air import AIRefinery client = AIRefinery(api_key="sk-...") traces = client.traces.list() for trace in traces.data: print(f"Trace ID: {trace.id}") print(f"Duration: {trace.duration_ms}ms") ``` -------------------------------- ### AsyncImagesClient Initialization Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/ImagesClient.md Initializes the asynchronous AsyncImagesClient with API key and optional base URL or default headers. Parameters are the same as ImagesClient. ```python class AsyncImagesClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, ): ``` -------------------------------- ### AsyncChatClient Initialization Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/ChatClient.md Initializes the asynchronous AsyncChatClient. This client provides access to chat completions through its `completions` sub-client. ```APIDOC ## AsyncChatClient ### Description Initializes the asynchronous AsyncChatClient. This client provides access to chat completions through its `completions` sub-client. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | api_key | `str \| TokenProvider` | Yes | — | API credential. | | base_url | str | No | `https://api.airefinery.accenture.com` | API endpoint. | | default_headers | `dict[str, str] \| None` | No | None | Headers for all requests. | ### Example ```python from air.chat import AsyncChatClient import asyncio async_client = AsyncChatClient(api_key="sk-...") response = await async_client.completions.create( model="openai/gpt-oss-120b", messages=[...] ) ``` ``` -------------------------------- ### Initialize AsyncKnowledgeClient Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/KnowledgeClient.md Constructor for the asynchronous client. Use this for knowledge graph operations. ```python class AsyncKnowledgeClient: def __init__( self, api_key: str | TokenProvider, *, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, ): ``` -------------------------------- ### AIRefinery Client Initialization Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/AIRefinery.md Initializes the AIRefinery client with an API key and optional base URL and headers. This client aggregates various AI service sub-clients. ```APIDOC ## AIRefinery Client Initialization ### Description Initializes the main AIRefinery client. This client acts as a unified interface for various AI services, aggregating sub-clients for chat, embeddings, audio, models, images, compression, knowledge, fine-tuning, moderations, governance, traces, logs, and metrics. Distiller functionality is async-only. ### Method ```python AIRefinery(api_key: str | TokenProvider, base_url: str = BASE_URL, default_headers: dict[str, str] | None = None, **kwargs) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **api_key** (`str` | `TokenProvider`) - Required - API key or token provider. If `str`, used as-is. If `TokenProvider`, `token()` and `token_async()` methods called before each request. - **base_url** (`str`) - Optional - API endpoint URL. Defaults to `https://api.airefinery.accenture.com`. Can be overridden via `AIR_BASE_URL` environment variable. - **default_headers** (`dict[str, str]` | `None`) - Optional - Headers applied to every request from all sub-clients. - **kwargs** (`Any`) - Optional - Additional configuration parameters. ### Sub-clients - **`chat`**: `ChatClient` - For chat completions (`/v1/chat/completions`). - **`embeddings`**: `EmbeddingsClient` - For text embeddings (`/v1/embeddings`). - **`audio`**: `Audio` - For speech synthesis and transcription. - **`models`**: `ModelsClient` - For model listing (`/v1/models`). - **`images`**: `ImagesClient` - For image generation (`/v1/images/generations`). - **`compression`**: `CompressionClient` - For text compression. - **`knowledge`**: `KnowledgeClient` - For document processing and knowledge services. - **`fine_tuning`**: `FineTuningClient` - For model fine-tuning operations. - **`moderations`**: `ModerationsClient` - For content moderation checks. - **`governance`**: `GovernanceClient` - For org, user, and workspace management. - **`traces`**: `TracesClient` - For distributed trace observability. - **`logs`**: `LogsClient` - For log aggregation and queries. - **`metrics`**: `MetricsClient` - For metrics collection and analysis. ### Example ```python from air import AIRefinery def main(): client = AIRefinery(api_key="sk-...") # Chat completions response = client.chat.completions.create( model="openai/gpt-oss-120b", messages=[{"role": "user", "content": "Hello"}] ) print(response.choices[0].message.content) # Embeddings embeddings = client.embeddings.create( model="intfloat/e5-mistral-7b-instruct", input=["Hello world"] ) print(embeddings.data[0].embedding[:5]) # Models list models = client.models.list() for model in models.data: print(f"- {model.id}") main() ``` ### Distiller Access Accessing `client.distiller` or `client.realtime_distiller` raises `NotImplementedError`. Use `AsyncAIRefinery` instead. ``` -------------------------------- ### Print SDK Cache Directory Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/configuration.md Shows how to print the current SDK cache directory path, which is a pathlib.Path instance. ```python from air import CACHE_DIR print(CACHE_DIR) ``` -------------------------------- ### Initialize AsyncDistillerClient with a context manager Source: https://github.com/accenture/airefinery-sdk/blob/main/_autodocs/api-reference/DistillerClient.md Use the `client.distiller` method as an asynchronous context manager to establish an interactive distiller session. This is useful for setting up custom agents with `executor_dict` for specific tasks. ```python import asyncio from air import AsyncAIRefinery async def my_agent(query: str) -> str: return f"Processed: {query}" async def main(): client = AsyncAIRefinery(api_key="sk-...") try: async with client.distiller( project="my-agent-system", uuid="user-123", executor_dict={"MyCustomAgent": my_agent} ) as dc: responses = await dc.query("What is 2+2?") async for response in responses: print(response["content"]) except Exception as e: print(f"Error: {e}") asyncio.run(main()) ```