Metadata-Version: 2.5
Name: aix
Version: 0.0.77
Summary: Artificial Intelligence eXtensions
Project-URL: Documentation, https://thorwhalen.github.io/aix/
Project-URL: Homepage, https://github.com/thorwhalen/aix
Project-URL: Repository, https://github.com/thorwhalen/aix
Project-URL: Issues, https://github.com/thorwhalen/aix/issues
Project-URL: Changelog, https://github.com/thorwhalen/aix/blob/master/CHANGELOG.md
Author: Thor Whalen
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: ai,anthropic,embeddings,litellm,llm,multi-provider,openai,prompt-engineering
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: config2py
Requires-Dist: litellm>=1.0.0
Requires-Dist: tomli; python_version < '3.11'
Provides-Extra: all
Requires-Dist: google-generativeai; extra == 'all'
Requires-Dist: huggingface-hub; extra == 'all'
Requires-Dist: i2; extra == 'all'
Requires-Dist: oa; extra == 'all'
Requires-Dist: pillow; extra == 'all'
Requires-Dist: requests; extra == 'all'
Requires-Dist: scribed; extra == 'all'
Requires-Dist: tabled; extra == 'all'
Provides-Extra: discovery
Requires-Dist: requests; extra == 'discovery'
Provides-Extra: google
Requires-Dist: google-generativeai; extra == 'google'
Requires-Dist: i2; extra == 'google'
Provides-Extra: hub
Requires-Dist: huggingface-hub; extra == 'hub'
Provides-Extra: image
Requires-Dist: pillow; extra == 'image'
Requires-Dist: requests; extra == 'image'
Provides-Extra: openai
Requires-Dist: oa; extra == 'openai'
Provides-Extra: scribed
Requires-Dist: scribed; extra == 'scribed'
Provides-Extra: tables
Requires-Dist: tabled; extra == 'tables'
Provides-Extra: testing
Requires-Dist: hypothesis; extra == 'testing'
Requires-Dist: pytest; extra == 'testing'
Provides-Extra: video
Requires-Dist: diffusers; extra == 'video'
Requires-Dist: requests; extra == 'video'
Requires-Dist: torch; extra == 'video'
Description-Content-Type: text/markdown

# AIX: Artificial Intelligence eXtensions

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

**Philosophy**: Make AI interactions as simple and intuitive as Python itself, while maintaining the power and flexibility needed for production use.

## Installation

```bash
pip install aix
```

`aix` is a headless facade and keeps its hard dependencies minimal — the base
install only pulls in [`litellm`](https://github.com/BerriAI/litellm) (the
provider backend) and `config2py` (for reading API keys / config). Optional
capabilities live in extras and are imported lazily, raising a clear install
hint if their backend is missing:

```bash
pip install "aix[image]"      # image generation helpers (Pillow)
pip install "aix[video]"      # local text-to-video (diffusers, torch)
pip install "aix[discovery]"  # model discovery via OpenRouter / Ollama (requests)
pip install "aix[google]"     # legacy Google Gemini backend
pip install "aix[openai]"     # legacy OpenAI (oa) backend
pip install "aix[all]"        # all optional backends
```

With a Claude subscription and the [Claude Code CLI](https://docs.claude.com/en/docs/claude-code/setup) installed, `chat("...", model="claude-cli/haiku")` (or `sonnet`, `opus`) runs the prompt through `claude -p` with no API key. The CLI has no sampling controls, so `temperature`, `max_tokens`, `stream` and the like raise `ValueError`; the cost it reports is `claude_cli_cost(complete(...))`.

For a run that needs tools, `aix.claude_cli.claude_cli_agent(prompt, model="claude-cli/sonnet", mcp_servers={...})` starts the same CLI as an agent that has only the tools of the MCP servers you pass (no shell, no file access, no web, no connector of the signed-in account unless you list a built-in tool), with limits on turns, spend and time. With `expect_tools=[...]` the tool list the CLI reports is checked before your prompt is sent, which is what you want when the prompt holds text you do not trust. It returns the final text, the tool calls made, the number of turns, the token counts and the reported cost; a run stopped by a limit raises `AgentStopped`, which carries what the run had already done.

## Quick Start

<!-- wads-docs: skip needs a provider API key -->
```python
from aix import chat, embeddings, prompt_func, models
from aix import generate_image, text_to_speech, transcribe

# Simple chat
response = chat("What is 2+2?")
print(response)  # "The answer is 4."

# Create prompt-based functions
translate = prompt_func("Translate to French: {text}")
result = translate(text="Hello world")
print(result)  # "Bonjour le monde"

# Get embeddings
vecs = list(embeddings(["hello", "world"]))
print(len(vecs))  # 2

# Generate images
image = generate_image("A serene mountain landscape")
image.save("landscape.png")

# Text to speech
audio = text_to_speech("Hello, world!")
audio.save("hello.mp3")

# Speech to text
text = transcribe("recording.mp3")

# Discover available models
models.discover()
print(list(models)[:5])  # ['openai/gpt-4o', 'openai/gpt-4o-mini', ...]
```

## Configuration

`aix` works with zero configuration — every function ships with sensible default
models. When you want to change *which model a function uses by default* (and
related parameters like temperature, image size, or TTS voice), there is a single
source of truth: `aix.config`.

Defaults are resolved in layers, **highest precedence first**:

1. **Explicit call argument** — `chat("hi", model="...")` always wins.
2. **Runtime override** — `aix.configure(...)` (persistent) or `aix.using(...)` (scoped).
3. **Environment variables** — `AIX_CHAT_MODEL`, `AIX_CHAT_TEMPERATURE`,
   `AIX_EMBEDDING_MODEL`, `AIX_IMAGE_MODEL`, `AIX_TTS_MODEL`, `AIX_TTS_VOICE`,
   `AIX_TRANSCRIPTION_MODEL`, …
4. **User config file** — a TOML file (see below).
5. **Shipped defaults** — the built-in values.

<!-- wads-docs: skip needs a provider API key -->
```python
import aix

# Inspect the active configuration
cfg = aix.get_config()
cfg.chat.model  # 'gpt-4.1-mini'
cfg.embeddings.model  # 'text-embedding-3-small'

# Persistently change a default (everything below an explicit arg still respects it)
aix.configure(chat_model="anthropic/claude-sonnet-4", chat_temperature=0.2)

# Scoped override that restores on exit
with aix.using(chat_model="openai/gpt-4o-mini"):
    aix.chat("quick + cheap question")
# back to the configured default here
```

### Semantic aliases

Pass an intent-level name instead of a concrete model id. Shipped aliases:
`fast` (cheap/low-latency), `best` (highest quality), `cheap` (cheapest).

<!-- wads-docs: skip needs a provider API key -->
```python
aix.chat("hard question", model="best")  # -> resolves via the alias table
aix.chat("quick question", model="fast")

# Add or override aliases (merges with the shipped set)
aix.configure(aliases={"smart": "anthropic/claude-sonnet-4"})
aix.resolve_model("smart")  # 'anthropic/claude-sonnet-4'
```

Aliases share a namespace with literal model ids: a name that is not a registered
alias (e.g. `"gpt-4o"`) is passed through unchanged. Inspect available aliases via
`aix.get_config().aliases`.

### Config file

Create a TOML file at your platform's app-config dir (or point `AIX_CONFIG_FILE`
at any path):

```toml
[chat]
model = "gpt-4.1-mini"
temperature = 1.0

[embeddings]
model = "text-embedding-3-small"

[image]
model = "openai/gpt-image-1.5"
size = "1024x1024"
edit_model = "openai/gpt-image-1.5"

[audio]
tts_model = "gpt-4o-mini-tts"
tts_voice = "alloy"
transcription_model = "whisper-1"

[aliases]              # semantic names -> concrete ids (override the shipped set)
fast = "gpt-4.1-mini"
best = "anthropic/claude-sonnet-4"
```

Find the active path with `aix.config.config_file_path()`. Environment variables
override file values; explicit call arguments override everything.

## Providing credentials

Every key-requiring function (`chat`, `embeddings`, `generate_image`,
`text_to_speech`, `transcribe`, `generate_video`, ...) resolves its API key
through one documented path. The resolution order, highest precedence first:

1. **Explicit argument** — `chat("hi", api_key="sk-...")` (keyword-only, on every
   key-requiring function).
2. **Provider environment variable** — the canonical name for the model's
   provider (see the table below). A project `.env` is *softly* discovered when
   `python-dotenv` is installed; an explicitly exported variable always wins over
   a `.env` value.
3. **AIX config store** — a per-user store in your app-config folder, keyed by the
   canonical env-var name (so the store and the env layer share one namespace).
4. **(Interactive only) prompt + persist** — in a REPL, AIX can ask once and save
   the key to the config store.

The provider is inferred from the model id, so you rarely name it yourself:

```python
import aix

aix.chat("Hello", model="gpt-4o")  # uses OPENAI_API_KEY
aix.chat("Hi", model="claude-sonnet-4")  # uses ANTHROPIC_API_KEY
aix.chat("Yo", api_key="sk-...")  # explicit key wins

# Check what's discoverable (values are never shown — availability only):
aix.check_keys()
# {'openai': {'available': True, 'env_vars': ['OPENAI_API_KEY'], 'source': 'env'}, ...}
```

When a required key is missing, you get an actionable `MissingCredentialError`
naming *which* key, *how* to set it, and *where* to get one — instead of a cryptic
provider error:

```python
>>> aix.chat("hi", model="gpt-4o")
aix.credentials.MissingCredentialError: No API key found for provider 'openai'
(model 'gpt-4o'). Set OPENAI_API_KEY via one of:
  - export it:  export OPENAI_API_KEY=...
  - add it to a .env file in your project, or
  - store it in the AIX config store under the key 'OPENAI_API_KEY'.
Get a key at: https://platform.openai.com/api-keys
```

### Provider → environment variable

| Provider | Environment variable | Get a key |
|---|---|---|
| OpenAI | `OPENAI_API_KEY` | https://platform.openai.com/api-keys |
| Anthropic | `ANTHROPIC_API_KEY` | https://console.anthropic.com/settings/keys |
| Google Gemini | `GEMINI_API_KEY` (or `GOOGLE_API_KEY`) | https://aistudio.google.com/apikey |
| OpenRouter | `OPENROUTER_API_KEY` | https://openrouter.ai/keys |
| Mistral | `MISTRAL_API_KEY` | https://console.mistral.ai/api-keys/ |
| Cohere | `COHERE_API_KEY` | https://dashboard.cohere.com/api-keys |
| Groq | `GROQ_API_KEY` | https://console.groq.com/keys |
| DeepSeek | `DEEPSEEK_API_KEY` | https://platform.deepseek.com/api_keys |
| xAI | `XAI_API_KEY` | https://console.x.ai/ |
| Perplexity | `PERPLEXITYAI_API_KEY` | https://www.perplexity.ai/settings/api |
| Runway (video) | `RUNWAY_API_KEY` | https://app.runwayml.com/ |

The full mapping is `aix.PROVIDER_ENV_VARS`. Keys are never logged, and the config
store lives in your user app-config folder — never in the repo.

## Core Features

### 1. Chat Interface

Clean, provider-agnostic chat completions:

<!-- wads-docs: skip needs an Anthropic API key -->
```python
from aix import chat

# Simple text prompt
response = chat("Explain quantum computing in one sentence")

# With specific model
response = chat("Hello!", model="gpt-4o-mini")

# With message history
messages = [
    {"role": "user", "content": "My name is Alice"},
    {"role": "assistant", "content": "Nice to meet you, Alice!"},
    {"role": "user", "content": "What's my name?"},
]
response = chat(messages, model="gpt-4o")

# Streaming responses
for chunk in chat("Count to 5", stream=True):
    print(chunk, end="", flush=True)

# Stateful conversations
from aix import chat_with_history

session = chat_with_history("You are a helpful math tutor")
response = session.send("What is 2+2?")
response = session.send("And if I add 3 to that?")  # Remembers context
```

`chat()` returns only the first choice's text. When you need the rest of the response (every one of `n` choices, token usage, why each choice stopped, the model that actually served the call), use `complete()`, which takes the same arguments and returns a `Completion`:

<!-- wads-docs: skip needs an Anthropic API key -->
```python
from aix import complete, Usage

c = complete("Name a color", n=3, temperature=1.0)
c.texts  # ('Blue', 'Green', 'Red')     -- all n choices
c.finish_reasons  # ('stop', 'stop', 'stop')     -- 'length' means truncated by max_tokens
c.usage  # Usage(prompt_tokens=11, completion_tokens=6, total_tokens=17, cached_prompt_tokens=0, ...)
c.model  # the model id the provider reports having served
c.text  # first choice, i.e. what chat() would return
c.raw  # the untouched LiteLLM response

# Usage values add up, for cost reporting. usage is None when a provider reports none.
cs = [complete(q) for q in questions]
total = sum((c.usage for c in cs if c.usage), Usage())
```

To ask the same question several times (agreement, stability, majority vote), use `sample()`. It sends one request with provider-side `n` when LiteLLM reports that the model supports it, and otherwise makes `n` independent requests concurrently. It records which path it took, because the two are not the same statistical object:

<!-- wads-docs: skip needs an Anthropic API key -->
```python
import json
from aix import sample

s = sample(
    'Is a tomato a fruit? Reply as JSON {"answer": bool}',
    n=5,
    temperature=1.0,
    parse=json.loads,
)
s.strategy  # 'provider_n', 'independent' or 'mixed'
s.payloads  # parsed answers (None where parsing failed)
[x.finish_reason for x in s]  # 'content_filter' means refused, 'length' means truncated
s.usage  # total tokens across every request that reported usage
s.n_requests  # how many requests were made
```

A failed request does not discard the work already paid for. By default `sample()` raises `SamplingError` once the launched requests finish, and the partial batch is on its `.samples`. With `on_error="record"`, the failure is stored on that sample's `.error` instead. A `seed` is sent as-is with a provider-side `n` request; each independent request gets a seed derived from `(seed, index)`.

`constrained_answer(..., n=k)` now runs its `k` calls concurrently too (`concurrency=`, default from config `chat.sample_concurrency`).

#### Seeds, determinism, and asking before calling

`complete()` and `sample()` take a keyword-only `seed`. Its support is provider-dependent, and even where it is supported, determinism is best-effort. So before you read run-to-run variance as a property of the model, check two things:

<!-- wads-docs: skip needs an Anthropic API key -->
```python
from aix import supports, complete

supports("gpt-4o-mini", "seed")  # True  -- LiteLLM forwards seed (best-effort)
supports(
    "anthropic/claude-sonnet-4", "seed"
)  # False -- seed would be dropped or rejected
supports("gpt-4o-mini", "n")  # provider-side n (what sample() prefers)
supports(
    "gpt-4o-mini", "response_schema"
)  # strict/schema structured output (response_schema=)

a = complete("...", seed=7, temperature=0)
b = complete("...", seed=7, temperature=0)
a.system_fingerprint == b.system_fingerprint  # if this differs, the backend changed: the comparison is void
```

`supports(model, param)` wraps LiteLLM's `get_supported_openai_params`, and `"response_schema"` is answered by `supports_response_schema`. It is conservative: `False` means "not known to work", so if you branch on it you take the path that works everywhere. `True` only means LiteLLM forwards the parameter. A router such as OpenRouter can still drop `seed` or `n` upstream, and seeding is best-effort on every provider (reasoning models may ignore it). That is why the fingerprint check matters. Each `Sample` from `sample()` also carries its `system_fingerprint`.

### 2. Embeddings

Generate vector embeddings for semantic search and similarity:

<!-- wads-docs: skip needs a provider API key -->
```python
from aix import embeddings, embed, cosine_similarity, find_most_similar

# Batch embeddings
texts = ["cat", "dog", "bird"]
vecs = list(embeddings(texts))

# Single text
vec = embed("Hello, world!")

# Compute similarity
v1 = embed("cat")
v2 = embed("kitten")
similarity = cosine_similarity(v1, v2)  # High similarity

# Find most similar documents
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)
# Returns: [('Machine learning is a type of AI', 0.95), ...]

# Caching for efficiency
from aix import EmbeddingCache

cache = EmbeddingCache()
v1 = cache.embed("hello")  # API call
v2 = cache.embed("hello")  # From cache
```

### 2b. Tools: a model that calls your Python functions

`run_with_tools` sends a prompt with a schema for each function (read from its signature and docstring), runs every call the model asks for, sends the results back, and repeats until the model answers. `python_tool()` is a ready-made local Python interpreter, with this environment's packages importable and no API keys in its environment. Each program is stopped past a wall-clock timeout (60 s) and a memory cap (2 GB, and `RLIMIT_AS` on Linux), together with anything it started. It runs model-written code on your machine: it is not a sandbox.

<!-- wads-docs: skip needs a provider API key -->
```python
from aix import run_with_tools, python_tool


def word_count(text: str) -> int:
    """Count the words in a text."""
    return len(text.split())


run = run_with_tools(
    "How many words in 'to be or not to be'?", [word_count], model="gpt-4o-mini"
)
(
    run.text,
    run.stop,
    run.turns,
    run.usage,
)  # the answer, why it stopped, model calls, summed tokens
run.calls  # every ToolCall(name, arguments, result)

run = run_with_tools(
    "What is the 30th Fibonacci number? Compute it.",
    [python_tool(max_memory_mb=1024)],
    model="gemini/gemini-3.1-flash-lite",
    max_turns=10,
    keep_going=lambda r: r.usage.total_tokens < 200_000,
)
```

### 3. Prompt-Based Functions

Transform natural language prompts into reusable Python functions:

```python
from aix import prompt_func, prompt_to_text, prompt_to_json

# Simple text generation
summarize = prompt_func("Summarize this text: {text}")
summary = summarize(text="Long article...")

# Structured output
extract_person = prompt_func(
    "Extract person information from: {text}",
    output_schema={"name": str, "age": int, "email": str},
)
result = extract_person(text="Contact John at john@example.com. He is 30 years old.")
# Returns: {'name': 'John', 'age': 30, 'email': 'john@example.com'}

# Multiple parameters
compare = prompt_func("Compare {item1} and {item2} in terms of {aspect}")
result = compare(item1="Python", item2="JavaScript", aspect="learning curve")

# Pre-built common functions
from aix import common_funcs

summary = common_funcs.summarize(text="Long article...")
keywords = common_funcs.extract_keywords(text="Article about AI and ML")
sentiment = common_funcs.sentiment(text="I love this product!")

# Create custom collections
from aix import PromptFuncs

my_funcs = PromptFuncs(model="gpt-4o")
my_funcs.add("analyze", "Analyze this code: {code}")
my_funcs.add("fix_bugs", "Fix bugs in: {code}")

result = my_funcs.analyze(code="def foo(): return bar")
```

#### `prompt_func` and prompt-optimisation frameworks

`prompt_func` is for prompts whose template is *data*: a string constant, or a template loaded from a store at run time. Parameters and `{name:default}` defaults come from the template, `egress=` turns the reply into a typed value, and model and credentials come from aix's configuration. If you would rather declare inputs and outputs and let a framework write and optimise the prompt against a metric, use [DSPy](https://github.com/stanfordnlp/dspy) instead; it does a different job. If your prompts are hand-written Python functions that return a string, [Mirascope](https://github.com/Mirascope/mirascope) fits that style.

#### Enforced, validated structured output

`output_schema` above is flat and only requested in the prompt; nothing checks the reply against it. For anything nested (objects inside objects, arrays of objects, enums, required vs optional), pass `response_schema=`, either a Pydantic model or a JSON Schema dict. It works on `complete()`, `sample()` and `prompt_func()`:

<!-- wads-docs: skip needs an Anthropic API key -->
```python
from typing import Literal
from pydantic import BaseModel
from aix import complete, prompt_func


class Span(BaseModel):
    start: int
    end: int


class Judgement(BaseModel):
    value: Literal["yes", "no", "unsure"]
    confidence: float
    evidence: list[Span]


judge = prompt_func("Does this text claim {claim}? {text}", response_schema=Judgement)
judge(
    claim="...", text="..."
)  # -> Judgement(value='yes', confidence=0.8, evidence=[...])

c = complete("...", response_schema=Judgement)
c.value  # the validated Judgement (raises SchemaValidationError if still invalid)
c.schema_mode  # 'strict' | 'schema' | 'json_mode' -- how the provider enforced it
c.repairs  # extra requests made to fix invalid replies (their tokens are in c.usage)
```

The provider enforces the schema as strongly as the model allows:

- **`strict`**: a strict `json_schema` response format, which constrains decoding. Used when LiteLLM's `supports_response_schema(model)` is true and the schema is strict-compatible (every object closes `additionalProperties` and requires all of its properties; Pydantic models are converted to that form automatically).
- **`schema`**: the same format, non-strict, for a schema that is not strict-compatible.
- **`json_mode`**: JSON mode plus the schema written into the prompt, for models without schema support (or whose support is unknown).
- **`prompt`**: the schema in the prompt only, for models LiteLLM knows accept no `response_format` at all.

A schema whose root is not an object (a list, a union, a `RootModel`) is sent wrapped as `{"value": ...}`, since providers only constrain objects. It is unwrapped for you after validation.

Every reply is also validated client-side. An invalid reply is re-asked up to `max_repairs` times (default from config `chat.schema_max_repairs`, which is 1), and each repair request shows the model its error. A refusal is recorded and never re-asked. A failed repair request is recorded on that choice; the other choices are kept.

### 4. Model Discovery & Selection

Discover and filter models across providers:

<!-- wads-docs: skip needs network discovery (models.discover) and an API key to chat -->
```python
from aix import models

# Discover available models
models.discover("openrouter")  # Fetch 400+ models from OpenRouter

# List all models
all_models = list(models)

# Get specific model info
info = models["openai/gpt-4o"]
print(info.provider)  # 'openai'
print(info.context_size)  # 128000

# Filter models
openai_models = models.filter(provider="openai")
cheap_models = models.filter(
    custom_filter=lambda m: m.cost_per_token.get("input", 0) < 0.001
)
local_models = models.filter(is_local=True)

# Search models
results = models.search("gpt-4")
results = models.search("claude")

# Get recommendations
recommended = models.recommend(
    task="chat", max_cost_per_mtok=5.0, min_context_size=16000
)

# Use with chat
model = models["gpt-4o-mini"]
response = chat("Hello", model=model.id)
```

### 5. Batch Operations

Process multiple requests efficiently:

<!-- wads-docs: skip needs a provider API key -->
```python
from aix import batch_chat, batch_embeddings, BatchProcessor

# Batch chat
prompts = ["What is 2+2?", "What is 3+3?", "What is 5+5?"]
results = list(batch_chat(prompts, batch_size=10, max_workers=5))

# Batch embeddings
texts = ["hello", "world", "foo", "bar"] * 100
vectors = list(batch_embeddings(texts, batch_size=20, show_progress=True))

# Generic batch processing
from aix import batch_process


def analyze(text):
    return chat(f"Analyze sentiment: {text}")


texts = ["I love it!", "It's okay", "Terrible"]
results = list(batch_process(texts, analyze, batch_size=5, retry_attempts=3))

# Stateful batch processor
processor = BatchProcessor(show_progress=True)
results = processor.process_chats(prompts)
processor.save_results("output.json")
```

### 6. Image Generation

Generate images from text descriptions:

<!-- wads-docs: skip needs a provider API key -->
```python
from aix import generate_image, generate_images

# Simple image generation
image = generate_image("A serene mountain landscape at sunset")
image.save("landscape.png")

# High quality with DALL-E 3
image = generate_image(
    "Abstract art with vibrant colors", model="openai/gpt-image-1.5", quality="high"
)

# Generate multiple variations
images = generate_images("A cute robot waving hello", n=3, size="512x512")
for i, img in enumerate(images):
    img.save(f"robot_{i}.png")

# Edit existing images
from aix import edit_image

edited = edit_image("photo.jpg", "Add a rainbow in the sky", mask_path="sky_mask.png")

# Create variations
from aix import create_variation

variations = create_variation("original.png", n=3)
```

### 7. Audio Operations

Text-to-speech and speech-to-text:

<!-- wads-docs: skip needs a provider API key -->
```python
from aix import text_to_speech, transcribe, transcribe_with_timestamps

# Text to speech
audio = text_to_speech("Hello, world!")
audio.save("hello.mp3")

# Different voices
audio = text_to_speech("This is a test", voice="nova", speed=1.2)

# Transcribe audio
text = transcribe("recording.mp3")
print(text)  # "This is the transcribed text"

# With language hint
text = transcribe("spanish_audio.mp3", language="es")

# Detailed transcription with timestamps
result = transcribe_with_timestamps("lecture.mp3")
for segment in result.segments:
    print(f"[{segment['start']:.2f}] {segment['text']}")

# Translate audio to English
from aix import translate_audio

english_text = translate_audio("spanish_audio.mp3")
```

### 8. Video Generation (Coming Soon)

Video generation with provider-specific implementations:

<!-- wads-docs: skip video providers are not configured by default (raises NotImplementedError) -->
```python
from aix import generate_video, get_video_providers

# Check available providers
providers = get_video_providers()
print(providers)  # ['runway', 'pika', ...]

# Generate video (requires provider setup)
video = generate_video(
    "A cat walking through a garden", duration=5, resolution="1920x1080"
)
video.save("cat_video.mp4")

# Animate static image
from aix import animate_image_to_video

video = animate_image_to_video(
    "landscape.jpg", prompt="Gentle camera pan across the scene"
)
```

**Note**: Video generation requires additional provider setup (Runway, Pika, etc.) and API keys.

## OpenRouter Integration

[OpenRouter](https://openrouter.ai) provides a single API key for 400+ models from 60+ providers. This is recommended for:

- **Getting started quickly** - One key vs. managing many
- **Experimenting** - Easy access to models from OpenAI, Anthropic, Google, etc.
- **Production flexibility** - Switch providers without code changes

### Setup

1. Get API key from https://openrouter.ai
2. Set environment variable:
   ```bash
   export OPENROUTER_API_KEY=your-key-here
   ```
3. Use OpenRouter models:
   <!-- wads-docs: skip needs an OpenRouter API key; indented list fence -->
   ```python
   # Prefix models with 'openrouter/'
   chat("Hello", model="openrouter/openai/gpt-4o")
   chat("Hello", model="openrouter/anthropic/claude-3.5-sonnet")

   # Discover available models
   models.discover("openrouter")
   ```

All standard AIX features work with OpenRouter models.

## Architecture

AIX follows the **i2mint philosophy** of clean, functional interfaces:

- **Mapping interfaces** for collections (models, registries)
- **Functional approach** over verbose OOP
- **Lazy evaluation** via generators where appropriate
- **Protocol-based design** for flexibility

### Backend: LiteLLM

AIX uses [LiteLLM](https://github.com/BerriAI/litellm) as the backend for provider interactions, but wraps it in clean, pythonic interfaces. Users never need to interact with LiteLLM directly.

**Supported Providers** (via LiteLLM):
- OpenAI
- Anthropic (Claude)
- Google (Gemini)
- Mistral
- Cohere
- And 100+ more

#### `import aix` does not touch the network

LiteLLM fetches its model-cost map over HTTPS **as a side effect of being
imported**. `aix` therefore resolves LiteLLM on the *first call* rather than at
import time, so importing `aix` (or any of its submodules) opens no outbound
connection: a server cold start doesn't block on it, an offline or
restricted-egress deployment doesn't eat a connect timeout, and a test suite
that merely imports `aix` stays hermetic. The first actual provider call pays
the import, and gets the live cost map — so provider resolution is unaffected.

If you also want the *first call* to stay offline, set LiteLLM's own knob in
your environment. `aix` deliberately never sets it for you — it is a
whole-process setting, so the choice is the operator's:

```bash
export LITELLM_LOCAL_MODEL_COST_MAP=1
```

The trade-off: LiteLLM then reads the cost map bundled in its wheel, which is a
snapshot. Bare model names newer than your installed `litellm` release may stop
resolving — pass those provider-prefixed (`"openai/gpt-5.2"` rather than
`"gpt-5.2"`), which works either way.

## Design Patterns

### From `oa` (OpenAI facade)

AIX builds on patterns from the `oa` package:OpenRouter
- Simple chat interface with smart defaults
- Template-based function creation
- Structured output support
- Batch processing capabilities

### From `i2` (Signature manipulation)

- Clean function signatures
- Flexible parameter handling
- Decorator-based composition

### From `dol` (Storage abstraction)

- Mapping-based interfaces
- Persistent storage options
- Cache management

## Advanced Usage

### Custom Model Sources

<!-- wads-docs: skip needs network access (OpenRouter discovery) -->
```python
from aix.ai_models import ModelManager, OpenRouterSource

manager = ModelManager()
source = OpenRouterSource()
manager.register_source("openrouter", source)
models = manager.discover_from_source("openrouter")
```

### Connector-Specific Metadata

<!-- wads-docs: skip fragment; models comes from the discovery example above -->
```python
# Get provider-specific parameters
metadata = models.get_connector_metadata("openai/gpt-4o", "openai")
# Use with native SDK: openai.ChatCompletion.create(**metadata, messages=[...])
```

### Error Handling

```python
from aix import chat

try:
    response = chat("Hello", model="nonexistent-model")
except Exception as e:
    print(f"Error: {e}")
```

## Backward Compatibility

The legacy `chat_funcs` and `chat_models` interfaces are still available:

```python
from aix import chat_funcs, chat_models

# Old style (still works)
list(chat_funcs)  # ['gpt-4o', 'gpt-4o-mini', ...]
response = chat_funcs.gpt_4o("Hello")

# Model metadata
info = chat_models["gpt-4o"]
# {'price_per_million_tokens': 5.0, 'provider': 'openai', ...}
```

However, the new interfaces (`chat`, `embeddings`, `prompt_func`, `models`) are recommended for new code.

## Examples

### Semantic Search

<!-- wads-docs: skip needs a provider API key -->
```python
from aix import embed, cosine_similarity

# Build document index
docs = ["AI is the future", "Python is great", "Machine learning works"]
doc_vecs = [embed(doc) for doc in docs]

# Search
query_vec = embed("artificial intelligence")
similarities = [cosine_similarity(query_vec, dv) for dv in doc_vecs]
best_match = docs[similarities.index(max(similarities))]
print(best_match)  # "AI is the future"
```

### Data Extraction Pipeline

```python
from aix import prompt_func, batch_process

# Define extraction function
extract = prompt_func(
    "Extract product info from: {text}",
    output_schema={"name": str, "price": float, "category": str},
)

# Process many product descriptions
descriptions = [...]  # Your data
results = list(
    batch_process(
        descriptions, lambda d: extract(text=d), batch_size=10, show_progress=True
    )
)
```

### Multi-Model Comparison

<!-- wads-docs: skip needs a provider API key -->
```python
from aix import chat

prompt = "Explain quantum computing in one sentence"

# Try different models
for model_id in ["gpt-4o-mini", "claude-sonnet-4", "gemini-1.5-flash"]:
    response = chat(prompt, model=model_id)
    print(f"{model_id}: {response}")
```

## Documentation

- **API Reference**: See docstrings in each module
- **Examples**: Check `examples/` directory
- **GitHub**: https://github.com/thorwhalen/aix

## Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

## License

Apache 2.0

## Credits

Built with:
- [LiteLLM](https://github.com/BerriAI/litellm) - Multi-provider backend
- [i2](https://github.com/i2mint/i2) - Signature manipulation utilities
- [dol](https://github.com/i2mint/dol) - Storage abstraction patterns
- [oa](https://github.com/thorwhalen/oa) - OpenAI facade inspiration

## What AIX is NOT

AIX is NOT an AI agent framework. For that, see the separate `aw` package. AIX focuses on foundational AI operations (chat, embeddings, etc.) that can be used to build agents and other applications.
