aix

AIX: Artificial Intelligence eXtensions

A clean, pythonic facade for common AI operations that abstracts away provider-specific details and complexities.

Quick Start:

>>> from aix import chat, embeddings, prompt_func, models

Simple chat

>>> response = chat("What is 2+2?")
'The answer is 4.'

Create prompt-based functions

>>> translate = prompt_func("Translate to French: {text}")
>>> translate(text="Hello world")
'Bonjour le monde'

Get embeddings

>>> vecs = list(embeddings(["hello", "world"]))
>>> len(vecs)
2

Discover models

>>> models.discover()
>>> list(models)[:5]
['openai/gpt-4o', 'openai/gpt-4o-mini', ...]

Main Features:

  • chat(): Simple chat interface across providers

  • complete(): The whole response (all n choices, usage, finish reasons)

  • sample(): n answers to one prompt, concurrently or via provider-side n

  • supports(): ask whether a model honours a parameter (seed, n, response_schema…)

  • embeddings(): Vector embeddings for text

  • prompt_func(): Create functions from prompt templates

  • models: Model discovery and selection

  • generate_image(): Text-to-image generation

  • text_to_speech(), transcribe(): Audio operations

  • generate_video(): Text-to-video generation (provider-dependent)

  • Batch operations for efficiency

  • Clean, i2mint-style Mapping interfaces

Backends:

  • Uses LiteLLM for provider interactions

  • Supports OpenAI, Anthropic, Google, and 100+ models

  • OpenRouter integration for multi-provider access

For detailed documentation, see: https://github.com/thorwhalen/aix

Functions

get_config()

Return the current active AixConfig.

set_config(config)

Replace the active config wholesale.

configure(**overrides)

Apply runtime overrides to the active config and return it.

using(**overrides)

Context manager applying scoped overrides, restored on exit.

load_config([path, environ])

Resolve an AixConfig from shipped defaults, TOML file, and env.

resolve_model(model, *[, config])

Resolve a semantic alias ("fast", "best", ...) to a concrete model id.

call_logger(logger)

Log calls made inside the with block to logger.

set_call_logger(logger)

Install logger for this context (None turns logging off).

jsonl_logger(path)

A logger that appends one JSON line per call to path.

resolve_api_key(model_or_provider, *[, ...])

Resolve an API key for model_or_provider through the documented layers.

check_requirements(model_or_provider, *[, ...])

Presence-only preflight: ensure a key for model_or_provider is resolvable.

check_keys([providers])

Report, per provider, whether a usable API key is discoverable.

chat(prompt, *[, model, temperature, ...])

Send a chat prompt and get a response.

complete(prompt, *[, model, temperature, ...])

Send a chat prompt and get the whole response back as a Completion.

ask(question[, model])

Ask a single question and get an answer.

sample(prompt, *, n[, temperature, seed, ...])

Draw n answers to prompt, each with its finish reason and usage.

supports(model, param)

Whether model is known to accept param -- i.e. whether LiteLLM forwards it to the provider for this model.

supported_params([model])

The OpenAI-style parameters LiteLLM says model accepts.

chat_with_history([system_prompt, model])

Create a stateful chat session that maintains conversation history.

embeddings(segments, *[, model, api_key])

Generate embeddings for multiple text segments.

embed(text, *[, model])

Generate embedding for a single text.

cosine_similarity(vec1, vec2)

Compute cosine similarity between two vectors.

find_most_similar(query, candidates, *[, ...])

Find most similar texts to a query.

prompt_func(template, *[, output_schema, ...])

Create a callable function from a prompt template.

prompt_to_text(template, **kwargs)

Create a function that returns text output.

prompt_to_json(template, schema, **kwargs)

Create a function that returns structured JSON output.

constrained_answer(prompt, valid_answers, *)

Get an answer from the LLM constrained to a set of valid answers or types.

discover_available_models([source, verbose])

Discover available models from a source.

get_model_info(model_id)

Get information about a specific model.

find_models(query)

Search for models matching a query.

batch_chat(prompts, *[, model, batch_size, ...])

Process multiple chat prompts in batches.

batch_embeddings(segments, *[, model, ...])

Generate embeddings for multiple texts in batches.

batch_process(items, process_func, *[, ...])

Generic batch processing with parallel execution and retries.

generate_image(prompt, *[, model, size, ...])

Generate a single image from a text prompt.

generate_images(prompt, *[, n, model, size, ...])

Generate multiple images from a text prompt.

edit_image(image_path, prompt, *[, ...])

Edit an existing image based on a prompt.

create_variation(image_path, *[, model, ...])

Create variations of an existing image.

text_to_speech(text, *[, model, voice, ...])

Convert text to speech audio.

transcribe(audio, *[, engine, model, ...])

Transcribe audio to text.

transcribe_with_timestamps(audio, *[, ...])

Transcribe audio with detailed timestamps.

translate_audio(audio, *[, model, prompt, ...])

Translate audio from any language to English.

generate_video(prompt, *[, model, duration, ...])

Generate a video from a text prompt.

animate_image_to_video(image_path[, prompt, ...])

Animate a static image into a video.

extend_video(video_path[, prompt, ...])

Extend an existing video with additional generated content.

get_video_providers()

Get list of available video generation providers.

describe_image(image, *[, prompt, model, ...])

Describe (or answer a question about) image and return the text.

to_image_content(image, *[, detail])

Build a multimodal image_url content block for image.

compare_images(candidate, reference, *[, ...])

Compare a candidate image to reference image(s) on a rubric.

Classes

AixConfig([chat, embeddings, image, audio, ...])

Top-level AIX configuration (single source of truth for defaults).

CallRecord(function, model, caller, ok, seconds)

One aix call: which function, the model it resolved to, who called, how it ended.

Completion(texts[, finish_reasons, usage, ...])

Everything a chat completion returned, not just the first text.

Usage([prompt_tokens, completion_tokens, ...])

Token counts billed for one call (or summed over several).

Sample(text, payload[, finish_reason, ...])

One drawn answer.

Samples([samples, usage, n_requests, ...])

The list of Sample returned by sample(), plus batch facts.

ResponseSchema(name, json_schema, ...[, ...])

A normalized response schema: its JSON Schema, name, and validator.

ChatSession([system_prompt, model])

Stateful chat session that maintains conversation history.

EmbeddingCache([model])

Cache for embeddings to avoid redundant API calls.

PromptFuncs([model])

Collection of prompt-based functions.

ModelStore([storage_path, auto_discover])

User-friendly interface for model discovery and selection.

BatchProcessor(*[, batch_size, max_workers, ...])

Stateful batch processor for managing long-running operations.

BatchError(exception, *[, index, message])

A batch result slot standing in for an item that raised.

GeneratedImage([url, b64_json, model, ...])

Wrapper for generated images.

GeneratedAudio(data[, model, text, voice, ...])

Wrapper for generated audio.

TranscriptionResult(text[, language, ...])

Result of audio transcription.

GeneratedVideo([url, data, model, prompt, ...])

Wrapper for generated videos.

RubricVerdict(aspect, match, confidence[, note])

A vision model's verdict on a single rubric aspect.

ImageComparison(match, confidence, explanation)

Structured result of comparing a candidate image to reference(s).

Exceptions

MissingCredentialError(model_or_provider, *)

Raised when a required API key cannot be resolved.

SamplingError(message, *[, samples])

A request inside sample() failed (with on_error="raise").

SchemaValidationError(message, *[, text, detail])

A reply was not JSON, or did not match the response schema.

ConstraintViolation(message, *[, answer, ...])

Raised when an LLM answer does not satisfy the requested constraint.

class aix.AixConfig(chat=ChatConfig(), embeddings=EmbeddingConfig(), image=ImageConfig(), audio=AudioConfig(), video=VideoConfig(), vision=VisionConfig(), aliases=<factory>)[source]

Bases: object

Top-level AIX configuration (single source of truth for defaults).

class aix.BatchError(exception, *, index=None, message=None)[source]

Bases: str

A batch result slot standing in for an item that raised.

Subclasses str so it is the "ERROR: ..." string these functions have always put in the failed slot – comparisons, .startswith, slicing, JSON serialisation and logging all behave identically. What it adds is the ability to tell a failure apart from a model that legitimately replied with text starting “ERROR:”, and to reach the original exception.

exception

The exception that was caught.

Type:

BaseException

index

Position of the failed item in the input, when known.

Type:

Optional[int]

Examples

>>> err = BatchError(RuntimeError("rate limit exceeded"), index=1)
>>> err == "ERROR: rate limit exceeded"
True
>>> isinstance(err, str), isinstance(err.exception, RuntimeError)
(True, True)
>>> err.index
1
class aix.BatchProcessor(*, batch_size=None, max_workers=None, show_progress=True)[source]

Bases: object

Stateful batch processor for managing long-running operations.

Provides a higher-level interface for batch processing with progress tracking, error handling, and result caching.

Examples

>>> processor = BatchProcessor(show_progress=True)
>>> results = processor.process_chats(prompts)
>>> processor.save_results("output.json")
clear()[source]

Clear stored results and errors.

Return type:

None

process_chats(prompts, **kwargs)[source]

Process chat prompts and store results.

Parameters:
Return type:

list[str]

Returns:

List of results

process_embeddings(texts, **kwargs)[source]

Process embeddings and store results.

Parameters:
  • texts (Iterable[str]) – Texts to embed

  • **kwargs – Additional parameters for batch_embeddings()

Return type:

list[Sequence[float]]

Returns:

List of embedding vectors

save_results(filepath)[source]

Save results to file.

Parameters:

filepath (str) – Path to save results (JSON)

Return type:

None

class aix.CallRecord(function, model, caller, ok, seconds, error=None, time=0.0)[source]

Bases: object

One aix call: which function, the model it resolved to, who called, how it ended.

class aix.ChatSession(system_prompt=None, *, model=None, **chat_kwargs)[source]

Bases: object

Stateful chat session that maintains conversation history.

This class provides a convenient way to have multi-turn conversations without manually managing message history.

Examples

>>> session = ChatSession()
>>> response = session.send("My name is Alice")
>>> response = session.send("What's my name?")
'Your name is Alice.'
clear_history(keep_system=True)[source]

Clear conversation history.

Parameters:

keep_system (bool) – If True, preserve system message (if any)

Return type:

None

send(message, **kwargs)[source]

Send a message and get a response.

Parameters:
  • message (str) – User message to send

  • **kwargs – Override chat parameters for this message

Return type:

str

Returns:

Assistant’s response

class aix.Completion(texts, finish_reasons=(), usage=None, model=None, raw=None, values=(), errors=(), schema_mode=None, repairs=0, system_fingerprint=None)[source]

Bases: object

Everything a chat completion returned, not just the first text.

texts

The text of every choice, in order (n of them when n was requested). A choice with no text content (e.g. a pure tool call) is ""; list-of-parts content is reduced to its joined text parts. Tool calls themselves are not surfaced here – read them from raw.

Type:

tuple[str, ...]

finish_reasons

Why each choice stopped ("stop", "length", "content_filter", "tool_calls"…), aligned with texts; None where the provider did not say. "length" means the text was truncated by max_tokens.

Type:

tuple[Optional[str], ...]

usage

Tokens billed for the whole call (all choices together), or None if the provider did not report usage (so filter before summing: sum((c.usage for c in cs if c.usage), Usage())).

Type:

Optional[Usage]

model

The model id the provider reports having served the call, which can differ from the one requested (aliases, dated snapshots).

Type:

Optional[str]

raw

The untouched LiteLLM response, for anything not surfaced here.

Type:

Any

system_fingerprint

The provider’s identifier for the serving backend configuration, when it reports one (OpenAI does). Seeded outputs are only comparable across calls with the same fingerprint. A response replayed from a cache carries its original fingerprint.

Type:

Optional[str]

values

With response_schema=: each choice’s validated value (a Pydantic instance for a Pydantic schema), None where invalid.

Type:

tuple

errors

Aligned with values: None, or why that choice has no value – the SchemaValidationError of a reply still invalid after the repair retries (or a refusal), or the exception a repair request raised.

Type:

tuple

schema_mode

How the schema was enforced: "strict", "schema", "json_mode" or "prompt" (see aix.structured); None without one.

Type:

Optional[str]

repairs

How many repair requests were made (their tokens are in usage).

Type:

int

>>> c = Completion(texts=("a", "b"), finish_reasons=("stop", "length"))
>>> c.text, c.finish_reason
('a', 'stop')
property finish_reason: Optional[str]

The first choice’s finish reason.

classmethod from_response(response)[source]

Build a Completion from a (non-streaming) LiteLLM response.

Return type:

Completion

property text: str

The first choice’s text ("" if there are no choices).

property value: Any

The first choice’s validated value (needs response_schema=).

Raises the recorded SchemaValidationError if that choice still did not validate after the repair retries.

exception aix.ConstraintViolation(message, *, answer=None, valid_answers=None)[source]

Bases: ValueError

Raised when an LLM answer does not satisfy the requested constraint.

A subclass of ValueError so that callers who already guard constrained_answer() with except ValueError keep working.

answer

The offending value, as it came back from the model.

valid_answers

The constraint the value failed, verbatim as passed in.

Examples

>>> violation = ConstraintViolation("nope", answer="nope", valid_answers=["a"])
>>> violation.answer, violation.valid_answers
('nope', ['a'])
>>> isinstance(violation, ValueError)
True
class aix.EmbeddingCache(model=None, **embedding_kwargs)[source]

Bases: object

Cache for embeddings to avoid redundant API calls.

Useful when you need to embed the same texts multiple times.

Examples

>>> cache = EmbeddingCache()
>>> vec1 = cache.embed("hello")  # API call
>>> vec2 = cache.embed("hello")  # From cache
>>> vec1 == vec2
True
clear()[source]

Clear the cache.

Return type:

None

embed(text, force_refresh=False)[source]

Get embedding for text, using cache if available.

Parameters:
  • text (str) – Text to embed

  • force_refresh (bool) – If True, bypass cache and get fresh embedding

Return type:

Sequence[float]

Returns:

Vector embedding

embed_batch(texts, force_refresh=False)[source]

Get embeddings for multiple texts, using cache when possible.

Parameters:
  • texts (Iterable[str]) – Texts to embed

  • force_refresh (bool) – If True, bypass cache

Return type:

list[Sequence[float]]

Returns:

List of embeddings in same order as input texts

class aix.GeneratedAudio(data, model=None, text=None, voice=None, format='mp3')[source]

Bases: object

Wrapper for generated audio.

Provides convenient access to audio data and saving.

Examples

>>> audio = GeneratedAudio(data=b'...', model="tts-1")
>>> audio.save("output.mp3")
>>> data = audio.as_bytes()
as_bytes()[source]

Get audio as bytes.

Return type:

bytes

Returns:

Audio data as bytes

play()[source]

Play the audio.

Requires a system audio player or library like pygame/pyaudio.

Examples

>>> audio.play()
Return type:

None

save(path)[source]

Save audio to file.

Parameters:

path (Union[str, Path]) – Output file path

Return type:

None

Examples

>>> audio.save("output.mp3")
>>> audio.save("speech.wav")
class aix.GeneratedImage(url=None, b64_json=None, model=None, prompt=None, revised_prompt=None)[source]

Bases: object

Wrapper for generated images.

Provides convenient access to image data in various formats.

Examples

>>> img = GeneratedImage(url="https://...", model="gpt-image-1.5")
>>> img.save("output.png")
>>> img.show()
>>> data = img.as_bytes()
as_bytes()[source]

Get image as bytes.

Return type:

bytes

Returns:

Image data as bytes

as_pil_image()[source]

Get image as PIL Image object.

Returns:

PIL.Image object

Raises:

ImportError – If PIL is not installed

save(path, format=None)[source]

Save image to file.

Parameters:
  • path (Union[str, Path]) – Output file path

  • format (str) – Image format (e.g., ‘PNG’, ‘JPEG’). Auto-detected from path if None.

Return type:

None

Examples

>>> img.save("output.png")
>>> img.save("output.jpg", format="JPEG")
show()[source]

Display the image.

Requires PIL (Pillow) to be installed.

Examples

>>> img.show()
Return type:

None

class aix.GeneratedVideo(url=None, data=None, model=None, prompt=None, duration=None, resolution=None, status='completed', task_id=None)[source]

Bases: object

Wrapper for generated videos.

Provides convenient access to video data and metadata.

Examples

>>> video = GeneratedVideo(url="https://...")
>>> video.save("output.mp4")
>>> print(video.duration)
5.0
as_bytes()[source]

Get video as bytes.

Return type:

bytes

Returns:

Video data as bytes

save(path)[source]

Save video to file.

Parameters:

path (Union[str, Path]) – Output file path

Return type:

None

Examples

>>> video.save("output.mp4")
wait_until_complete(max_wait=300, poll_interval=5)[source]

Wait for video generation to complete (for async operations).

Parameters:
  • max_wait (int) – Maximum time to wait in seconds

  • poll_interval (int) – Time between status checks in seconds

Raises:
Return type:

None

class aix.ImageComparison(match, confidence, explanation, aspects=tuple(), model=None, usage=None)[source]

Bases: object

Structured result of comparing a candidate image to reference(s).

Behaves like an ordered, read-only mapping of aspect -> RubricVerdict (comparison["identity"], in, iteration, len) so per-aspect lookups read naturally, while also carrying the overall verdict.

match

Overall pass/fail across the whole rubric.

Type:

bool

confidence

Overall confidence in [0.0, 1.0].

Type:

float

explanation

A short overall summary of the comparison.

Type:

str

aspects

The per-aspect verdicts, one RubricVerdict per rubric item, in rubric order.

Type:

tuple[RubricVerdict, ...]

model

The vision model id that produced the verdict.

Type:

str | None

usage

Tokens billed for the comparison request (see aix.Usage), or None if the provider did not report it.

Type:

Usage | None

get(aspect, default=None)[source]

Return the verdict for aspect, or default if absent.

Return type:

RubricVerdict | None

exception aix.MissingCredentialError(model_or_provider, *, provider=None, env_names=None)[source]

Bases: Exception

Raised when a required API key cannot be resolved.

The message names which key is missing, how to set it, and (when known) where to obtain one. Key values are never included.

class aix.ModelStore(storage_path=None, auto_discover=False)[source]

Bases: Mapping

User-friendly interface for model discovery and selection.

Provides a Mapping interface over the ModelManager with convenient access patterns and integration with chat/embeddings functions.

Examples

>>> models = ModelStore()
>>> models.discover()  # Fetch available models
>>> # List all models
>>> list(models)[:5]
['openai/gpt-4o', 'openai/gpt-4o-mini', ...]
>>> # Get model info
>>> info = models['openai/gpt-4o']
>>> info.provider
'openai'
>>> # Filter models
>>> openai_models = models.filter(provider='openai')
>>> local_models = models.filter(is_local=True)
>>> # Use with chat
>>> from aix.chat import chat
>>> model = models['gpt-4o-mini']
>>> chat("Hello", model=model.id)
'Hello! How can I help you?'
by_provider(provider)[source]

Get all models from a specific provider.

Parameters:

provider (str) – Provider name

Return type:

list[Model]

Returns:

List of models

Examples

>>> models = ModelStore()
>>> openai_models = models.by_provider('openai')
by_task(task)[source]

Get models suitable for a specific task.

Parameters:

task (str) – Task name (‘chat’, ‘embedding’, ‘image’, etc.)

Return type:

list[Model]

Returns:

List of suitable models

Examples

>>> models = ModelStore()
>>> chat_models = models.by_task('chat')
discover(source='openrouter', auto_register=True, verbose=False)[source]

Discover models from a source.

Parameters:
  • source (str) – Source name (‘openrouter’, ‘ollama’, etc.)

  • auto_register (bool) – If True, add discovered models to registry

  • verbose (bool) – If True, print progress information

Return type:

list[Model]

Returns:

List of discovered models

Examples

>>> models = ModelStore()
>>> discovered = models.discover('openrouter')
>>> len(discovered) > 100
True
filter(*, provider=None, is_local=None, min_context_size=None, max_context_size=None, has_capabilities=None, tags=None, custom_filter=None)[source]

Filter models by criteria.

Parameters:
  • provider (str) – Filter by provider name (‘openai’, ‘anthropic’, etc.)

  • is_local (bool) – Filter by local vs remote

  • min_context_size (int) – Minimum context window size

  • max_context_size (int) – Maximum context window size

  • has_capabilities (list[str]) – Required capabilities

  • tags (list[str]) – Required tags

  • custom_filter (callable) – Custom filter function: f(Model) -> bool

Return type:

list[Model]

Returns:

List of models matching criteria

Examples

>>> models = ModelStore()
>>> models.discover(verbose=False)
>>> # Get OpenAI models
>>> openai = models.filter(provider='openai')
>>> # Get local models
>>> local = models.filter(is_local=True)
>>> # Get cheap models
>>> cheap = models.filter(
...     custom_filter=lambda m: m.cost_per_token.get('input', 0) < 0.001
... )
>>> # Combine criteria
>>> good_models = models.filter(
...     provider='openai',
...     min_context_size=8000,
...     custom_filter=lambda m: 'gpt-4' in m.id
... )
get_connector_metadata(model_id, connector)[source]

Get connector-specific metadata for a model.

Parameters:
  • model_id (str) – Model identifier

  • connector (str) – Connector name (‘openai’, ‘openrouter’, etc.)

Return type:

dict[str, Any]

Returns:

Dict with connector-specific parameters

Examples

>>> models = ModelStore()
>>> meta = models.get_connector_metadata(
...     'openai/gpt-4o',
...     'openai'
... )
>>> meta['model']
'gpt-4o'
get_info(model_id)[source]

Get detailed information about a model.

Parameters:

model_id (str) – Model identifier

Return type:

Model

Returns:

Model object with full metadata

Examples

>>> models = ModelStore()
>>> models.discover(verbose=False)
>>> info = models.get_info('openai/gpt-4o')
>>> info.context_size
128000
recommend(*, task='chat', max_cost_per_mtok=None, min_context_size=None, prefer_local=False)[source]

Get recommended models based on requirements.

Parameters:
  • task (str) – Primary task (‘chat’, ‘embedding’, etc.)

  • max_cost_per_mtok (float) – Maximum cost per million tokens

  • min_context_size (int) – Minimum required context size

  • prefer_local (bool) – Prefer local models if available

Return type:

list[Model]

Returns:

List of recommended models, sorted by suitability

Examples

>>> models = ModelStore()
>>> recommendations = models.recommend(
...     task='chat',
...     max_cost_per_mtok=5.0,
...     min_context_size=16000
... )
search(query)[source]

Search models by text query.

Searches in model ID, provider, and tags.

Parameters:

query (str) – Search query

Return type:

list[Model]

Returns:

List of matching models

Examples

>>> models = ModelStore()
>>> models.discover(verbose=False)
>>> results = models.search('gpt-4')
>>> len(results) > 0
True
class aix.PromptFuncs(model=None, **default_kwargs)[source]

Bases: object

Collection of prompt-based functions.

Provides a namespace for organizing related prompt functions with attribute-based access.

Examples

>>> funcs = PromptFuncs()
>>> funcs.add('summarize', "Summarize: {text}")
>>> funcs.add('translate', "Translate {text} to {language}")
>>> funcs.summarize(text="Long article...")
'Summary...'
>>> funcs.translate(text="Hello", language="Spanish")
'Hola'
add(name, template, *, output_schema=None, **kwargs)[source]

Add a function to the collection.

Parameters:
  • name (str) – Function name (will be accessible as attribute)

  • template (str) – Prompt template

  • output_schema (Union[dict, type]) – Optional schema for structured output

  • **kwargs – Additional parameters for prompt_func

Return type:

None

keys()[source]

Get all function names.

class aix.ResponseSchema(name, json_schema, wire_schema, strict_compatible, source, wrapped=False, _coerce_json=None)[source]

Bases: object

A normalized response schema: its JSON Schema, name, and validator.

Build it with from_schema(); aix.complete() does that for you from response_schema=.

name

The schema name sent to the provider.

Type:

str

json_schema

The caller’s JSON Schema dict (what a value must match).

Type:

dict

wire_schema

What is sent: json_schema itself, or wrapped as {"value": json_schema} when its root is not an object.

Type:

dict

strict_compatible

Whether wire_schema satisfies strict-mode rules.

Type:

bool

wrapped

Whether wire_schema is the {"value": ...} wrapper.

Type:

bool

source

What the caller passed (a dict or a Pydantic model class).

Type:

Any

classmethod from_schema(schema)[source]

Normalize a JSON Schema dict or a Pydantic model class.

Raises:
  • TypeError – For anything else.

  • jsonschema.SchemaError – For a malformed JSON Schema dict.

Return type:

ResponseSchema

instruction()[source]

The prompt text that asks for this schema (JSON / prompt modes, repairs).

Return type:

str

mode_for(model)[source]

The strongest enforcement mode available for model and this schema.

Return type:

str

response_format(mode)[source]

The LiteLLM response_format for mode (None for "prompt").

Return type:

Optional[dict]

validate(text)[source]

Parse and validate a reply; return the value (a model instance for Pydantic).

Raises:

SchemaValidationError – If text is not JSON or does not match.

Return type:

Any

class aix.RubricVerdict(aspect, match, confidence, note='')[source]

Bases: object

A vision model’s verdict on a single rubric aspect.

aspect

The rubric item this verdict is about (e.g. "identity").

Type:

str

match

Whether the candidate matches the reference for this aspect.

Type:

bool

confidence

The model’s self-reported confidence in [0.0, 1.0].

Type:

float

note

A short free-text explanation of the verdict.

Type:

str

class aix.Sample(text, payload, finish_reason=None, usage=None, strategy='independent', seed=None, error=None, system_fingerprint=None)[source]

Bases: object

One drawn answer.

text

The raw text of this choice ("" if its request failed).

Type:

str

payload

parse(text) when a parse function was given, else text; None if the request or the parsing failed (see error).

Type:

Any

finish_reason

Why this choice stopped. "length" = truncated, "content_filter" = refused/filtered; check it before treating the payload as a judgement.

Type:

Optional[str]

usage

Tokens for the request that produced only this sample, or None when it shared a provider-side n request (whose usage cannot be split per choice; see Samples.usage).

Type:

Optional[Usage]

strategy

How this sample was drawn: "provider_n" or "independent".

Type:

str

seed

The seed sent with its request, if any.

Type:

Optional[int]

error

The exception this sample’s request raised (with on_error="record") or that parse raised on its text.

Type:

Optional[Exception]

system_fingerprint

The serving backend’s fingerprint for its request, when reported. Seeded samples are only comparable across equal fingerprints (see aix.supports() for whether seed is honoured at all).

Type:

Optional[str]

property ok: bool

True when the request succeeded and the text parsed (if asked).

class aix.Samples(samples=(), *, strategy, usage=None, n_requests=0, n_usage_reports=0, fallback_error=None)[source]

Bases: list

The list of Sample returned by sample(), plus batch facts.

It is a plain list otherwise: slicing or concatenating gives a list without the batch attributes, which describe the whole draw only.

strategy

"provider_n", "independent" or "mixed" (provider n topped up with independent calls).

usage

Total tokens over every request that reported usage, or None if none did. Compare n_requests with n_usage_reports to see whether it is complete.

n_requests

How many requests were made (schema repair requests included).

n_usage_reports

How many of them reported usage (a completion’s repair requests are counted with it when it reported usage). A provider request refused with a 400 (see fallback_error) reports none.

fallback_error

With strategy="auto": the error that made the provider-side n request fall back to independent requests (LiteLLM refusing n, or the provider rejecting it with a 400), else None.

property errors: tuple[Exception, ...]

Every recorded error (request or parse), in sample order.

exception aix.SamplingError(message, *, samples=None)[source]

Bases: Exception

A request inside sample() failed (with on_error="raise").

No request is launched after the first failure, and the ones already in flight are awaited, so the work already paid for is not lost: samples holds every request that was made, failed ones included (as samples whose error is set) – possibly fewer than n. The first failure is __cause__.

exception aix.SchemaValidationError(message, *, text='', detail='')[source]

Bases: ValueError

A reply was not JSON, or did not match the response schema.

text

The reply that failed.

detail

The parse / validation message (what a repair prompt is told).

class aix.TranscriptionResult(text, language=None, duration=None, segments=None, model=None)[source]

Bases: object

Result of audio transcription.

Contains the transcribed text and optional metadata like segments and timestamps.

Examples

>>> result = TranscriptionResult(text="Hello world")
>>> print(result.text)
'Hello world'
class aix.Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0, cached_prompt_tokens=0, cache_creation_tokens=0, reasoning_tokens=0)[source]

Bases: object

Token counts billed for one call (or summed over several).

prompt_tokens / completion_tokens / total_tokens are the headline counts. The breakdowns – prompt tokens served from the provider’s cache (cached_prompt_tokens), written to it (cache_creation_tokens), and hidden reasoning tokens inside completion_tokens (reasoning_tokens) – are priced differently by most providers, so cost reporting needs them. Counts a provider did not report are 0.

Usages add, and sum works when you give it a Usage() start (so an empty batch is a zero Usage, not the integer 0):

>>> Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15)
Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15, cached_prompt_tokens=0, cache_creation_tokens=0, reasoning_tokens=0)
>>> sum([Usage(1, 2, 3), Usage(10, 20, 30)], Usage()).total_tokens
33
>>> sum([], Usage()) == Usage()
True
classmethod from_response(response)[source]

Read the usage block of a LiteLLM response; None if absent.

>>> u = Usage.from_response({"usage": {"prompt_tokens": 3, "completion_tokens": 4}})
>>> u.prompt_tokens, u.completion_tokens, u.total_tokens
(3, 4, 7)
>>> Usage.from_response({}) is None
True
Return type:

Optional[Usage]

aix.animate_image_to_video(image_path, prompt=None, *, model=None, duration=3.0, motion_strength=0.5, **kwargs)

Animate a static image into a video.

Parameters:
  • image_path (Union[str, Path]) – Path to the source image

  • prompt (str) – Optional text prompt to guide the animation

  • model (str) – Video generation model to use

  • duration (float) – Animation duration in seconds

  • motion_strength (float) – Strength of motion (0.0 to 1.0)

  • **kwargs – Additional provider-specific parameters

Return type:

GeneratedVideo

Returns:

GeneratedVideo object

Examples

>>> from aix.video import animate_image
>>> video = animate_image(
...     "landscape.jpg",
...     prompt="Gentle camera pan across the scene",
...     duration=4
... )
>>> video.save("animated_landscape.mp4")
aix.ask(question, model=None, **kwargs)[source]

Ask a single question and get an answer.

This is a convenience wrapper around chat() for simple Q&A.

Parameters:
  • question (str) – The question to ask

  • model (str) – Model to use

  • **kwargs – Additional parameters for chat()

Return type:

str

Returns:

The answer as a string

Examples

>>> from aix.chat import ask
>>> ask("What is the capital of France?")
'The capital of France is Paris.'
aix.batch_chat(prompts, *, model=None, batch_size=None, max_workers=None, show_progress=False, on_error='return', **chat_kwargs)[source]

Process multiple chat prompts in batches.

This function processes multiple prompts efficiently by:

  1. Chunking prompts into batches

  2. Processing batches in parallel where possible

  3. Yielding results in the same order as input

Parameters:
  • prompts (Iterable[Union[str, list[dict]]]) – Iterable of prompts (strings or message lists)

  • model (str) – Model to use for all prompts

  • batch_size (int) – Number of prompts to process in each batch

  • max_workers (int) – Maximum number of parallel workers

  • show_progress (bool) – If True, print progress information

  • on_error (Literal['return', 'raise', 'skip']) – What to do with a prompt whose call raised. 'return' (default) yields a BatchError in that slot, keeping the stream the same length and order as the input. 'raise' stops after the batch in which the first failure landed and re-raises the lowest-indexed exception of that batch. 'skip' omits the failed slots from the stream.

  • **chat_kwargs – Additional parameters passed to chat()

Yields:

Responses in the same order as input prompts. A prompt that raised yields a BatchError – a str subclass equal to "ERROR: <message>", carrying the original exception on .exception.

Raises:

ValueError – If on_error is not one of ‘return’, ‘raise’, ‘skip’.

Return type:

Iterable[str]

Examples

>>> from aix.batches import batch_chat
>>> prompts = [
...     "What is 2+2?",
...     "What is 3+3?",
...     "What is 5+5?"
... ]
>>> results = list(batch_chat(prompts))
>>> len(results)
3
>>> # With specific model
>>> results = list(batch_chat(
...     prompts,
...     model="gpt-4o-mini",
...     batch_size=5
... ))
>>> # Process large dataset
>>> def generate_prompts():
...     for i in range(100):
...         yield f"Explain concept {i}"
>>> results = batch_chat(
...     generate_prompts(),
...     show_progress=True
... )
>>> for i, result in enumerate(results):
...     print(f"Result {i}: {result[:50]}...")
>>> # Tell a failure apart from a reply that starts with "ERROR:"
>>> for result in batch_chat(prompts):
...     if isinstance(result, BatchError):
...         raise result.exception
aix.batch_embeddings(segments, *, model=None, batch_size=None, show_progress=False, **embedding_kwargs)[source]

Generate embeddings for multiple texts in batches.

For efficiency, this function processes embeddings in chunks, as most embedding APIs can handle multiple texts per request.

Parameters:
  • segments (Iterable[str]) – Iterable of text strings to embed

  • model (str) – Embedding model to use

  • batch_size (int) – Number of texts per batch

  • show_progress (bool) – If True, print progress information

  • **embedding_kwargs – Additional parameters for embeddings()

Yields:

Vector embeddings in the same order as input

Return type:

Iterable[Sequence[float]]

Examples

>>> from aix.batches import batch_embeddings
>>> texts = ["hello", "world", "foo", "bar"] * 25  # 100 texts
>>> vectors = list(batch_embeddings(
...     texts,
...     batch_size=10,
...     show_progress=True
... ))
>>> len(vectors)
100
>>> # Process large dataset efficiently
>>> def read_documents():
...     # Generator that yields documents
...     for i in range(1000):
...         yield f"Document {i} content"
>>> all_vectors = []
>>> for vec in batch_embeddings(read_documents()):
...     all_vectors.append(vec)
aix.batch_process(items, process_func, *, batch_size=None, max_workers=None, show_progress=False, retry_attempts=None, retry_delay=None, on_error='return')[source]

Generic batch processing with parallel execution and retries.

This is a general-purpose batch processor that can be used for any operation, not just chat or embeddings.

Parameters:
  • items (Iterable[Any]) – Items to process

  • process_func (callable) – Function to apply to each item

  • batch_size (int) – Batch size for chunking

  • max_workers (int) – Maximum parallel workers

  • show_progress (bool) – Show progress information

  • retry_attempts (int) – Number of retry attempts on failure

  • retry_delay (float) – Delay between retries (seconds)

  • on_error (Literal['return', 'raise', 'skip']) – What to do with an item still failing after every retry. 'return' (default) yields a BatchError in that slot, 'raise' re-raises, 'skip' omits it. See batch_chat().

Yields:

Results in same order as input. An item that raised yields a BatchError – a str subclass equal to "ERROR: <message>", carrying the original exception on .exception.

Raises:

ValueError – If on_error is not one of ‘return’, ‘raise’, ‘skip’.

Return type:

Iterable[Any]

Examples

>>> from aix.batches import batch_process
>>> from aix.chat import chat
>>> # Custom processing function
>>> def analyze_sentiment(text):
...     return chat(f"Analyze sentiment: {text}")
>>> texts = ["I love this!", "This is terrible", "It's okay"]
>>> results = list(batch_process(
...     texts,
...     analyze_sentiment,
...     batch_size=5
... ))
>>> # With retries for flaky operations
>>> def flaky_api_call(item):
...     # Some API that might fail
...     return call_api(item)
>>> results = batch_process(
...     items,
...     flaky_api_call,
...     retry_attempts=3,
...     retry_delay=2.0
... )
aix.call_logger(logger)[source]

Log calls made inside the with block to logger.

Return type:

Iterator[None]

aix.chat(prompt, *, model=None, temperature=None, max_tokens=None, stream=False, api_key=None, **kwargs)[source]

Send a chat prompt and get a response.

This is the main chat interface for AIX. It abstracts away provider-specific details and provides a clean, consistent API across all models.

Parameters:
  • prompt (Union[str, Iterable[dict]]) – Either a string (becomes a user message) or a list of message dicts with ‘role’ and ‘content’ keys

  • model (str) – Model identifier (e.g., ‘gpt-4o’, ‘claude-sonnet-4’, ‘openrouter/anthropic/claude-3.5-sonnet’). If None, uses default.

  • temperature (float) – Sampling temperature (0.0 = deterministic, 2.0 = creative). If None, uses default (1.0).

  • max_tokens (int) – Maximum tokens to generate. If None, uses model’s default.

  • stream (bool) – If True, return an iterator of text chunks. If False, return complete response as string.

  • api_key (str) – Explicit API key. If None, resolved from the environment / .env / AIX config store for the model’s provider (see aix.credentials).

  • on_call – Optional fn(CallRecord) called after the call with the resolved model, the caller and the outcome (opt-in call log, see aix.calllog).

  • **kwargs – Additional provider-specific parameters passed to LiteLLM

Returns:

Complete response as string If stream=True: Iterator yielding text chunks as they arrive

Return type:

Union[str, Iterable[str]]

Raises:

Examples

>>> chat("What is Python?")
'Python is a high-level programming language...'
>>> chat("Hello", model="gpt-4o")
'Hello! How can I assist you today?'
>>> # Streaming response
>>> for chunk in chat("Count to 5", stream=True):
...     print(chunk, end='', flush=True)
1, 2, 3, 4, 5
>>> # With message history
>>> messages = [
...     {"role": "system", "content": "You are a helpful assistant."},
...     {"role": "user", "content": "What is 2+2?"}
... ]
>>> chat(messages)
'2+2 equals 4.'
aix.chat_with_history(system_prompt=None, *, model=None, **chat_kwargs)[source]

Create a stateful chat session that maintains conversation history.

Parameters:
  • system_prompt (str) – Optional system message to set context/behavior

  • model (str) – Model to use for this session

  • **chat_kwargs – Additional parameters passed to chat()

Return type:

ChatSession

Returns:

ChatSession object with send() method

Examples

>>> session = chat_with_history("You are a helpful math tutor")
>>> session.send("What is 2+2?")
'The answer is 4.'
>>> session.send("And if I add 3 to that?")
'That would be 7.'
>>> len(session.history)
5
aix.check_keys(providers=None)[source]

Report, per provider, whether a usable API key is discoverable.

Never returns or logs key values – only availability and the env-var name(s) checked. Useful for quick setup debugging.

Parameters:

providers (Optional[Iterable[str]]) – Providers to check; defaults to every provider in PROVIDER_ENV_VARS.

Returns:

bool, “env_vars”: […], “source”: <where-found-or-None>}``. source is "env", "store", or None (never the value itself).

Return type:

dict[str, dict]

Examples

>>> report = check_keys(["openai"])
>>> report["openai"]["available"]
True
aix.check_requirements(model_or_provider, *, api_key=None)[source]

Presence-only preflight: ensure a key for model_or_provider is resolvable.

Does not validate the key over the network – only that one is discoverable via resolve_api_key() (explicit arg, env/.env, or store). Raises MissingCredentialError with actionable guidance when absent.

Returns True when a key is available, or when the model is local and needs none (is_keyless(), e.g. ollama/...).

Examples

>>> check_requirements("gpt-4o", api_key="sk-explicit")
True
>>> check_requirements("ollama/mistral")
True
Return type:

bool

aix.compare_images(candidate, reference, *, rubric=('identity', 'costume', 'setting', 'lighting', 'props'), model=None, api_key=None, max_tokens=None, temperature=0.0, detail=None, instruction='You are a strict visual continuity supervisor. The FIRST image is the CANDIDATE; the remaining image(s) are the locked REFERENCE the candidate must match. Judge each rubric aspect INDEPENDENTLY (do not let one aspect color another). For each aspect decide whether the candidate matches the reference, give a confidence in [0.0, 1.0], and a short note explaining what matches or drifts. Then give an overall match (true only if every important aspect matches), an overall confidence, and a one-sentence explanation.', **kwargs)[source]

Compare a candidate image to reference image(s) on a rubric.

The explainable half of a reference supervisor: a vision model returns a per-aspect pass/fail checklist (does the face match? the costume? the set? the lighting? the props?) plus an overall verdict — the explainable layer over a cheap numeric identity-cosine gate (which lives elsewhere, e.g. lookbook). Built on to_image_content() (multi-image content block) and the same multimodal completion path as describe_image(), asked via a JSON contract for a structured answer.

The comparison is pointwise (each aspect judged on its own), not a ranked pairwise comparison, to avoid position bias.

Parameters:
  • candidate (Union[str, Path, bytes, Any]) – The image under review (URL / path / bytes / PIL image / data: URI — anything to_image_content() accepts).

  • reference (Union[str, Path, bytes, Any, Sequence[Any]]) – The locked reference — a single image or a sequence of images (a locked set) in the same flexible formats. An empty sequence is an error.

  • rubric (Sequence[str]) – The aspects to evaluate, one verdict per item. Defaults to DFLT_COMPARE_RUBRIC; pass DFLT_FILM_RUBRIC (or any custom sequence) to override — e.g. ("face", "architecture", "props", "lighting"). Must be non-empty.

  • model (str | None) – Vision-capable model id or alias. None → the configured default (aix.config.VisionConfig).

  • api_key (str | None) – Explicit API key; None resolves it for the model’s provider from the environment / .env / config store.

  • max_tokens (int | None) – Cap on generated tokens (None → provider default).

  • temperature (float | None) – Sampling temperature (default 0.0 for a stable, reproducible verdict; None → provider default).

  • detail (str | None) – Image detail hint ("low" | "high" | "auto"), applied to every image block.

  • instruction (str) – The system-style framing prepended to the rubric. Has a sensible default; override to retune the supervisor’s strictness.

  • **kwargs (Any) – Extra provider-specific params forwarded to LiteLLM.

Return type:

ImageComparison

Returns:

An ImageComparison — overall match / confidence / explanation plus an ordered, mapping-like collection of RubricVerdict (one per rubric aspect, keyed by aspect).

Raises:
  • ImportError – If LiteLLM is not installed.

  • ValueError – If rubric is empty or reference is an empty sequence, or if the model’s reply can’t be parsed as the expected JSON verdict.

Examples

Default rubric, single reference:

>>> compare_images("gen.png", "ref.png")
ImageComparison(match=True, confidence=0.9, ...)

Filmmaking rubric, a locked reference set:

>>> from aix.vision import DFLT_FILM_RUBRIC
>>> compare_images(
...     candidate="frame_042.png",
...     reference=["ref_front.png", "ref_side.png"],
...     rubric=DFLT_FILM_RUBRIC,
... )["face_identity"].match
True
aix.complete(prompt, *, model=None, temperature=None, max_tokens=None, n=1, seed=None, response_format=None, response_schema=None, max_repairs=None, api_key=None, **kwargs)[source]

Send a chat prompt and get the whole response back as a Completion.

The non-lossy sibling of chat(): same inputs and defaults, but instead of the first choice’s text it returns every choice (texts), why each one stopped (finish_reasons), the tokens billed (usage), the model that served the call, and the raw response.

Parameters:
  • prompt (Union[str, Iterable[dict]]) – A string (becomes a user message) or a list of message dicts.

  • model (str) – Model identifier or alias. If None, uses the configured default.

  • temperature (float) – Sampling temperature. If None, uses the configured default.

  • max_tokens (int) – Maximum tokens per choice. If None, uses the configured default.

  • n (int) – How many choices to ask the provider for in this one call. Only sent when n != 1; providers without native n support reject it (see LiteLLM’s get_supported_openai_params).

  • seed (int) – Best-effort reproducibility seed. Only sent when given. Support is provider-dependent (aix.supports(model, "seed")); where it is unsupported LiteLLM either drops it or rejects the call, and where it is supported determinism is still best-effort – compare system_fingerprint across calls before reading a difference as model instability.

  • response_format (Union[dict, type]) – Passed through to LiteLLM (e.g. {"type": "json_object"}). Mutually exclusive with response_schema.

  • response_schema (Union[dict, type]) – A JSON Schema dict or a Pydantic model class. The provider is asked to enforce it as strongly as the model allows (strict json_schema > non-strict json_schema > JSON mode plus the schema in the prompt; see aix.structured), and every choice is validated client-side into values / errors.

  • max_repairs (int) – With response_schema: how many times to re-ask for an invalid choice, showing the model its error (None = config chat.schema_max_repairs; 0 disables repair).

  • api_key (str) – Explicit API key; otherwise resolved as for chat().

  • **kwargs – Additional provider-specific parameters passed to LiteLLM.

Return type:

Completion

Returns:

A Completion.

Raises:
  • ImportError – If LiteLLM is not installed.

  • ValueError – If n is not a positive integer, or the prompt is invalid.

Examples

>>> c = complete("Name a color", n=3)
>>> c.texts, c.finish_reasons
(('Blue', 'Green', 'Red'), ('stop', 'stop', 'stop'))
>>> c.usage
Usage(prompt_tokens=11, completion_tokens=6, total_tokens=17)
>>> complete("Write an essay", max_tokens=5).finish_reason
'length'

Structured output, validated:

>>> from pydantic import BaseModel
>>> class Verdict(BaseModel):
...     label: str
...     confidence: float
>>> c = complete("Is the sky green?", response_schema=Verdict)
>>> c.value, c.schema_mode
(Verdict(label='no', confidence=0.99), 'strict')
aix.configure(**overrides)[source]

Apply runtime overrides to the active config and return it.

Examples

>>> from aix import config
>>> _ = config.configure(chat_model="openai/gpt-4o-mini")
>>> config.get_config().chat.model
'openai/gpt-4o-mini'
>>> _ = config.configure(chat={"temperature": 0.2})
>>> config.get_config().chat.temperature
0.2
Return type:

AixConfig

aix.constrained_answer(prompt, valid_answers, *, model=None, temperature=None, enhance_prompt=False, n=1, on_violation='raise', max_retries=0, concurrency=None)[source]

Get an answer from the LLM constrained to a set of valid answers or types.

Uses JSON mode to ensure the LLM returns a valid response based on constraints. More flexible than the oa version - works with any model that supports JSON mode via LiteLLM.

This can be seen as a facade for some common structured output use cases, as well as a convenient tool to do response statistics and validation (via n>1).

Parameters:
  • prompt (str) – The question or prompt to ask the LLM

  • valid_answers (Union[list[str], list[int], list[float], type, tuple[float, float]]) –

    Can be:

    • list[str]: List of valid string options

    • list[int]: List of valid integer options

    • list[float]: List of valid float options

    • bool: Constrains answer to True or False

    • int: Any integer

    • float: Any number

    • tuple[float, float]: Numerical range (min, max) inclusive

  • model (str) – The model to use for the LLM (default: uses DFLT_CHAT_MODEL)

  • temperature (float) – Temperature for sampling (default: None, uses model’s default). Higher values (e.g., 1.0) give more random/varied results. Lower values (e.g., 0.0) give more deterministic results.

  • enhance_prompt (bool) – If True, adds explicit instructions to the prompt about JSON formatting and constraints. If False (default), relies on response_format alone. Default is False to match oa behavior.

  • n (int) – Number of times to call the LLM (default: 1). The n calls are independent and run concurrently (see concurrency); each is validated (and retried) on its own. On the first failure no new call is started, but calls already in flight finish (and are billed) before the error propagates. For raw samples with finish reasons and usage, use aix.sample().

  • on_violation (Literal['raise', 'return']) – What to do when the model’s answer does not satisfy valid_answers. 'raise' (default) raises ConstraintViolation. 'return' returns the model’s value unchecked – the behaviour of this function before enforcement existed, kept as an escape hatch.

  • max_retries (int) – How many times to re-ask the model after a violation before giving up (default: 0, i.e. ask exactly once). Ignored when on_violation='return', which never detects a violation.

  • concurrency (int) – Max simultaneous calls when n > 1 (default: config chat.sample_concurrency).

Returns:

One of the valid answers, respecting the type constraint. If n > 1, returns a list of answers.

Raises:
  • ConstraintViolation – If the answer is not a member of an options list, falls outside a (min, max) range, or cannot be converted to the declared type – unless on_violation='return'.

  • ValueError – If the response is not JSON, or has no “answer” field.

Examples

>>> # String options
>>> answer = constrained_answer(
...     "Is Python compiled or interpreted?",
...     ["compiled", "interpreted", "both"]
... )
>>> answer in ["compiled", "interpreted", "both"]
True
>>> # Boolean
>>> answer = constrained_answer(
...     "Is Python dynamically typed?",
...     bool
... )
>>> isinstance(answer, bool)
True
>>> # Integer options
>>> answer = constrained_answer(
...     "How many wheels does a car have?",
...     [2, 3, 4, 6, 8]
... )
>>> answer in [2, 3, 4, 6, 8]
True
>>> # Numerical range
>>> answer = constrained_answer(
...     "What is a reasonable hourly rate for a senior Python developer? (USD)",
...     (50.0, 300.0)
... )
>>> 50.0 <= answer <= 300.0
True
>>> # Multiple samples for statistics
>>> answers = constrained_answer(
...     "Which is better: cats or dogs?",
...     ["cats", "dogs"],
...     n=10
... )
>>> len(answers)
10
>>> # Tolerate an off-constraint answer instead of raising
>>> answer = constrained_answer(
...     "Is Python compiled or interpreted?",
...     ["compiled", "interpreted"],
...     on_violation="return",
... )
aix.cosine_similarity(vec1, vec2)[source]

Compute cosine similarity between two vectors.

Parameters:
Return type:

float

Returns:

Cosine similarity (between -1 and 1)

Examples

>>> from aix.embeddings import embed, cosine_similarity
>>> v1 = embed("cat")
>>> v2 = embed("kitten")
>>> similarity = cosine_similarity(v1, v2)
>>> similarity > 0.8
True
aix.create_variation(image_path, *, model=None, size=None, n=1, api_key=None, **kwargs)[source]

Create variations of an existing image.

Parameters:
  • image_path (Union[str, Path]) – Path to the source image

  • model (str) – Model to use (None = configured image.variation_model)

  • size (str) – Output image size

  • n (int) – Number of variations to generate

  • **kwargs – Additional provider-specific parameters

Return type:

Union[GeneratedImage, list[GeneratedImage]]

Returns:

GeneratedImage or list of GeneratedImage objects

Examples

>>> from aix.image import create_variation
>>> variations = create_variation(
...     "original.png",
...     n=3,
...     size="512x512"
... )
>>> for i, var in enumerate(variations):
...     var.save(f"variation_{i}.png")
aix.describe_image(image, *, prompt='Describe this image in detail.', model=None, api_key=None, max_tokens=None, temperature=None, detail=None, **kwargs)[source]

Describe (or answer a question about) image and return the text.

The image→text primitive. image accepts a URL, a local path, raw bytes, a PIL image, or a data: URI (see to_image_content()). prompt is the instruction (default: a generic “describe this image”); pass a question for VQA or a rubric for a judgement. Everything past image is keyword.

Parameters:
  • image (Union[str, Path, bytes, Any]) – The image (URL / path / bytes / PIL image / data: URI).

  • prompt (str) – The text instruction accompanying the image.

  • model (str | None) – Vision-capable model id (e.g. gpt-4o, claude-sonnet-4-6, gemini/gemini-1.5-pro) or an alias. None → the configured default (aix.config.VisionConfig).

  • api_key (str | None) – Explicit API key; None resolves it from the environment / .env / config store for the model’s provider.

  • max_tokens (int | None) – Cap on generated tokens (None → provider default).

  • temperature (float | None) – Sampling temperature (None → provider default).

  • detail (str | None) – Image detail hint ("low" | "high" | "auto").

  • **kwargs (Any) – Extra provider-specific params forwarded to LiteLLM.

Return type:

str

Returns:

The model’s text response.

Raises:

ImportError – If LiteLLM is not installed.

>>> describe_image("cat.jpg", prompt="Caption it.")
'A cat on a sofa.'

For usage, several samples (n) or validated structured output, send the same image content through aix.complete() (or aix.sample()):

>>> from aix import complete
>>> c = complete([{"role": "user", "content": [
...     {"type": "text", "text": "Caption it."}, to_image_content("cat.jpg")]}],
...     model="gpt-4o-mini", n=3)
>>> c.texts, c.usage
aix.discover_available_models(source='openrouter', verbose=True)[source]

Discover available models from a source.

Convenience function that uses the global models instance.

Parameters:
  • source (str) – Source name (‘openrouter’, ‘ollama’, etc.)

  • verbose (bool) – Print progress information

Return type:

list[Model]

Returns:

List of discovered models

Examples

>>> from aix.models import discover_available_models
>>> models = discover_available_models('openrouter')
>>> len(models) > 100
True
aix.edit_image(image_path, prompt, *, mask_path=None, model=None, size=None, n=1, api_key=None, **kwargs)[source]

Edit an existing image based on a prompt.

Parameters:
  • image_path (Union[str, Path]) – Path to the image to edit

  • prompt (str) – Description of the desired edit

  • mask_path (Union[str, Path]) – Optional path to mask image (transparent areas will be edited)

  • model (str) – Model to use (None = configured image.edit_model)

  • size (str) – Output image size

  • n (int) – Number of variations to generate

  • **kwargs – Additional provider-specific parameters

Return type:

Union[GeneratedImage, list[GeneratedImage]]

Returns:

GeneratedImage or list of GeneratedImage objects

Examples

>>> from aix.image import edit_image
>>> edited = edit_image(
...     "photo.png",
...     "Add a rainbow in the sky",
...     mask_path="sky_mask.png"
... )
>>> edited.save("edited_photo.png")
aix.embed(text, *, model=None, **kwargs)[source]

Generate embedding for a single text.

Convenience function for embedding a single text string.

Parameters:
  • text (str) – Text string to embed

  • model (str) – Model identifier

  • **kwargs – Additional parameters for embeddings()

Return type:

Sequence[float]

Returns:

Vector embedding as sequence of floats

Examples

>>> from aix.embeddings import embed
>>> vec = embed("Hello, world!")
>>> len(vec)
1536
>>> # Compare similarity
>>> import numpy as np
>>> v1 = np.array(embed("cat"))
>>> v2 = np.array(embed("kitten"))
>>> v3 = np.array(embed("computer"))
>>> # Cosine similarity
>>> np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
0.92  # High similarity
>>> np.dot(v1, v3) / (np.linalg.norm(v1) * np.linalg.norm(v3))
0.23  # Low similarity
aix.embeddings(segments, *, model=None, api_key=None, **kwargs)[source]

Generate embeddings for multiple text segments.

This is the main embedding interface for AIX. It abstracts away provider-specific details and provides a clean, consistent API across all embedding models.

Parameters:
  • segments (Iterable[str]) – Iterable of text strings to embed

  • model (str) – Model identifier (e.g., ‘text-embedding-3-small’, ‘text-embedding-ada-002’, ‘openrouter/openai/text-embedding-3-small’). If None, uses default.

  • api_key (str) – Explicit API key. If None, resolved from the environment / .env / AIX config store for the model’s provider (see aix.credentials).

  • **kwargs – Additional provider-specific parameters passed to LiteLLM

Yields:

Vector embeddings as sequences of floats. Each embedding corresponds to one input segment in the same order.

Raises:
Return type:

Iterable[Sequence[float]]

Examples

>>> from aix.embeddings import embeddings
>>> texts = ["cat", "dog", "bird"]
>>> vecs = list(embeddings(texts))
>>> len(vecs)
3
>>> # With specific model
>>> vecs = list(embeddings(
...     ["hello", "world"],
...     model="text-embedding-3-large"
... ))
>>> # Process in chunks for large datasets
>>> def chunk_texts(texts, size=100):
...     for i in range(0, len(texts), size):
...         yield texts[i:i+size]
>>> all_vecs = []
>>> for chunk in chunk_texts(large_dataset):
...     all_vecs.extend(embeddings(chunk))
aix.extend_video(video_path, prompt=None, *, extend_duration=2.0, model=None, **kwargs)[source]

Extend an existing video with additional generated content.

Parameters:
  • video_path (Union[str, Path]) – Path to the source video

  • prompt (str) – Optional text prompt to guide the extension

  • extend_duration (float) – How many seconds to add

  • model (str) – Video generation model

  • **kwargs – Additional provider-specific parameters

Return type:

GeneratedVideo

Returns:

GeneratedVideo object with extended content

Examples

>>> from aix.video import extend_video
>>> extended = extend_video(
...     "original.mp4",
...     prompt="Continue the same scene",
...     extend_duration=3
... )
aix.find_models(query)[source]

Search for models matching a query.

Convenience function that uses the global models instance.

Parameters:

query (str) – Search query

Return type:

list[Model]

Returns:

List of matching models

Examples

>>> from aix.models import find_models
>>> results = find_models('claude')
>>> any('claude' in m.id.lower() for m in results)
True
aix.find_most_similar(query, candidates, *, model=None, top_k=5, **kwargs)[source]

Find most similar texts to a query.

Parameters:
  • query (Union[str, Sequence[float]]) – Query text or pre-computed embedding vector

  • candidates (Iterable[str]) – Candidate texts to compare against

  • model (str) – Embedding model to use

  • top_k (int) – Number of top results to return

  • **kwargs – Additional parameters for embeddings()

Return type:

list[tuple[str, float]]

Returns:

List of (text, similarity_score) tuples, sorted by similarity (highest first)

Examples

>>> query = "What is machine learning?"
>>> docs = [
...     "Machine learning is a type of AI",
...     "Python is a programming language",
...     "Neural networks are used in deep learning",
... ]
>>> results = find_most_similar(query, docs, top_k=2)
>>> results[0][0]  # Most similar doc
'Machine learning is a type of AI'
aix.generate_image(prompt, *, model=None, size=None, quality=None, style=None, response_format=None, api_key=None, **kwargs)[source]

Generate a single image from a text prompt.

Parameters:
  • prompt (str) – Text description of the image to generate

  • model (str) – Model to use (e.g., ‘openai/gpt-image-1.5’, ‘openai/gpt-image-1-mini’, ‘stable-diffusion’)

  • size (str) – Image size (e.g., ‘1024x1024’, ‘512x512’, ‘1792x1024’)

  • quality (str) – Image quality (‘standard’ or ‘hd’ for DALL-E 3)

  • style (str) – Image style (‘vivid’ or ‘natural’ for DALL-E 3)

  • response_format (str) – Format of response (‘url’ or ‘b64_json’). Left out of the request when None, since some providers and models (OpenAI’s gpt-image models, and the images endpoint as of 2026) reject the parameter.

  • api_key (str) – Explicit API key. If None, resolved from the environment / .env / AIX config store for the model’s provider (see aix.credentials).

  • **kwargs – Additional provider-specific parameters

Return type:

GeneratedImage

Returns:

GeneratedImage object

Raises:

ImportError – If LiteLLM is not installed

Examples

>>> from aix.image import generate_image
>>> image = generate_image("A serene mountain landscape")
>>> image.save("landscape.png")
>>> # High quality with DALL-E 3
>>> image = generate_image(
...     "Abstract art with vibrant colors",
...     model="gpt-image-1.5",
...     quality="high",
... )
>>> # Specific size
>>> image = generate_image(
...     "A futuristic city",
...     size="1792x1024"
... )
aix.generate_images(prompt, *, n=None, model=None, size=None, quality=None, style=None, response_format=None, api_key=None, **kwargs)[source]

Generate multiple images from a text prompt.

Parameters:
  • prompt (str) – Text description of images to generate

  • n (int) – Number of images to generate

  • model (str) – Model to use

  • size (str) – Image size

  • quality (str) – Image quality

  • style (str) – Image style

  • response_format (str) – Format of response, sent only when given

  • **kwargs – Additional provider-specific parameters

Return type:

list[GeneratedImage]

Returns:

List of GeneratedImage objects

Examples

>>> from aix.image import generate_images
>>> images = generate_images(
...     "A cute robot",
...     n=3,
...     size="512x512"
... )
>>> for i, img in enumerate(images):
...     img.save(f"robot_{i}.png")
aix.generate_video(prompt, *, model=None, duration=5.0, resolution='1280x720', fps=24, aspect_ratio=None, style=None, seed=None, api_key=None, **kwargs)[source]

Generate a video from a text prompt.

Note

This is a high-level interface. Actual implementation depends on available video generation providers (Runway, Pika, etc.) and may require provider-specific API keys.

Parameters:
  • prompt (str) – Text description of the video to generate

  • model (str) – Video generation model to use

  • duration (float) – Video duration in seconds (typically 2-10 seconds)

  • resolution (str) – Video resolution (‘1280x720’, ‘1920x1080’, etc.)

  • fps (int) – Frames per second

  • aspect_ratio (str) – Aspect ratio (‘16:9’, ‘9:16’, ‘1:1’, etc.)

  • style (str) – Video style hint (provider-specific)

  • seed (int) – Random seed for reproducibility

  • api_key (str) – Explicit API key for the video provider. If None, resolved from the environment / .env / AIX config store (see aix.credentials).

  • **kwargs – Additional provider-specific parameters

Return type:

GeneratedVideo

Returns:

GeneratedVideo object

Raises:

Examples

>>> from aix.video import generate_video
>>> video = generate_video(
...     "A serene ocean sunset with gentle waves",
...     duration=5,
...     resolution="1920x1080"
... )
>>> video.save("sunset.mp4")
>>> # Specific style
>>> video = generate_video(
...     "A futuristic city",
...     style="cyberpunk",
...     duration=4
... )
aix.get_config()[source]

Return the current active AixConfig.

Inside a using() block this is the scoped config of the current thread or asyncio task; otherwise the process-wide config.

Return type:

AixConfig

aix.get_model_info(model_id)[source]

Get information about a specific model.

Convenience function that uses the global models instance.

Parameters:

model_id (str) – Model identifier

Return type:

Model

Returns:

Model object

Examples

>>> from aix.models import get_model_info
>>> info = get_model_info('openai/gpt-4o')
>>> info.provider
'openai'
aix.get_video_providers()

Get list of available video generation providers.

Return type:

list[str]

Returns:

List of provider names that are configured

Examples

>>> from aix.video import get_available_providers
>>> providers = get_available_providers()
>>> print(providers)
['runway', 'pika']
aix.jsonl_logger(path)[source]

A logger that appends one JSON line per call to path.

Return type:

Callable[[CallRecord], None]

aix.load_config(path=None, *, environ=None)[source]

Resolve an AixConfig from shipped defaults, TOML file, and env.

Precedence (low to high): shipped defaults < TOML file < environment variables. Runtime overrides (configure()/using()) and explicit call arguments sit above this and are applied elsewhere.

Parameters:
  • path (Optional[str]) – Optional explicit TOML path. Defaults to config_file_path().

  • environ (Optional[Mapping[str, str]]) – Optional environment mapping (defaults to os.environ).

Return type:

AixConfig

Returns:

A fully resolved AixConfig.

aix.prompt_func(template, *, output_schema=None, response_schema=None, egress=None, model=None, temperature=None, name=None, **chat_kwargs)[source]

Create a callable function from a prompt template.

This is the main function for creating prompt-based functions. It automatically detects parameters from the template and creates a function with those parameters.

Without output_schema: Returns text With output_schema: Returns structured data (dict, list, etc.) With egress: Returns whatever the egress post-processor returns.

Templates use the default-aware {name:default} dialect (matching oa.prompt_function): {name} is a required parameter, {name:default} supplies a default value (the text after the colon), and braces inside ` fenced ` regions are left literal. Plain {name}-only templates behave exactly as before.

>>> greet = prompt_func("Greet {name} in {language:English}")
>>> greet.param_names
['name', 'language']

The signature lists every template field, keyword-only, with its default:

>>> from inspect import signature
>>> str(signature(prompt_func("{a} {b:x}")))
"(*, a: str, b: str = 'x')"
Parameters:
  • template (str) – Prompt template with {var} placeholders for parameters

  • output_schema (Union[dict, type]) – Optional schema for structured output. Can be: - Dict mapping field names to types: {“name”: str, “age”: int} - A single type for simple outputs: str, int, list, etc. - None for plain text output (default)

  • response_schema (Union[dict, type]) – Optional JSON Schema dict or Pydantic model class for enforced, validated structured output (nested objects, arrays, enums, required/optional all work): routed to the provider’s strict json_schema mode where supported, otherwise JSON mode, then validated client-side with a bounded repair retry (see aix.complete()). The function returns the validated value (a model instance for a Pydantic schema) or raises aix.SchemaValidationError. Prefer it over output_schema, which is flat, prompt-only and unvalidated; pass one or the other.

  • egress (Callable[[Any], Any]) – Optional post-processor (result) -> Any applied to the output before returning — on both the text and structured paths. Lets a caller keep “prompt → typed Python value” inside the facade (e.g. parse the LLM text into a list of lines/ids) instead of wrapping the returned function. None (default) returns the raw result unchanged.

  • model (str) – Model to use for this function

  • temperature (float) – Temperature for generation

  • name (str) – Optional __name__ for the generated function (for tracing / identity). Defaults to "prompt_based_function".

  • **chat_kwargs – Additional parameters passed to chat()

Return type:

Callable

Returns:

Callable function with parameters derived from template

Examples

>>> # Simple text generation
>>> summarize = prompt_func("Summarize this text: {text}")
>>> summarize(text="Long article...")
'Brief summary...'
>>> # Structured output
>>> extract = prompt_func(
...     "Extract contact info from: {text}",
...     output_schema={"name": str, "email": str, "phone": str}
... )
>>> result = extract(text="Contact John at john@example.com, 555-1234")
>>> result['name']
'John'
>>> # Multiple parameters
>>> compare = prompt_func(
...     "Compare {item1} and {item2} in terms of {aspect}. "
...     "Keep it under {word_limit} words."
... )
>>> compare(
...     item1="Python",
...     item2="Java",
...     aspect="learning curve",
...     word_limit=50
... )
'Python has a gentler learning curve...'
>>> # With specific model
>>> creative_writer = prompt_func(
...     "Write a creative story about {topic}",
...     model="gpt-4o",
...     temperature=1.5
... )
>>> creative_writer(topic="a time-traveling cat")
'Once upon a time, there was a cat named Whiskers...'
aix.prompt_to_json(template, schema, **kwargs)[source]

Create a function that returns structured JSON output.

This is an explicit alias for prompt_func with output_schema.

Parameters:
  • template (str) – Prompt template

  • schema (Union[dict, type]) – Output schema

  • **kwargs – Additional parameters for prompt_func

Return type:

Callable

Returns:

Function that returns structured data

Examples

>>> extract = prompt_to_json(
...     "Extract name and age from: {text}",
...     schema={"name": str, "age": int}
... )
>>> result = extract(text="Alice is 30")
>>> isinstance(result, dict)
True
aix.prompt_to_text(template, **kwargs)[source]

Create a function that returns text output.

This is an explicit alias for prompt_func without output_schema.

Parameters:
  • template (str) – Prompt template

  • **kwargs – Additional parameters for prompt_func

Return type:

Callable

Returns:

Function that returns text

Examples

>>> summarize = prompt_to_text("Summarize: {text}")
>>> result = summarize(text="Long text...")
>>> isinstance(result, str)
True
aix.resolve_api_key(model_or_provider, *, api_key=None, prompt_if_missing=False)[source]

Resolve an API key for model_or_provider through the documented layers.

Layers, highest precedence first: explicit api_key argument, provider environment variable (with soft .env discovery), the AIX config store, and – only when prompt_if_missing is true and running interactively – an interactive prompt that persists the answer.

Parameters:
  • model_or_provider (Optional[str]) – A model id (provider inferred via LiteLLM) or a provider name directly (e.g. "openai").

  • api_key (Optional[str]) – An explicit key; when given (non-empty) it is returned verbatim.

  • prompt_if_missing (bool) – If true, fall back to a REPL prompt + persist when no key is found elsewhere. Off by default so the common path never blocks on input.

Return type:

Optional[str]

Returns:

The resolved key, or None if genuinely absent.

Examples

>>> resolve_api_key("gpt-4o", api_key="sk-explicit")
'sk-explicit'
aix.resolve_model(model, *, config=None)[source]

Resolve a semantic alias ("fast", "best", …) to a concrete model id.

Plain substitution: if model is a key in the active aliases table it is replaced (following chains, with cycle protection). Anything that is not an alias – including every literal model id like "gpt-4o" – is returned unchanged. None passes through (callers apply their own default first).

Note

aliases share a namespace with literal model ids, so an unknown name is treated as a literal id, not an error. Inspect available aliases via aix.get_config().aliases.

Examples

>>> from aix import config
>>> config.resolve_model("fast") in config.DEFAULT_ALIASES.values()
True
>>> config.resolve_model("gpt-4o")  # not an alias -> unchanged
'gpt-4o'
>>> config.resolve_model(None) is None
True
Return type:

Optional[str]

aix.sample(prompt, *, n, temperature=None, seed=None, concurrency=None, model=None, strategy='auto', parse=None, response_schema=None, on_error='raise', api_key=None, **kwargs)[source]

Draw n answers to prompt, each with its finish reason and usage.

Parameters:
  • prompt (Union[str, Iterable[dict]]) – A string or a list of message dicts, as for aix.chat().

  • n (int) – How many samples to draw.

  • temperature (float) – Sampling temperature (None = configured default). At 0 the samples mostly coincide, which is rarely what you want here.

  • seed (int) – Base seed. A provider-side n request sends it as is; each independent request sends a seed derived from (seed, index) so independent samples are not forced identical and runs with different base seeds do not overlap. Support is provider-dependent.

  • concurrency (int) – Max simultaneous independent requests (None = config chat.sample_concurrency).

  • model (str) – Model id or alias (None = configured default).

  • strategy (Literal['auto', 'provider', 'independent']) – "auto" (provider n when supported, else independent; also falls back to independent if LiteLLM or the provider refuses n – for a provider 400 the first independent request is sent alone as a probe, and if it fails too the original 400 is raised; see Samples.fallback_error), "provider" (force one n request) or "independent". n=1 is always a single plain request, recorded "independent".

  • response_schema (Union[dict, type]) – A JSON Schema dict or Pydantic model class, enforced and validated per request as in aix.complete(); each payload is the validated value, and a choice still invalid after repairs records its SchemaValidationError as error. Exclusive with parse.

  • parse (Callable[[str], Any]) – Optional text -> payload (e.g. json.loads). A failure is recorded on that sample (payload=None, error=...), not raised.

  • on_error (Literal['raise', 'record']) – When a request fails: "raise" (default) raises SamplingError once the launched requests finish, carrying the partial batch; "record" returns the batch with the failure on that sample’s error.

  • api_key (str) – Explicit API key, as for aix.chat().

  • **kwargs – Passed to every request (e.g. max_tokens, response_format).

Return type:

Samples

Returns:

Samples – a list of Sample with batch .strategy, .usage, .n_requests.

Raises:
  • ValueError – For a non-positive n / concurrency, an unknown strategy / on_error, or a reserved kwarg (messages, stream).

  • SamplingError – A request failed and on_error="raise".

aix.set_call_logger(logger)[source]

Install logger for this context (None turns logging off).

Return type:

None

aix.set_config(config)[source]

Replace the active config wholesale. Returns the new active config.

Inside a using() block this replaces only that block’s scoped config (it is discarded on exit); outside, it replaces the process-wide config.

Return type:

AixConfig

aix.supported_params(model=None)[source]

The OpenAI-style parameters LiteLLM says model accepts.

None when that is unknown (LiteLLM cannot place the model, or is not installed) – which is not the same as “supports nothing”.

Parameters:

model (Optional[str]) – Model id or alias; None means the configured chat default.

Return type:

Optional[frozenset]

aix.supports(model, param)[source]

Whether model is known to accept param – i.e. whether LiteLLM forwards it to the provider for this model.

Conservative: False when support is unknown (or for a non-string param), so a caller that branches on it takes the path that works everywhere. True is not a guarantee that the parameter has an effect: a router (OpenRouter…) can forward seed / n to an upstream model that drops them, and a provider can deprecate or ignore a parameter (seeding is best-effort everywhere; reasoning models may ignore it).

Parameters:
  • model (Optional[str]) – Model id or alias; None means the configured chat default.

  • param (str) – An OpenAI-style request parameter name ("n", "seed", "response_format"…) or a capability in CAPABILITIES ("response_schema").

Return type:

bool

>>> supports("gpt-4o-mini", "seed")
True
>>> supports("gpt-4o-mini", "response_schema")
True
aix.text_to_speech(text, *, model=None, voice=None, speed=None, response_format='mp3', api_key=None, **kwargs)[source]

Convert text to speech audio.

Parameters:
  • text (str) – Text to convert to speech

  • model (str) – TTS model to use (e.g., ‘tts-1’, ‘tts-1-hd’)

  • voice (str) – Voice to use (‘alloy’, ‘echo’, ‘fable’, ‘onyx’, ‘nova’, ‘shimmer’)

  • speed (float) – Playback speed (0.25 to 4.0)

  • response_format (str) – Audio format (‘mp3’, ‘opus’, ‘aac’, ‘flac’)

  • **kwargs – Additional provider-specific parameters

Return type:

GeneratedAudio

Returns:

GeneratedAudio object

Raises:

ImportError – If LiteLLM is not installed

Examples

>>> from aix.audio import text_to_speech
>>> audio = text_to_speech("Hello, how are you?")
>>> audio.save("greeting.mp3")
>>> # Different voice and speed
>>> audio = text_to_speech(
...     "This is a test.",
...     voice="nova",
...     speed=1.2
... )
>>> # High quality
>>> audio = text_to_speech(
...     "Important announcement",
...     model="tts-1-hd",
...     voice="onyx"
... )
aix.to_image_content(image, *, detail=None)[source]

Build a multimodal image_url content block for image.

image may be:

  • an http(s):// URL or a data: URI — passed through verbatim;

  • a local file path (str or Path) — read and inlined as a base64 data: URI with a guessed MIME type;

  • raw bytes — base64-inlined (MIME sniffed from magic bytes, else JPEG);

  • a PIL Image — encoded to PNG and inlined.

detail ("low" | "high" | "auto") is forwarded when set; the block is the OpenAI/LiteLLM multimodal shape understood across providers.

>>> to_image_content("https://x/y.jpg")
{'type': 'image_url', 'image_url': {'url': 'https://x/y.jpg'}}
>>> to_image_content("data:image/png;base64,AAAA")["image_url"]["url"][:10]
'data:image'
Return type:

dict

aix.transcribe(audio, *, engine=None, model=None, language=None, prompt=None, response_format='text', temperature=None, timestamp_granularities=None, api_key=None, **kwargs)[source]

Transcribe audio to text.

By default this routes through LiteLLM (OpenAI-style transcription). Pass engine= to instead delegate to a scribed backend — one façade over many ASR engines (local Whisper / faster-whisper / vosk, or cloud Deepgram / AssemblyAI / Groq / ElevenLabs / Google …) with speaker diarization and SRT/VTT output. The return type is unchanged either way, so existing callers are unaffected.

Parameters:
  • audio (Union[str, Path, BinaryIO, bytes]) – Audio file path, file object, or bytes.

  • engine (str) – Optional scribed backend id (e.g. "faster-whisper", "deepgram"). When given, transcription is delegated to scribed (which resolves that engine’s own credentials); the LiteLLM path is bypassed. Requires pip install 'aix[scribed]'. See scribed.list_backends().

  • model (str) – Transcription model (e.g. 'whisper-1'); for a scribed engine, the engine-specific model (e.g. a Whisper size).

  • language (str) – Source language (ISO-639-1 code, e.g. 'en', 'es').

  • prompt (str) – Optional text to guide the model’s style (LiteLLM path).

  • response_format (str) – 'text' (default) → str; 'srt'/'vtt' → subtitle str (scribed path); else → TranscriptionResult.

  • temperature (float) – Sampling temperature (LiteLLM path).

  • timestamp_granularities (list[str]) – Timestamp types (‘word’, ‘segment’) (LiteLLM path).

  • **kwargs – Additional parameters (forwarded to LiteLLM, or to the scribed backend — e.g. diarize=True).

Return type:

Union[str, TranscriptionResult]

Returns:

str for response_format in {text, srt, vtt}, else a TranscriptionResult.

Examples

>>> from aix.audio import transcribe
>>> text = transcribe("recording.mp3")
>>> # delegate to a scribed engine (local, free, diarized SRT):
>>> srt = transcribe(
...     "meeting.wav", engine="faster-whisper", response_format="srt"
... )
>>> dg = transcribe(
...     "call.mp3", engine="deepgram", diarize=True,
...     response_format="verbose_json",
... )
aix.transcribe_with_timestamps(audio, *, granularity='segment', model=None, **kwargs)[source]

Transcribe audio with detailed timestamps.

Parameters:
  • audio (Union[str, Path, BinaryIO, bytes]) – Audio file path, file object, or bytes

  • granularity (str) – Timestamp granularity (‘word’ or ‘segment’)

  • model (str) – Transcription model

  • **kwargs – Additional parameters for transcribe()

Return type:

TranscriptionResult

Returns:

TranscriptionResult with detailed segments

Examples

>>> from aix.audio import transcribe_with_timestamps
>>> result = transcribe_with_timestamps("lecture.mp3")
>>> for segment in result.segments:
...     start = segment['start']
...     end = segment['end']
...     text = segment['text']
...     print(f"[{start:.2f}-{end:.2f}] {text}")
aix.translate_audio(audio, *, model=None, prompt=None, api_key=None, **kwargs)[source]

Translate audio from any language to English.

Note

Currently uses Whisper’s translation capability which translates to English.

Parameters:
  • audio (Union[str, Path, BinaryIO, bytes]) – Audio file path, file object, or bytes

  • model (str) – Translation model (typically ‘whisper-1’)

  • prompt (str) – Optional text to guide translation

  • **kwargs – Additional provider-specific parameters

Return type:

str

Returns:

Translated text in English

Examples

>>> from aix.audio import translate_audio
>>> english_text = translate_audio("spanish_audio.mp3")
>>> print(english_text)
'This is the English translation.'
aix.using(**overrides)[source]

Context manager applying scoped overrides, restored on exit.

The override lives in a ContextVar, so it is private to the current thread / asyncio task: concurrent using() blocks do not leak into each other, nor into code running outside any block. A thread you start yourself typically begins with an empty context and sees the process-wide config (carry a scope into it with contextvars.copy_context()); aix’s own worker pools (sample, batch_chat…) propagate it. An asyncio task created inside the block keeps the scope for its lifetime.

Examples

>>> from aix import config
>>> with config.using(chat_temperature=0.0) as c:
...     c.chat.temperature
0.0
Return type:

Iterator[AixConfig]

Modules

config

Central configuration for AIX (single source of truth for defaults).

ai_models

AI Model Management Module.

audio

Audio operations interface for AIX.

batches

Batch processing interface for AIX.

calllog

An opt-in log of aix model calls: the resolved model, the caller, the outcome.

capabilities

What a model supports, asked before calling it.

claude_cli

A chat backend that runs prompts through the Claude Code CLI (claude -p).

credentials

Unified, discoverable API-key / secret resolution for AIX.

gen_ai

Generative AI modules.

image

Image generation interface for AIX.

misc

Misc AIX functions.

models

User-friendly interface for model discovery and selection.

prompts

Prompt-based function creation for AIX.

sampling

Repeated sampling: n answers to one prompt, drawn as fast as the provider allows.

stores

Storage layers for AIX.

structured

Structured output: a schema in, validated values out, enforced as far as the provider allows.

util

Utils for AIX.

video

Video generation interface for AIX.

vision

Image-to-text (vision) interface for AIX.