Metadata-Version: 2.4
Name: pi169
Version: 0.2.1
Summary: Official Python SDK and CLI for 169Pi models (Alpie Core and Alpie Seed)
License: Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.27.0
Requires-Dist: numpy>=1.24.0
Provides-Extra: memory
Requires-Dist: faiss-cpu>=1.7.4; extra == "memory"
Requires-Dist: sentence-transformers>=2.6.0; extra == "memory"
Provides-Extra: image
Requires-Dist: Pillow>=10.0.0; extra == "image"
Provides-Extra: video
Requires-Dist: opencv-python-headless>=4.8.0; extra == "video"
Provides-Extra: all
Requires-Dist: faiss-cpu>=1.7.4; extra == "all"
Requires-Dist: sentence-transformers>=2.6.0; extra == "all"
Requires-Dist: Pillow>=10.0.0; extra == "all"
Requires-Dist: opencv-python-headless>=4.8.0; extra == "all"

# Pi169 Python SDK

[![PyPI](https://img.shields.io/badge/PyPI-pi169-blue)](https://pypi.org/project/pi169/)

Pi169 is the official Python SDK and CLI for **169Pi** models, including **Alpie Core (`alpie-32b`)**, a fine-tuned 32B pure-reasoning model running in native 4-bit precision, and **Alpie Seed (`alpie_seed`)**, a 9B multimodal model supporting text, images, video, hybrid thinking, and tool calling. It provides a production-ready interface for synchronous, asynchronous, and streaming inference with automatic session-isolated semantic memory.

## Quick Start

```bash
# Install the SDK with memory, image, and video support
pip install "pi169[all]"

# Set your API key
export ALPIE_API_KEY="your_key_here"

# Start using the CLI (alpie_seed defaults to non-thinking; session memory is active automatically)
pi169 "What is AI?" --model alpie_seed
pi169 "Summarize this chart" --model alpie_seed --image Benchmark.png --stream
pi169 "Explain 4-bit quantization in simple terms" --model alpie-32b --max-tokens 4096
```

That's it! You're ready to interact with Alpie Core and Alpie Seed from your terminal.

## Installation

```bash
pip install pi169              # Lightweight core SDK & CLI (stateless inference)
pip install "pi169[memory]"    # Local SQLite + FAISS semantic session memory
pip install "pi169[image]"     # Pillow support for PIL.Image inputs
pip install "pi169[video]"     # OpenCV support for video frame extraction
pip install "pi169[all]"       # Full multimodal + local session memory support
```

Python 3.10+ required.

## Authentication

Pi169 uses Bearer Token authentication.

**Synchronous Client:**

```python
from pi169 import Pi169Client

client = Pi169Client(api_key="YOUR_API_KEY")
```

**Asynchronous Client:**

```python
from pi169 import AsyncPi169Client

client = AsyncPi169Client(api_key="YOUR_API_KEY")
```

Every request automatically sends ([Create API Key](https://playground.169pi.ai/dashboard/api-keys)):

```text
Authorization: Bearer <API_KEY>
```

## Base URL & Client Configuration

**Synchronous Client:**

```python
from pi169 import Pi169Client

client = Pi169Client(
    api_key="YOUR_API_KEY",
    base_url="https://api.169pi.com/v1",
    timeout=60.0,
    max_retries=2,
)
```

**Asynchronous Client:**

```python
from pi169 import AsyncPi169Client

client = AsyncPi169Client(
    api_key="YOUR_API_KEY",
    base_url="https://api.169pi.com/v1",
    timeout=60.0,
    max_retries=2,
)
```

- `base_url` → API root (`https://api.169pi.com/v1`)
- `timeout` → max wait time in seconds (non-streaming requests)
- `max_retries` → reserved for future retry logic
- `memory` → enable/disable automatic session memory (default: `True`)
- `session_id` → optional custom session ID (auto-generated per client instance if omitted)
- `memory_config` → optional `MemoryConfig` for local SQLite + FAISS storage settings

## Available Models

| Model | Product Name | Mode / Architecture | Parameters | Context Window | Max Tokens | Capabilities |
|---|---|---|---|---|---|---|
| `alpie-32b` | Alpie Core | Pure Reasoning (always-on `<think>`, non-hybrid) | 32B (4-bit) | 65,536 | Up to 16,384 | Text only (mathematics, coding, deep reasoning); no images/video, tool calling, or thinking toggle |
| `alpie_seed` | Alpie Seed | Multimodal + Hybrid Thinking + Tool-Capable | 9B | 262,144 | 500 – 100,000 | Text, images, video (frame-based), tool calling, non-thinking by default (`enable_thinking=True` opt-in) |

## Features

- **Multi-model support** for `alpie-32b` and `alpie_seed` with pre-flight parameter validation
- **Non-thinking by default** (`alpie_seed`), with opt-in `<think>` reasoning via `enable_thinking=True` (`--enable-thinking` in CLI)
- **Multimodal inputs** (`alpie_seed`) via `encode_image`, `extract_video_frames`, and `build_multimodal_content`
- **Tool / function calling** (`alpie_seed`) with OpenAI-compatible `tools`, `tool_choice`, `ToolCall` / `FunctionCall` types, and `--tool-calling` CLI round-trips
- **Automatic session-isolated semantic memory** backed by SQLite and FAISS (requires `pi169[memory]`; on by default once installed; pass `memory=False` or `--no-memory` for stateless calls)
- **CLI** for text, image, video, tool-calling, and thinking modes
- **Streaming and non-streaming** chat completions
- **Async/await** support for concurrent requests
- **Type-safe Python interface** (dataclasses, type hints)
- **Typed exceptions** for error handling
- **Networking** with timeouts and httpx
- **Tested** with pytest

## CLI

Use Alpie models directly from your terminal. The CLI reads the `ALPIE_API_KEY` environment variable.

### Setting Up Your API Key

**macOS / Linux:**

```bash
export ALPIE_API_KEY="your_key_here"
```

**Windows Command Prompt:**

```cmd
set ALPIE_API_KEY=your_key_here
```

**Windows PowerShell:**

```powershell
$env:ALPIE_API_KEY = "your_key_here"
```

Session memory is on by default when `pi169[memory]` is installed. Add `--no-memory` for independent test cases. Run `pi169 --help` to see all flags.

### Alpie Seed: Non-Thinking Default vs. Thinking Enabled

```bash
# Non-streaming (non-thinking by default)
pi169 "What is AI?" --model alpie_seed

# Streaming (non-thinking by default)
pi169 "What is AI?" --model alpie_seed --stream

# Explicit non-thinking flag
pi169 "What is AI?" --model alpie_seed --no-thinking --stream

# Thinking enabled (non-streaming & streaming)
pi169 "What is AI?" --model alpie_seed --enable-thinking --max-tokens 4096
pi169 "What is AI?" --model alpie_seed --enable-thinking --max-tokens 4096 --stream
```

### Alpie Core 32B: Always-On Reasoning

```bash
# Non-streaming
pi169 "What is AI?" --model alpie-32b --max-tokens 4096

# Streaming
pi169 "What is AI?" --model alpie-32b --max-tokens 4096 --stream
```

### Alpie Seed: Image and Video

```bash
# Image input (non-thinking by default)
pi169 "Describe this image." --model alpie_seed --image "path/to/image.png" --stream

# Image input with thinking enabled
pi169 "Describe this image." --model alpie_seed --enable-thinking --image "path/to/image.png" --max-tokens 4096 --stream

# Video input (extracts timestamped frames automatically; non-thinking by default)
pi169 "Describe what happens in this video." --model alpie_seed --video "path/to/video.mp4" --max-frames 8 --stream

# Video input with thinking enabled
pi169 "Describe what happens in this video." --model alpie_seed --enable-thinking --video "path/to/video.mp4" --max-frames 8 --max-tokens 4096 --stream
```

### Alpie Seed: Tool Calling

```bash
# Tool-calling round-trip (non-thinking by default)
pi169 "What is the weather in Patna right now?" --model alpie_seed --tool-calling --no-memory

# Tool-calling round-trip with thinking enabled
pi169 "What is the weather in Patna right now?" --model alpie_seed --enable-thinking --tool-calling --max-tokens 4096 --no-memory
```

### Session Memory

```bash
# Memory works automatically across CLI calls (uses default 'cli-default' session)
pi169 "Remember that my target latency is 150ms" --model alpie_seed
pi169 "What is my target latency?" --model alpie_seed

# Isolate a separate project session
pi169 "Remember deployment region is Patna" --model alpie_seed --session-id prod-notes

# Run a stateless command without reading or writing memory
pi169 "Give me a quick regex for email validation" --model alpie_seed --no-memory
```

### CLI Options

- `--model` → Model identifier (alpie-32b or alpie_seed, default: alpie-32b)
- `--stream` → Enable streaming mode for real-time token-by-token responses
- `--max-tokens` → Maximum tokens to generate (500–100000 for alpie_seed; 1–16384 for alpie-32b)
- `--enable-thinking` → Enable step-by-step <think> reasoning trace (alpie_seed only; defaults to non-thinking)
- `--no-thinking` → Explicitly disable <think> reasoning trace (alpie_seed only; default behavior)
- `--image` → Path or URL to an image (repeatable for multiple images, alpie_seed only)
- `--video` → Path to a local video file (alpie_seed only, requires opencv-python-headless)
- `--max-frames` → Maximum video frames to sample when --video is passed (default: 8)
- `--tool-calling` → Attach built-in demo tools and run a full tool-calling round-trip (alpie_seed only)
- `--tools-file` → Path to a JSON file containing OpenAI-compatible tool definitions (alpie_seed only)
- `--memory` → Enable persistent local SQLite + FAISS memory (enabled by default)
- `--no-memory` → Disable persistent local memory for a stateless command
- `--session-id` → Memory session ID for conversation isolation (default: cli-default)

## Python Examples

### Non-Streaming (`alpie_seed`, Non-Thinking Default)

```python
import os
from dotenv import load_dotenv
from pi169 import Pi169Client

load_dotenv()

api_key = os.getenv("ALPIE_API_KEY")
if not api_key:
    raise ValueError("API key missing")

client = Pi169Client(api_key=api_key, memory=False)

# enable_thinking defaults to False for alpie_seed
response = client.chat.completions.create(
    model="alpie_seed",
    messages=[
        {"role": "user", "content": "What is the capital of France?"}
    ],
    stream=False,
)

# Print the assistant reply
if response.choices:
    message = response.choices[0].message
    if message and message.content:
        print(message.content)
else:
    print("No choices returned")

client.close()
```

### Non-Streaming (`alpie_seed`, Thinking Enabled)

```python
import os
from dotenv import load_dotenv
from pi169 import Pi169Client

load_dotenv()

client = Pi169Client(api_key=os.environ["ALPIE_API_KEY"], memory=False)

response = client.chat.completions.create(
    model="alpie_seed",
    messages=[{"role": "user", "content": "What is AI?"}],
    enable_thinking=True,
    max_tokens=4096,
    stream=False,
)

if response.choices:
    msg = response.choices[0].message
    if getattr(msg, "reasoning", None):
        print(msg.reasoning)
    print(msg.content)

client.close()
```

### Streaming

```python
import os
from dotenv import load_dotenv
from pi169 import Pi169Client

load_dotenv()

api_key = os.getenv("ALPIE_API_KEY")
if not api_key:
    raise ValueError("API key missing")

client = Pi169Client(api_key=api_key, memory=False)

# Set enable_thinking=True to stream reasoning tokens.
# For model="alpie-32b", remove enable_thinking: it always reasons and rejects the parameter.
stream = client.chat.completions.create(
    model="alpie_seed",
    messages=[{"role": "user", "content": "What is the capital of France?"}],
    enable_thinking=False,
    stream=True,
)

for chunk in stream:
    reasoning = getattr(chunk, "delta_reasoning", None)
    if reasoning:
        print(reasoning, end="", flush=True)

    if chunk.delta_content:
        print(chunk.delta_content, end="", flush=True)
print()

client.close()
```

Streaming responses yield partial tokens in real time, ideal for chatbots, UIs, and live applications.

## Multimodal Usage (`alpie_seed`)

### Image Input

```python
import os
from pi169 import Pi169Client, build_multimodal_content

client = Pi169Client(
    api_key=os.environ["ALPIE_API_KEY"],
    memory=False,
    timeout=120.0,
)

try:
    content = build_multimodal_content(
        text="Summarize this benchmark chart briefly.",
        images=["Benchmark.png"],
    )
    messages = [{"role": "user", "content": content}]

    # Non-streaming image request (non-thinking by default)
    response = client.chat.completions.create(
        model="alpie_seed",
        messages=messages,
        max_tokens=1024,
        stream=False,
    )
    if response.choices:
        print(response.choices[0].message.content)

    # Streaming image request
    stream = client.chat.completions.create(
        model="alpie_seed",
        messages=messages,
        max_tokens=1024,
        stream=True,
    )
    for chunk in stream:
        if chunk.delta_content:
            print(chunk.delta_content, end="", flush=True)
    print()
finally:
    client.close()
```

### Video Input

Extracts timestamped frames from a local video file and sends them as image blocks with your prompt. Requires `pip install "pi169[video]"`.

```python
import os
from pi169 import Pi169Client, build_multimodal_content

client = Pi169Client(
    api_key=os.environ["ALPIE_API_KEY"],
    memory=False,
    timeout=120.0,
)

try:
    content = build_multimodal_content(
        text="Describe what happens in this video briefly.",
        video="demo.mp4",
        max_video_frames=8,
    )
    messages = [{"role": "user", "content": content}]

    # Non-streaming video request (non-thinking by default)
    response = client.chat.completions.create(
        model="alpie_seed",
        messages=messages,
        max_tokens=1024,
        stream=False,
    )
    if response.choices:
        print(response.choices[0].message.content)

    # Streaming video request
    stream = client.chat.completions.create(
        model="alpie_seed",
        messages=messages,
        max_tokens=1024,
        stream=True,
    )
    for chunk in stream:
        if chunk.delta_content:
            print(chunk.delta_content, end="", flush=True)
    print()
finally:
    client.close()
```

### Multiple Images

```python
import os
from pi169 import Pi169Client, Pi169Error, build_multimodal_content

IMAGES = [
    "Benchmark.png",
    "image2.jpg",
]

def main():
    client = Pi169Client(
        api_key=os.environ["ALPIE_API_KEY"],
        memory=False,
        timeout=180.0,
    )

    try:
        print("=== Multiple Images Test ===")

        content = build_multimodal_content(
            text="Compare all attached images and summarize the key differences.",
            images=IMAGES,
        )

        response = client.chat.completions.create(
            model="alpie_seed",
            messages=[{"role": "user", "content": content}],
            max_tokens=1024,
            stream=False,
        )

        print("\nAlpie Seed Response:")
        print(response.choices[0].message.content)

    except Pi169Error as e:
        print(f"Pi169 API/SDK error: {e}")
    finally:
        client.close()


if __name__ == "__main__":
    main()
```

### Multiple Videos

Requires `pip install "pi169[video]"`.

```python
import os
from pathlib import Path
from pi169 import Pi169Client, Pi169Error, extract_video_frames

VIDEOS = [
    "video1.mp4",
    "video2.mp4",
]

MAX_FRAMES_PER_VIDEO = 4


def main():
    client = Pi169Client(
        api_key=os.environ["ALPIE_API_KEY"],
        memory=False,
        timeout=180.0,
    )

    try:
        print("=== Multiple Videos Test ===")

        content = [
            {
                "type": "text",
                "text": "Describe what happens in each video and compare them."
            }
        ]

        for idx, video_path in enumerate(VIDEOS, start=1):
            print(f"Extracting Video {idx}: {video_path}")

            content.append({
                "type": "text",
                "text": f"--- Video {idx}: {Path(video_path).name} ---"
            })

            frames = extract_video_frames(
                video_path,
                max_frames=MAX_FRAMES_PER_VIDEO,
            )

            content.extend(frames)

        response = client.chat.completions.create(
            model="alpie_seed",
            messages=[{"role": "user", "content": content}],
            max_tokens=1024,
            stream=False,
        )

        print("\nAlpie Seed Response:")
        print(response.choices[0].message.content)

    except Pi169Error as e:
        print(f"Pi169 API/SDK error: {e}")
    finally:
        client.close()


if __name__ == "__main__":
    main()
```

## Tool / Function Calling (`alpie_seed`)

> **Note:** pass `memory=False` for tool calling. With memory enabled, tool call and tool result fields are not preserved between steps.

### Thinking Off (Default)

```python
import json
import os
from pi169 import Pi169Client, Pi169Error

MODEL = "alpie_seed"
PROMPT = "What is the weather in Patna right now?"


def get_weather(city: str) -> dict:
    # Dummy data for testing; replace with a real weather API
    return {"city": city, "temp_c": 26, "condition": "Clear"}


tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city.",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "City name"}
                },
                "required": ["city"],
            },
        },
    }
]

messages = [{"role": "user", "content": PROMPT}]

client = Pi169Client(
    api_key=os.environ["ALPIE_API_KEY"],
    memory=False,
    timeout=120.0,
)

try:
    # Step 1: Model decides to invoke a tool (non-thinking by default)
    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        tools=tools,
        tool_choice="auto",
        max_tokens=2048,
    )

    assistant_msg = response.choices[0].message

    if not assistant_msg.tool_calls:
        print("No tool call made. Reply:", assistant_msg.content)
    else:
        messages.append(assistant_msg.to_dict())

        # Step 2: Execute local tool logic and append tool results
        for call in assistant_msg.tool_calls:
            args = json.loads(call.function.arguments)
            print(f"Tool call: {call.function.name}({args})")

            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "name": call.function.name,
                "content": json.dumps(get_weather(args["city"])),
            })

        # Step 3: Model generates final response using tool output
        final = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=tools,
            max_tokens=2048,
        )
        print("Final answer:", final.choices[0].message.content)

except Pi169Error as e:
    print("Pi169 error:", e)

finally:
    client.close()
```

### Thinking On

Pass `enable_thinking=True` and `max_tokens=4096` to inspect `assistant_msg.reasoning`:

```python
response = client.chat.completions.create(
    model="alpie_seed",
    messages=messages,
    tools=tools,
    tool_choice="auto",
    enable_thinking=True,
    max_tokens=4096,
)
assistant_msg = response.choices[0].message
print("Thinking:", getattr(assistant_msg, "reasoning", None))
```

## Automatic Session Memory (SQLite + FAISS)

Requires `pip install "pi169[memory]"`. Without it, requests run statelessly and the SDK shows a warning.

Every `Pi169Client` and `AsyncPi169Client` instance tracks session-isolated semantic memory across turns, with no extra flags:

```python
import os
from pi169 import Pi169Client

client = Pi169Client(api_key=os.environ["ALPIE_API_KEY"])

# Turn 1: Context is saved automatically to this client's session
client.chat.completions.create(
    model="alpie_seed",
    messages=[{"role": "user", "content": "Our production cluster runs in Patna with max_tokens=2048."}],
)

# Turn 2: Context is recalled automatically on subsequent turns
response = client.chat.completions.create(
    model="alpie_seed",
    messages=[{"role": "user", "content": "Where is our cluster hosted and what is max_tokens?"}],
)
print(response.choices[0].message.content)

# Optional: Run a stateless call without reading or writing memory
stateless = client.chat.completions.create(
    model="alpie-32b",
    messages=[{"role": "user", "content": "What is 17 * 23?"}],
    max_tokens=4096,
    memory=False,
)

client.close()
```

To resume a named session across script runs, pass `session_id="ops-session"` to `Pi169Client(...)` or `create(...)`.

## Asynchronous Usage

### Non-Streaming

```python
import asyncio
import os
from dotenv import load_dotenv
from pi169 import AsyncPi169Client

load_dotenv()

async def main():
    api_key = os.getenv("ALPIE_API_KEY")
    if not api_key:
        raise ValueError("API key missing")

    async with AsyncPi169Client(api_key=api_key, memory=False) as client:
        response = await client.chat.completions.create(
            model="alpie_seed",
            messages=[
                {"role": "user", "content": "What is the capital of France?"}
            ],
        )
        print(response.choices[0].message.content)

if __name__ == "__main__":
    asyncio.run(main())
```

### Streaming

```python
import asyncio
import os
from dotenv import load_dotenv
from pi169 import AsyncPi169Client

load_dotenv()

async def main():
    api_key = os.getenv("ALPIE_API_KEY")
    if not api_key:
        raise ValueError("API key missing")

    async with AsyncPi169Client(api_key=api_key, memory=False) as client:
        stream = await client.chat.completions.create(
            model="alpie_seed",
            messages=[
                {"role": "user", "content": "What is the capital of France?"}
            ],
            stream=True,
        )

        async for chunk in stream:
            if chunk.delta_content:
                print(chunk.delta_content, end="", flush=True)
        print()

if __name__ == "__main__":
    asyncio.run(main())
```

### Concurrent Requests

```python
import asyncio
import os
from dotenv import load_dotenv
from pi169 import AsyncPi169Client

load_dotenv()

async def main():
    api_key = os.getenv("ALPIE_API_KEY")
    if not api_key:
        raise ValueError("API key missing")

    async with AsyncPi169Client(api_key=api_key, memory=False) as client:
        # Create multiple tasks
        tasks = [
            client.chat.completions.create(
                model="alpie_seed",
                messages=[{"role": "user", "content": f"What is {n} + {n}?"}]
            )
            for n in range(1, 6)
        ]

        # Execute concurrently
        responses = await asyncio.gather(*tasks)

        for i, response in enumerate(responses, 1):
            print(f"Response {i}: {response.choices[0].message.content}")

if __name__ == "__main__":
    asyncio.run(main())
```

## Rate Limits and Quotas

Pi169 enforces rate limits to ensure fair and stable usage of the API.

- **Requests per minute (RPM):** 60
- **Requests per hour (RPH):** 1000

If you exceed the limit, the API returns:

```json
{
  "status": 429,
  "error": "rate_limit_exceeded"
}
```

### Retry and Backoff

- Wait for the `Retry-After` header
- Avoid retry storms: do not send parallel retries

### Rate Limit Best Practices

- Batch multiple operations into fewer requests
- Use streaming for long outputs to avoid token bursts
- Let session memory manage multi-turn context (or pass `memory=False` for one-off queries)
- Cache responses when appropriate
- Spread requests evenly instead of sending them in spikes
- Use the async client for concurrent requests, within rate limits

## Error Handling

The SDK includes a typed exception hierarchy.

### Base Exception

```python
class Pi169Error(Exception):
    ...
```

### Exception Hierarchy

```text
Pi169Error
├── APIError
├── ContentPolicyViolationError
├── ContextWindowExceededError
├── UnsupportedParamsError
├── AuthError
├── RateLimitError
├── ServerError
├── EngineOverloadedError
├── TimeoutError
├── ModelNotFoundError
├── LimitExceededError
└── KeyNotActive
```

### Example Error Response

```json
{
  "error": {
    "message": "Key not active",
    "type": "key_not_active",
    "code": 402
  }
}
```

The SDK maps this to:

```python
KeyNotActive("Key not active", status_code=402, response_data={...})
```

### Catching Errors (Sync)

**Catch all Pi169 errors:**

```python
from pi169 import Pi169Error

try:
    client.chat.completions.create(...)
except Pi169Error as e:
    print("Error:", e.message)
```

**Catch specific errors:**

```python
from pi169 import (
    Pi169Client,
    AuthError,
    UnsupportedParamsError,
    RateLimitError,
    TimeoutError,
    KeyNotActive,
    ModelNotFoundError,
    Pi169Error,
)

client = Pi169Client(api_key="YOUR_API_KEY")

try:
    response = client.chat.completions.create(
        model="alpie_seed",
        messages=[{"role": "user", "content": "Hello!"}],
        max_tokens=500,
    )

except AuthError:
    print("Invalid API key.")

except KeyNotActive:
    print("Your API key is not active.")

except UnsupportedParamsError as e:
    print("Invalid parameter for model:", e.message)

except RateLimitError:
    print("Rate limit exceeded. Please try again later.")

except TimeoutError:
    print("The request timed out.")

except ModelNotFoundError:
    print("The requested model does not exist.")

except Pi169Error as e:
    print("A Pi169 SDK error occurred:", e)

else:
    print("Response:", response.choices[0].message.content)
```

### Catching Errors (Async)

```python
import asyncio
from pi169 import (
    AsyncPi169Client,
    AuthError,
    UnsupportedParamsError,
    RateLimitError,
    TimeoutError,
    KeyNotActive,
    ModelNotFoundError,
    Pi169Error,
)

async def main():
    async with AsyncPi169Client(api_key="YOUR_API_KEY") as client:
        try:
            response = await client.chat.completions.create(
                model="alpie_seed",
                messages=[{"role": "user", "content": "Hello!"}],
                max_tokens=500,
            )

        except AuthError:
            print("Invalid API key.")

        except KeyNotActive:
            print("Your API key is not active.")

        except UnsupportedParamsError as e:
            print("Invalid parameter for model:", e.message)

        except RateLimitError:
            print("Rate limit exceeded. Please try again later.")

        except TimeoutError:
            print("The request timed out.")

        except ModelNotFoundError:
            print("The requested model does not exist.")

        except Pi169Error as e:
            print("A Pi169 SDK error occurred:", e)

        else:
            print("Response:", response.choices[0].message.content)

if __name__ == "__main__":
    asyncio.run(main())
```

### Error-to-Exception Mapping

| API Error | SDK Exception |
|---|---|
| 401 auth failure | `AuthError` |
| 402 key not active | `KeyNotActive` |
| 402 credit/quota limit exceeded | `LimitExceededError` |
| 400 invalid params (or local validation failure) | `UnsupportedParamsError` |
| 400 context window exceeded | `ContextWindowExceededError` |
| 400 / 403 content policy violation | `ContentPolicyViolationError` |
| 404 model not found | `ModelNotFoundError` |
| 429 rate limit exceeded | `RateLimitError` |
| 500 internal server error | `ServerError` |
| 503 engine overloaded | `EngineOverloadedError` |
| 504 request timeout | `TimeoutError` |

## Best Practices

### CLI vs Python SDK

**Use the CLI for:**

- Quick testing or prototyping
- One-off queries, image/video analysis, or `--tool-calling` smoke tests
- Shell scripting and automation
- Learning the API without writing code
- Debugging API responses

**Use the Python SDK for:**

- Building applications or services
- Complex conversations or multi-step tool-calling workflows
- Error handling
- Processing multiple requests
- Integration with existing Python code

### Async vs Sync

**Use async when:**

- Making concurrent API requests
- Building high-performance web servers (FastAPI, aiohttp)
- Integrating with other async libraries
- Handling many simultaneous streams
- You need maximum throughput within rate limits

**Use sync when:**

- Writing simple scripts
- Making sequential requests
- Working in environments without async support
- Prototyping or learning

## Project Structure

```text
src/pi169/
├── __init__.py          # Public exports (clients, types, multimodal & model helpers, errors)
├── alpie_types.py       # Dataclasses for messages, multimodal content, ToolCall, StreamChunk
├── model_registry.py    # Model specs & pre-flight validation (alpie-32b, alpie_seed)
├── multimodal.py        # encode_image, extract_video_frames, build_multimodal_content
├── client.py            # Synchronous Pi169Client
├── async_client.py      # Asynchronous AsyncPi169Client
├── cli.py               # CLI entrypoint (text, image, video, --tool-calling, thinking, memory)
├── exceptions.py        # Typed exception hierarchy
└── memory/              # SQLite + FAISS local semantic memory subsystem
    ├── config.py
    ├── context_builder.py
    ├── embeddings.py
    ├── manager.py
    ├── models.py
    ├── retrieval.py
    ├── storage.py
    ├── vector_store.py
    └── backends/
```

## Testing

The SDK includes a pytest-based test suite. API responses can be mocked so tests run offline.

### Install Test Dependencies

```bash
pip install pytest pytest-httpx pytest-asyncio respx pytest-mock
```

### Run Tests

```bash
pytest
pytest -v
pytest tests/test_alpie_core.py -v
pytest tests/test_alpie_seed.py -v
pytest tests/test_multimodal.py -v
pytest tests/test_cli_seed.py -v
```

## Environment Variables

```bash
# .env file
ALPIE_API_KEY=your_api_key_here
```

```python
import os
from dotenv import load_dotenv
from pi169 import Pi169Client

load_dotenv()

api_key = os.getenv("ALPIE_API_KEY")
client = Pi169Client(api_key=api_key)
```

## Support

- **Playground & API Keys:** https://playground.169pi.ai/
- **GitHub Issues:** https://github.com/169Pi/Pi169-SDK
- **Support Email:** support@169pi.com

When contacting support, include:

- SDK version
- Python version
- Model identifier (`alpie-32b` or `alpie_seed`)
- API endpoint used
- Error message or traceback
- Minimal reproducible example if possible (never include your API key)
- Whether you use sync, async, or CLI

## Changelog

### Version 0.2.6

Added Alpie Seed (`alpie_seed`) with non-thinking default, multimodal inputs, `--tool-calling`, and automatic session-isolated semantic memory.

- **Alpie Seed support:** model registry (`MODEL_REGISTRY`, `get_model_spec`) with `max_tokens` defaults and pre-flight validation (500–100,000 tokens, 262K context window)
- **Non-thinking default and hybrid toggle:** `alpie_seed` defaults to `enable_thinking=False`; opt in with `enable_thinking=True` (`--enable-thinking` / `--no-thinking`), with `message.reasoning` and `chunk.delta_reasoning` fields
- **Multimodal helpers:** `encode_image`, `extract_video_frames`, and `build_multimodal_content`
- **Tool calling:** `tools`, `tool_choice`, `parallel_tool_calls`, `ToolCall` and `FunctionCall` across sync, async, and streaming APIs, plus `--tool-calling` and `--tools-file`
- **Session memory:** local SQLite + FAISS memory enabled by default (`memory=False` / `--no-memory` to opt out), with `<think>` filtering

### Version 0.1

Initial public release with sync, async, and streaming support for Alpie Core.

- CLI integration
- Async support with `AsyncPi169Client`, including streaming and error handling
- Concurrent request examples
- Context manager support
- Chat completions (sync and streaming)
- Typed exceptions and error mapping
- Timeout configuration and base client setup
- Available models listing
- pytest-based test suite
- CLI, async, best-practice, testing, and environment variable documentation

 ## License

Apache 2.0

## About 169Pi

169Pi is the edge AI company. We build the Alpie family of models and the stack to run them anywhere: phones, laptops, servers, cloud, or fully offline. Our models are quantized from day one, small enough to run on your own hardware and capable enough to do real work. Your data stays where you put it.

© 169PI
