### Build and Install SDK from Source Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Build a distributable version of the library by creating wheel files, then install it using pip. ```sh uv build ``` ```sh python -m build ``` ```sh pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Add and Make Example Executable Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Add new examples to the `examples/` directory and make them executable. The generator will not modify files in this directory. ```python # add an example to examples/.py #!/usr/bin/env -S uv run python … ``` ```sh chmod +x examples/.py ``` -------------------------------- ### Install SDK from Git Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Install the Dedalus SDK Python package directly from a Git repository using pip. ```sh pip install git+ssh://git@github.com/dedalus-labs/dedalus-sdk-python.git ``` -------------------------------- ### Install aiohttp for Async Client Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Install the aiohttp library to enable it as the HTTP backend for the asynchronous Dedalus client, potentially improving concurrency performance. ```sh pip install aiohttp ``` -------------------------------- ### Start Prism Mock Server Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Start the Prism mock server to run API resource tests that are marked as skipped by default. This uses the spec URL from .stats.yml. ```sh ./scripts/mock --daemon ``` -------------------------------- ### Install Dependencies without uv Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Use this command to install development dependencies using pip if uv is not installed. Ensure the Python version specified in `.python-version` is met. ```sh pip install -r requirements-dev.lock ``` -------------------------------- ### Install Dedalus Python SDK Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Install the Dedalus Python library from PyPI. Ensure you are using Python 3.9 or newer. ```sh pip install dedalus_labs ``` -------------------------------- ### Bootstrap Project Environment with uv Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Run this script to automatically provision a Python environment using uv. Alternatively, install uv manually and run `uv sync --all-extras`. ```sh ./scripts/bootstrap ``` ```sh uv sync --all-extras ``` -------------------------------- ### Run Prism Mock Server Manually with bun Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Manually start the Prism mock server using bun. This command fetches the OpenAPI spec URL from .stats.yml. ```sh bunx @stainless-api/prism-cli@5.15.0 prism mock \ "$(grep openapi_spec_url .stats.yml | cut -d' ' -f2)" ``` -------------------------------- ### Run Prism Mock Server Manually with npx Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Manually start the Prism mock server using npx if bun is not available. This command fetches the OpenAPI spec URL from .stats.yml. ```sh npx @stainless-api/prism-cli@5.15.0 prism mock \ "$(grep openapi_spec_url .stats.yml | cut -d' ' -f2)" ``` -------------------------------- ### Asynchronous Client Usage Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Instantiate the asynchronous Dedalus client and make a chat completion request using await. This example demonstrates running the async main function. ```python import os import asyncio from dedalus_labs import AsyncDedalus client = AsyncDedalus( api_key=os.environ.get("DEDALUS_API_KEY"), # This is the default and can be omitted # defaults to "production". environment="development", ) async def main() -> None: chat_completion = await client.chat.completions.create( model="openai/gpt-5-nano", messages=[ { "role": "system", "content": "You are Stephen Dedalus. Respond in morose Joycean malaise.", }, { "role": "user", "content": "Hello, how are you today?", }, ], ) print(chat_completion.id) asyncio.run(main()) ``` -------------------------------- ### Initialize Asynchronous Dedalus Client Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Initialize the asynchronous Dedalus client for concurrent operations. Use an async context manager for proper resource cleanup. This example demonstrates a basic chat completion. ```python import os import asyncio from dedalus_labs import AsyncDedalus async def main(): client = AsyncDedalus( api_key=os.environ.get("DEDALUS_API_KEY"), environment="production", ) # Use async context manager for proper resource cleanup async with client: completion = await client.chat.completions.create( model="openai/gpt-5-nano", messages=[{"role": "user", "content": "Hello!"}], ) print(completion.choices[0].message.content) asyncio.run(main()) ``` -------------------------------- ### List Models Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Retrieves a list of available models. This method corresponds to the GET /v1/models API endpoint. ```python client.models.list() -> ListModelsResponse ``` -------------------------------- ### Streaming Chat Completions Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Stream chat completions using Server-Sent Events for real-time response delivery. Process streaming chunks as they arrive. Includes both synchronous and asynchronous streaming examples. ```python from dedalus_labs import Dedalus client = Dedalus() stream = client.chat.completions.create( model="openai/gpt-5-nano", stream=True, messages=[ {"role": "system", "content": "You are a creative writer."}, {"role": "user", "content": "Write a short poem about coding."}, ], ) # Process streaming chunks for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True) print() # Final newline # Async streaming import asyncio from dedalus_labs import AsyncDedalus async def stream_async(): client = AsyncDedalus() stream = await client.chat.completions.create( model="openai/gpt-5-nano", stream=True, messages=[{"role": "user", "content": "Tell me a joke."}] ) async for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="") asyncio.run(stream_async()) ``` -------------------------------- ### Set Default Headers in Dedalus SDK Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Customize default headers sent with all requests. This example overrides the default `User-Agent` header. ```python from dedalus_labs import Dedalus client = Dedalus( default_headers={"User-Agent": "My-Custom-Value"}, ) ``` -------------------------------- ### Determine Installed Dedalus SDK Version Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Use this snippet to check the version of the Dedalus SDK currently active in your Python environment. Ensure the 'dedalus_labs' package is installed. ```python import dedalus_labs print(dedalus_labs.__version__) ``` -------------------------------- ### Access Raw Response Data with Dedalus SDK Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Use `.with_raw_response.` before an HTTP method to access the raw `APIResponse` object, which includes headers. Call `.parse()` on the response to get the structured completion object. ```python from dedalus_labs import Dedalus client = Dedalus() response = client.chat.completions.with_raw_response.create( model="openai/gpt-5-nano", messages=[ { "role": "system", "content": "You are Stephen Dedalus. Respond in morose Joycean malaise.", }, { "role": "user", "content": "Hello, how are you today?", } ], ) print(response.headers.get('X-My-Header')) completion = response.parse() # get the object that `chat.completions.create()` would have returned print(completion.id) ``` -------------------------------- ### Retrieve Model Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Retrieves details for a specific model by its ID. This method corresponds to the GET /v1/models/{model_id} API endpoint. ```python client.models.retrieve(model_id) -> Model ``` -------------------------------- ### Use Nested Parameters for Audio Configuration Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Demonstrates how to pass nested parameters, such as audio configuration, when creating a chat completion. The 'audio' parameter expects a dictionary with format and voice details. ```python from dedalus_labs import Dedalus client = Dedalus() chat_completion = client.chat.completions.create( model="openai/gpt-5", audio={ "format": "wav", "voice": "string", }, ) print(chat_completion.audio) ``` -------------------------------- ### Instantiate Async Client and Create Chat Completion Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Instantiate the asynchronous client with an API key and make a chat completion request. Ensure the DEDALUS_API_KEY environment variable is set. ```python import os import asyncio from dedalus_labs import DefaultAioHttpClient from dedalus_labs import AsyncDedalus async def main() -> None: async with AsyncDedalus( api_key=os.environ.get("DEDALUS_API_KEY"), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: chat_completion = await client.chat.completions.create( model="openai/gpt-5-nano", messages=[ { "role": "system", "content": "You are Stephen Dedalus. Respond in morose Joycean malaise.", }, { "role": "user", "content": "Hello, how are you today?", }, ], ) print(chat_completion.id) asyncio.run(main()) ``` -------------------------------- ### Run Tests with uv Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Execute all project tests using uv. This command utilizes respx mocking and does not require a running server. ```sh uv run pytest ``` -------------------------------- ### POST /v1/chat/completions Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md The `create` method allows you to send a prompt to the chat completions API and receive a text completion. It supports various parameters for controlling the generation process. ```APIDOC ## POST /v1/chat/completions ### Description Creates a chat completion request. ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Request Body - **params** (ChatCompletionCreateParams) - Required - Parameters for the chat completion request. ### Request Example ```json { "model": "gpt-3.5-turbo", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"} ] } ``` ### Response #### Success Response (200) - **ChatCompletion** - The response object containing the completion. #### Response Example ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1677652288, "model": "gpt-3.5-turbo-0613", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 10, "completion_tokens": 15, "total_tokens": 25 } } ``` ``` -------------------------------- ### Initialize Synchronous Dedalus Client Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Initialize the synchronous Dedalus client. Configure with an API key, environment, retry count, and timeout. The API key can be omitted if set in the environment. ```python import os from dedalus_labs import Dedalus # Synchronous client client = Dedalus( api_key=os.environ.get("DEDALUS_API_KEY"), # Can also be omitted if set in env environment="production", # or "development" max_retries=2, # Default retry count timeout=60.0, # Request timeout in seconds ) # Access SDK version import dedalus_labs print(dedalus_labs.__version__) # Output: 0.3.0 ``` -------------------------------- ### Custom HTTP Client Configuration with Proxies and Transports Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Configure custom base URLs, proxies, and transports for the HTTP client. This allows for network-level customization. ```python import httpx from dedalus_labs import Dedalus, DefaultHttpxClient # Custom base URL and proxy client = Dedalus( base_url="https://custom-api.example.com", http_client=DefaultHttpxClient( proxy="http://proxy.example.com:8080", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### List and Retrieve Models Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Manage available AI models by listing all models or retrieving details for a specific model. ```python from dedalus_labs import Dedalus client = Dedalus() # List all available models models = client.models.list() for model in models.data: print(f"Model: {model.id}, Owner: {model.owned_by}") ``` ```python # Retrieve specific model details model = client.models.retrieve("openai/gpt-5-nano") print(f"Model ID: {model.id}") print(f"Created: {model.created}") ``` -------------------------------- ### Publish Package Manually Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Manually release a package to PyPI by running the `bin/publish-pypi` script with a `PYPI_TOKEN` set in the environment. ```sh bin/publish-pypi ``` -------------------------------- ### Lint Repository Code Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Run the linting process for the repository code using ruff. ```sh ./scripts/lint ``` -------------------------------- ### Chat Completions with MCP Server Integration Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Integrate with Model Context Protocol (MCP) servers for extended tool capabilities and server-side execution. You can specify servers by slug or URL and provide credentials if necessary. ```python from dedalus_labs import Dedalus client = Dedalus() # Use MCP servers by slug or URL completion = client.chat.completions.create( model="openai/gpt-5-nano", messages=[ {"role": "user", "content": "Search for recent Python news"} ], mcp_servers=["search-server", "https://custom-mcp.example.com"], automatic_tool_execution=True, # Execute tools server-side credentials={ "search-server": { "type": "api_key", "api_key": "your-api-key", } }, ) print(completion.choices[0].message.content) ``` -------------------------------- ### Sync Context Manager for HTTP Client Cleanup Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Use `with Dedalus() as client:` for automatic cleanup of the synchronous HTTP client. Ensures connections are properly closed. ```python from dedalus_labs import Dedalus # Sync context manager with Dedalus() as client: completion = client.chat.completions.create( model="openai/gpt-5-nano", messages=[{"role": "user", "content": "Hello!"}], ) print(completion.choices[0].message.content) # HTTP client automatically closed ``` -------------------------------- ### Async Context Manager for HTTP Client Cleanup Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Use `async with AsyncDedalus() as client:` for automatic cleanup of the asynchronous HTTP client. Essential for concurrent applications. ```python from dedalus_labs import AsyncDedalus import asyncio # Async context manager async def main(): async with AsyncDedalus() as client: completion = await client.chat.completions.create( model="openai/gpt-5-nano", messages=[{"role": "user", "content": "Hello!"}], ) print(completion.choices[0].message.content) asyncio.run(main()) ``` -------------------------------- ### Custom HTTP Client Configuration with Default Headers Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Set default headers for all requests made by the client. This is useful for adding authentication tokens or custom metadata. ```python client = Dedalus( default_headers={ "X-Custom-Header": "custom-value", "User-Agent": "MyApp/1.0", }, ) ``` -------------------------------- ### Chat Completions with Tool/Function Calling Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Define tools using JSON schemas to enable models to call functions. The model can then suggest function calls based on user input. You need to parse the arguments and execute the function yourself. ```python from dedalus_labs import Dedalus client = Dedalus() tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City and state, e.g., San Francisco, CA", }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], }, }, "required": ["location"], }, }, } ] completion = client.chat.completions.create( model="openai/gpt-5-nano", messages=[{"role": "user", "content": "What's the weather in Tokyo?"}], tools=tools, tool_choice="auto", ) # Check if model wants to call a tool message = completion.choices[0].message if message.tool_calls: for tool_call in message.tool_calls: print(f"Function: {tool_call.function.name}") print(f"Arguments: {tool_call.function.arguments}") # Parse arguments and execute function # Then send results back to continue conversation ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Manually activate the virtual environment to run scripts without the `uv run` prefix. This method is compatible with standard Python virtual environments. ```sh source .venv/bin/activate ``` -------------------------------- ### Configure Dedalus HTTP Client with Proxies and Transports Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Customize the underlying `httpx` client by passing a `DefaultHttpxClient` instance to the `Dedalus` constructor. This allows configuration of proxies, transports, and other advanced `httpx` features. ```python import httpx from dedalus_labs import Dedalus, DefaultHttpxClient client = Dedalus( # Or use the `DEDALUS_BASE_URL` env var base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Handle Streaming Responses with Sync Client Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Create a chat completion request with streaming enabled using the synchronous client. Iterate over the stream to process responses as they arrive. ```python from dedalus_labs import Dedalus client = Dedalus() stream = client.chat.completions.create( model="openai/gpt-5-nano", stream=True, messages=[ { "role": "system", "content": "You are Stephen Dedalus. Respond in morose Joycean malaise.", }, { "role": "user", "content": "What do you think of artificial intelligence?", }, ], ) for chat_completion in stream: print(chat_completion.id) ``` -------------------------------- ### Create Chat Completion Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Initiates a chat completion request using the client. This method corresponds to the POST /v1/chat/completions API endpoint. Pass parameters as a dictionary to the create method. ```python client.chat.completions.create(**params) ``` -------------------------------- ### Handle Streaming Responses with Async Client Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Create a chat completion request with streaming enabled using the asynchronous client. Use an async for loop to process streamed responses. ```python from dedalus_labs import AsyncDedalus client = AsyncDedalus() stream = await client.chat.completions.create( model="openai/gpt-5-nano", stream=True, messages=[ { "role": "system", "content": "You are Stephen Dedalus. Respond in morose Joycean malaise.", }, { "role": "user", "content": "What do you think of artificial intelligence?", }, ], ) async for chat_completion in stream: print(chat_completion.id) ``` -------------------------------- ### Format and Fix Code with ruff Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Automatically format and fix all ruff issues in the repository code. ```sh ./scripts/format ``` -------------------------------- ### Chat Completions with Pydantic Structured Outputs Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Utilize the parse() method to automatically parse chat completion responses into Pydantic models. Define Pydantic models for expected data structures. Access parsed data directly from the response. ```python from pydantic import BaseModel from dedalus_labs import Dedalus class PersonInfo(BaseModel): name: str age: int occupation: str class MovieReview(BaseModel): title: str rating: float summary: str pros: list[str] cons: list[str] client = Dedalus() # Parse response into Pydantic model completion = client.chat.completions.parse( model="openai/gpt-4o-mini", messages=[ {"role": "user", "content": "Tell me about Alice, a 28-year-old software engineer."} ], response_format=PersonInfo, ) # Access parsed data directly person = completion.choices[0].message.parsed print(f"Name: {person.name}") # "Alice" print(f"Age: {person.age}") # 28 print(f"Occupation: {person.occupation}") # "software engineer" ``` -------------------------------- ### Import Chat Completion Types Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Imports all necessary types for chat completions from the dedalus_labs.types.chat module. Ensure these imports are present before using chat completion functionalities. ```python from dedalus_labs.types.chat import ( Audio, ChatCompletion, ChatCompletionAssistantMessageParam, ChatCompletionAudioParam, ChatCompletionChunk, ChatCompletionContentPartFileParam, ChatCompletionContentPartImageParam, ChatCompletionContentPartInputAudioParam, ChatCompletionContentPartRefusalParam, ChatCompletionContentPartTextParam, ChatCompletionCreateParams, ChatCompletionDeveloperMessageParam, ChatCompletionFunctionMessageParam, ChatCompletionFunctions, ChatCompletionMessage, ChatCompletionMessageCustomToolCall, ChatCompletionMessageToolCall, ChatCompletionSystemMessageParam, ChatCompletionTokenLogprob, ChatCompletionToolMessageParam, ChatCompletionToolParam, ChatCompletionUserMessageParam, Choice, ChoiceDelta, ChoiceDeltaToolCall, ChoiceLogprobs, CompletionTokensDetails, CompletionUsage, DeferredCallResponse, InputTokenDetails, PredictionContent, PromptTokensDetails, StreamChoice, StreamChoiceLogprobs, ThinkingConfigDisabled, ThinkingConfigEnabled, ToolChoiceAny, ToolChoiceAuto, ToolChoiceNone, ToolChoiceTool, ) ``` -------------------------------- ### Upload Audio File for Transcription Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Shows how to upload an audio file for transcription using the Dedalus SDK. File parameters can be bytes, a PathLike object, or a tuple containing filename, contents, and media type. ```python from pathlib import Path from dedalus_labs import Dedalus client = Dedalus() client.audio.transcriptions.create( file=Path("/path/to/file"), model="model", ) ``` -------------------------------- ### Synchronous Client Usage Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Instantiate the synchronous Dedalus client and make a chat completion request. It's recommended to manage API keys using environment variables or a .env file. ```python import os from dedalus_labs import Dedalus client = Dedalus( api_key=os.environ.get("DEDALUS_API_KEY"), # This is the default and can be omitted # defaults to "production". environment="development", ) chat_completion = client.chat.completions.create( model="openai/gpt-5-nano", messages=[ { "role": "system", "content": "You are Stephen Dedalus. Respond in morose Joycean malaise.", }, { "role": "user", "content": "Hello, how are you today?", }, ], ) print(chat_completion.id) ``` -------------------------------- ### Parse Chat Completions with Structured Response Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Use the `parse` method for chat completions when you need the response in a specific Pydantic model. Ensure the model is compatible with structured output. ```python from dedalus_labs import Dedalus client = Dedalus() review_completion = client.chat.completions.parse( model="openai/gpt-4o-mini", messages=[ {"role": "user", "content": "Review the movie 'Inception' (2010)"} ], response_format=MovieReview, ) review = review_completion.choices[0].message.parsed print(f"Rating: {review.rating}/10") ``` -------------------------------- ### Text-to-Speech API Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Generate speech audio from text input. ```APIDOC ## POST /api/audio/speech ### Description Generate speech audio from text input. ### Method POST ### Endpoint /api/audio/speech ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model** (string) - Required - The ID of the TTS model to use (e.g., "tts-1"). - **voice** (string) - Required - The voice to use for the generated speech. Options: "alloy", "echo", "fable", "onyx", "nova", "shimmer". - **input** (string) - Required - The text to synthesize into speech. - **response_format** (string) - Optional - The format of the audio file. Supported options: "mp3", "opus", "aac", "flac", "wav", "pcm". Defaults to "mp3". - **speed** (number) - Optional - The speaking rate of the generated speech. Values range from 0.25 to 4.0. Defaults to 1.0. ### Request Example ```json { "model": "tts-1", "voice": "alloy", "input": "Hello, this is a test of text-to-speech synthesis." } ``` ### Response #### Success Response (200) - **content** (bytes) - The audio content of the generated speech. #### Response Example (Binary audio data, typically saved to a file) ```python # Example of saving the response content to a file speech_file = Path("/path/to/output.mp3") speech_file.write_bytes(response.content) ``` ``` -------------------------------- ### Run Tests Across Python Versions Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Execute tests using both Pydantic v1 and v2 across different Python versions by running the provided script. ```sh ./scripts/test ``` -------------------------------- ### Stop Prism Mock Server Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/CONTRIBUTING.md Kill the Prism mock server process running on TCP port 4010. ```sh kill $(lsof -t -i tcp:4010) ``` -------------------------------- ### Generate Images with DALL-E 3 Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Generate images from text prompts using DALL-E models. Specify the prompt, model, size, quality, and style. The response contains a URL for the generated image. ```python from dedalus_labs import Dedalus client = Dedalus() # Generate image with DALL-E 3 response = client.images.generate( prompt="A serene mountain landscape at sunset with vibrant colors", model="openai/dall-e-3", size="1024x1024", quality="hd", style="vivid", n=1, ) # Get image URL (valid for 60 minutes) image_url = response.data[0].url print(f"Image URL: {image_url}") ``` -------------------------------- ### Basic Chat Completion Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Perform a basic chat completion using the synchronous client. Include conversation history and system prompts. Access response fields like ID, content, finish reason, and token usage. ```python from dedalus_labs import Dedalus client = Dedalus() chat_completion = client.chat.completions.create( model="openai/gpt-5-nano", messages=[ { "role": "system", "content": "You are a helpful assistant.", }, { "role": "user", "content": "What is the capital of France?", }, ], temperature=0.7, max_tokens=150, ) # Access response print(chat_completion.id) # e.g., "cmpl_abc123" print(chat_completion.choices[0].message.content) # "The capital of France is Paris." print(chat_completion.choices[0].finish_reason) # "stop" print(chat_completion.usage.total_tokens) # Token usage statistics ``` -------------------------------- ### Create Speech Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Generates speech audio from text. This method corresponds to the POST /v1/audio/speech API endpoint and accepts various parameters. ```python client.audio.speech.create(**params) -> BinaryAPIResponse ``` -------------------------------- ### Configure Retries and Timeouts Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Enhance API call resilience by configuring automatic retries and request timeouts globally or per request. ```python import httpx from dedalus_labs import Dedalus # Configure retries and timeout globally client = Dedalus( max_retries=5, # Retry up to 5 times timeout=30.0, # 30 second timeout ) ``` ```python # Fine-grained timeout control client = Dedalus( timeout=httpx.Timeout( connect=5.0, read=30.0, write=10.0, pool=10.0, ), ) ``` ```python # Override per request response = client.with_options( max_retries=10, timeout=120.0, ).chat.completions.create( model="openai/gpt-5-nano", messages=[{"role": "user", "content": "Complex analysis task..."}], ) ``` -------------------------------- ### Manage HTTP Resources with Dedalus Client Context Manager Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Use the Dedalus client as a context manager (`with Dedalus() as client:`) to ensure that underlying HTTP connections are reliably closed upon exiting the block, preventing resource leaks. ```python from dedalus_labs import Dedalus with Dedalus() as client: # make requests here ... ``` -------------------------------- ### Edit Existing Images with Inpainting Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Edit existing images using inpainting with a prompt and optional mask. The `image` parameter accepts a Path object. The response contains the edited image as base64 JSON. ```python from pathlib import Path from dedalus_labs import Dedalus client = Dedalus() # Edit image with prompt response = client.images.edit( image=Path("/path/to/image.png"), prompt="Add a red hat to the person", model="openai/gpt-image-1", size="1024x1024", ) print(f"Edited image: {response.data[0].b64_json[:50]}...") ``` -------------------------------- ### Create Transcription Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Transcribes audio to text. This method corresponds to the POST /v1/audio/transcriptions API endpoint and accepts various parameters. ```python client.audio.transcriptions.create(**params) -> TranscriptionCreateResponse ``` -------------------------------- ### Translate Audio to English Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Translate audio content from any language into English text using the Whisper model. ```python from pathlib import Path from dedalus_labs import Dedalus client = Dedalus() translation = client.audio.translations.create( file=Path("/path/to/french_audio.mp3"), model="whisper-1", ) print(f"English translation: {translation.text}") ``` -------------------------------- ### Create Response Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Creates a response object. This method corresponds to the POST /v1/responses API endpoint and accepts various parameters. ```python client.responses.create(**params) -> Response ``` -------------------------------- ### Configure Timeouts for Dedalus SDK Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Set default request timeouts or override them per-request. Supports float values for seconds or `httpx.Timeout` objects for granular control. ```python from dedalus_labs import Dedalus # Configure the default for all requests: client = Dedalus( # 20 seconds (default is 1 minute) timeout=20.0, ) # More granular control: client = Dedalus( timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), ) # Override per-request: client.with_options(timeout=5.0).chat.completions.create( model="openai/gpt-5-nano", messages=[ { "role": "system", "content": "You are Stephen Dedalus. Respond in morose Joycean malaise.", }, { "role": "user", "content": "Hello, how are you today?", }, ], ) ``` -------------------------------- ### Import Response Types Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Imports types for creating and handling responses. Used with the responses API. ```python from dedalus_labs.types import Response, ResponseCreateParams ``` -------------------------------- ### Import Transcription Types Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Imports types for audio transcription responses. Used with the audio transcription API. ```python from dedalus_labs.types.audio import TranscriptionCreateResponse ``` -------------------------------- ### Generate Images with GPT Image Model Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Generate images using GPT Image models, which return base64 encoded data. You can specify various parameters like prompt, model, size, output format, and background. ```python from dedalus_labs import Dedalus client = Dedalus() # Generate with GPT Image model (returns base64) response = client.images.generate( prompt="A futuristic city skyline", model="openai/gpt-image-1", size="1536x1024", # Landscape quality="high", output_format="png", background="transparent", ) # Base64 encoded image b64_image = response.data[0].b64_json ``` -------------------------------- ### Create Image Variations Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Generate variations of an existing image. This functionality is specific to DALL-E 2. ```python from pathlib import Path from dedalus_labs import Dedalus client = Dedalus() response = client.images.create_variation( image=Path("/path/to/original.png"), n=3, size="512x512", ) for i, variation in enumerate(response.data): print(f"Variation {i+1}: {variation.url}") ``` -------------------------------- ### Text-to-Speech Synthesis Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Generate speech audio from provided text input. Supports various models and voices. ```python from pathlib import Path from dedalus_labs import Dedalus client = Dedalus() # Generate speech response = client.audio.speech.create( model="tts-1", voice="alloy", # Options: alloy, echo, fable, onyx, nova, shimmer input="Hello, this is a test of text-to-speech synthesis.", ) # Save to file speech_file = Path("/path/to/output.mp3") speech_file.write_bytes(response.content) ``` -------------------------------- ### Create Translation Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Translates audio from one language to another. This method corresponds to the POST /v1/audio/translations API endpoint and accepts various parameters. ```python client.audio.translations.create(**params) -> TranslationCreateResponse ``` -------------------------------- ### Import Translation Types Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Imports types for audio translation responses. Used with the audio translation API. ```python from dedalus_labs.types.audio import TranslationCreateResponse ``` -------------------------------- ### Create Embeddings Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Creates embeddings for given input text. This method corresponds to the POST /v1/embeddings API endpoint and accepts various parameters. ```python client.embeddings.create(**params) -> CreateEmbeddingResponse ``` -------------------------------- ### Manual HTTP Client Cleanup Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Manually close the HTTP client using `client.close()` within a `finally` block to ensure resources are released, especially when not using context managers. ```python from dedalus_labs import Dedalus client = Dedalus() try: # Use client... pass finally: client.close() ``` -------------------------------- ### Retries and Timeouts Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Configure automatic retries and request timeouts for resilient API calls. ```APIDOC ## Retries and Timeouts ### Description Configure automatic retries and request timeouts to enhance the resilience of API calls. ### Global Configuration Set `max_retries` and `timeout` when initializing the `Dedalus` client for global application. ```python import httpx from dedalus_labs import Dedalus # Configure retries and timeout globally client = Dedalus( max_retries=5, # Retry up to 5 times timeout=30.0, # 30 second timeout ) ``` ### Fine-grained Timeout Control Use `httpx.Timeout` for more specific control over connection, read, write, and pool timeouts. ```python import httpx from dedalus_labs import Dedalus client = Dedalus( timeout=httpx.Timeout( connect=5.0, read=30.0, write=10.0, pool=10.0, ), ) ``` ### Per-Request Overrides Override global settings for individual requests using the `with_options` method. ```python from dedalus_labs import Dedalus client = Dedalus() response = client.with_options( max_retries=10, timeout=120.0, ).chat.completions.create( model="openai/gpt-5-nano", messages=[{"role": "user", "content": "Complex analysis task..."}] ) ``` ``` -------------------------------- ### Error Handling Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Handle API errors with typed exceptions for different failure scenarios. ```APIDOC ## Error Handling ### Description The Dedalus SDK provides specific exception types for various API errors, allowing for granular error handling. ### Exception Types - **dedalus_labs.AuthenticationError**: Raised for authentication failures (e.g., invalid API key). - **dedalus_labs.RateLimitError**: Raised when the API rate limit is exceeded. - **dedalus_labs.BadRequestError**: Raised for invalid requests, such as malformed parameters. - **dedalus_labs.NotFoundError**: Raised when a requested resource does not exist. - **dedalus_labs.InternalServerError**: Raised for server-side errors within the API. - **dedalus_labs.APIConnectionError**: Raised for network-related issues when connecting to the API. - **dedalus_labs.APIStatusError**: A base class for errors related to specific HTTP status codes. ### Example Usage ```python import dedalus_labs from dedalus_labs import Dedalus client = Dedalus() try: completion = client.chat.completions.create( model="openai/gpt-5-nano", messages=[{"role": "user", "content": "Hello!"}] ) except dedalus_labs.AuthenticationError as e: print(f"Authentication failed (401): {e.message}") except dedalus_labs.RateLimitError as e: print(f"Rate limited (429): {e.message}") # Implement backoff strategy except dedalus_labs.BadRequestError as e: print(f"Invalid request (400): {e.message}") except dedalus_labs.NotFoundError as e: print(f"Resource not found (404): {e.message}") except dedalus_labs.InternalServerError as e: print(f"Server error (5xx): {e.message}") except dedalus_labs.APIConnectionError as e: print(f"Connection failed: {e.__cause__}") except dedalus_labs.APIStatusError as e: print(f"Status {e.status_code}: {e.message}") ``` ``` -------------------------------- ### Streaming Response with Lazy Body Reading Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Use `with_streaming_response` for streaming chat completions. Access the status code and iterate over lines of the response. ```python with client.chat.completions.with_streaming_response.create( model="openai/gpt-5-nano", messages=[{"role": "user", "content": "Hello!"}], ) as response: print(f"Status: {response.status_code}") for line in response.iter_lines(): print(line) ``` -------------------------------- ### Models API Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Endpoints for retrieving and listing available models. ```APIDOC ## GET /v1/models/{model_id} ### Description Retrieves a specific model by its ID. ### Method GET ### Endpoint /v1/models/{model_id} ### Parameters #### Path Parameters - **model_id** (string) - Required - The unique identifier of the model to retrieve. ### Response #### Success Response (200) - **Model** (object) - Detailed information about the requested model. ``` ```APIDOC ## GET /v1/models ### Description Lists all available models. ### Method GET ### Endpoint /v1/models ### Response #### Success Response (200) - **ListModelsResponse** (object) - A list of available models and their details. ``` -------------------------------- ### Audio Speech API Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Endpoint for converting text to speech. ```APIDOC ## POST /v1/audio/speech ### Description Converts text into speech audio. ### Method POST ### Endpoint /v1/audio/speech ### Parameters #### Request Body - **params** (object) - Required - Parameters for speech synthesis. Refer to `src/dedalus_labs/types/audio/speech_create_params.py` for details. ### Response #### Success Response (200) - **BinaryAPIResponse** - The audio data in binary format. ``` -------------------------------- ### Generate Image Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Generates new images based on a text prompt. This method corresponds to the POST /v1/images/generations API endpoint and accepts various parameters. ```python client.images.generate(**params) -> ImagesResponse ``` -------------------------------- ### Stream Response Data with Dedalus SDK Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/README.md Utilize `.with_streaming_response.` within a context manager to stream response bodies. Read the content using methods like `.iter_lines()` after accessing headers. ```python with client.chat.completions.with_streaming_response.create( model="openai/gpt-5-nano", messages=[ { "role": "system", "content": "You are Stephen Dedalus. Respond in morose Joycean malaise.", }, { "role": "user", "content": "Hello, how are you today?", }, ], ) as response: print(response.headers.get("X-My-Header")) for line in response.iter_lines(): print(line) ``` -------------------------------- ### Import Image Types Source: https://github.com/dedalus-labs/dedalus-sdk-python/blob/main/api.md Imports types related to image generation and manipulation. These are used with the images API. ```python from dedalus_labs.types import CreateImageRequest, Image, ImagesResponse ``` -------------------------------- ### Transcribe Audio to Text Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Transcribe audio files into text using speech recognition. Supports various audio formats and Whisper models. ```python from pathlib import Path from dedalus_labs import Dedalus client = Dedalus() # Transcribe audio file transcription = client.audio.transcriptions.create( file=Path("/path/to/audio.mp3"), model="whisper-1", ) print(transcription.text) ``` ```python # With additional options transcription = client.audio.transcriptions.create( file=Path("/path/to/meeting.wav"), model="whisper-1", language="en", response_format="verbose_json", # Include timestamps ) print(f"Transcribed text: {transcription.text}") ``` -------------------------------- ### Create Text Embeddings Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Generate vector embeddings from text for semantic search and similarity applications. You can create embeddings for single or multiple text inputs and specify model and dimensions. ```python from dedalus_labs import Dedalus client = Dedalus() # Single text embedding response = client.embeddings.create( input="The quick brown fox jumps over the lazy dog.", model="text-embedding-3-small", ) embedding = response.data[0].embedding print(f"Embedding dimensions: {len(embedding)}") # e.g., 1536 print(f"First 5 values: {embedding[:5]}") # Multiple text embeddings response = client.embeddings.create( input=[ "First document about machine learning.", "Second document about natural language processing.", "Third document about computer vision.", ], model="text-embedding-3-large", dimensions=256, # Reduce dimensions for efficiency ) for i, data in enumerate(response.data): print(f"Document {i}: {len(data.embedding)} dimensions") # Usage statistics print(f"Total tokens: {response.usage.total_tokens}") ``` -------------------------------- ### Image Variations API Source: https://context7.com/dedalus-labs/dedalus-sdk-python/llms.txt Create variations of an existing image using the DALL-E 2 model. ```APIDOC ## POST /api/images/create_variation ### Description Create variations of an existing image. This functionality is available for DALL-E 2 only. ### Method POST ### Endpoint /api/images/create_variation ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **image** (Path) - Required - The path to the original image file. - **n** (integer) - Optional - The number of variations to generate. Defaults to 1. - **size** (string) - Optional - The desired size of the generated variations (e.g., "512x512"). Defaults to "256x256". ### Request Example ```json { "image": "/path/to/original.png", "n": 3, "size": "512x512" } ``` ### Response #### Success Response (200) - **data** (array) - A list of generated image variation objects. - **url** (string) - The URL of the generated image variation. #### Response Example ```json { "data": [ { "url": "https://example.com/variation1.png" }, { "url": "https://example.com/variation2.png" }, { "url": "https://example.com/variation3.png" } ] } ``` ```