Metadata-Version: 2.4
Name: chatjimmy
Version: 0.1.0
Summary: A Python SDK for ChatJimmy's ultra-fast AI inference platform, featuring simplified and OpenAI-compatible interfaces.
Author-email: Community SDK Contributor <developer@chatjimmy-community.org>
License-Expression: MIT
Project-URL: Homepage, https://github.com/community-sdks/chatjimmy-python
Project-URL: Documentation, https://github.com/community-sdks/chatjimmy-python#readme
Project-URL: Repository, https://github.com/community-sdks/chatjimmy-python.git
Project-URL: Bug Tracker, https://github.com/community-sdks/chatjimmy-python/issues
Keywords: chatjimmy,ai,llm,llama3,taalas,inference,fast-inference,openai-compatible,streaming
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28.0
Requires-Dist: httpx>=0.24.0
Requires-Dist: urllib3>=1.26.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Dynamic: license-file

# ChatJimmy Python SDK (`chatjimmy`)

[![PyPI version](https://img.shields.io/pypi/v/chatjimmy.svg)](https://pypi.org/project/chatjimmy/)
[![Python Versions](https://img.shields.io/pypi/pyversions/chatjimmy.svg)](https://pypi.org/project/chatjimmy/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A developer-friendly, production-grade Python SDK for [ChatJimmy](https://chatjimmy.ai/) — an ultra-fast AI inference platform powered by Taalas Inc.'s custom direct-to-silicon compute hardware running Meta's Llama 3.1 8B.

The SDK offers two intuitive developer experiences:
1. **Simplified Interface**: A lightweight, minimal API (`client.chat("Hello")`).
2. **OpenAI-Compatible Interface**: An interface mimicking the official OpenAI Python package (`client.chat.completions.create(...)`) with full support for streaming and asynchronous calls.

---

> [!IMPORTANT]
> **Community Notice & Disclaimer**: This package is an independent community SDK and is neither an official product of nor affiliated with ChatJimmy or Taalas Inc. It communicates with ChatJimmy's publicly served backend and is subject to its service availability, terms of use, and network rate limits.

---

## Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
  - [1. Simplified Interface](#1-simplified-interface)
  - [2. OpenAI-Compatible Interface](#2-openai-compatible-interface)
- [Model Discovery](#model-discovery)
- [Multi-Turn Conversations](#multi-turn-conversations)
- [Real-Time Streaming](#real-time-streaming)
  - [OpenAI-Compatible Streaming](#openai-compatible-streaming)
  - [Simplified Token Streaming](#simplified-token-streaming)
- [Asynchronous Client (`AsyncChatJimmy`)](#asynchronous-client-asyncchatjimmy)
  - [Async Chat Completions](#async-chat-completions)
  - [Async Streaming](#async-streaming)
  - [Concurrent Requests with asyncio](#concurrent-requests-with-asyncio)
- [File Attachments (Up to 50KB)](#file-attachments-up-to-50kb)
- [Hardware Performance Metrics](#hardware-performance-metrics)
- [Configuration & Networking](#configuration--networking)
- [Error Handling](#error-handling)
- [Testing](#testing)
- [Known Limitations](#known-limitations)
- [License](#license)

---

## Features

- **Zero Authentication**: No API keys, login credentials, or browser automation required.
- **OpenAI-Compatible API**: Seamlessly drop into existing workflows expecting OpenAI-style `client.chat.completions.create(...)` and `ChatCompletion` objects.
- **Dual Synchronous & Asynchronous Support**: Both `ChatJimmy` (sync via `requests`) and `AsyncChatJimmy` (async via `httpx`).
- **High-Performance Streaming**: Token-by-token and chunk-by-chunk streaming with zero internal sentinel token leaks.
- **Hardware Telemetry**: Direct access to Taalas silicon execution metrics (TTFT, decode tokens/sec, prefill tokens/sec, compute latency).
- **Multi-Turn Context**: Automatic conversation tracking and session management.
- **Attachment Support**: Upload and analyze text documents or code snippets up to 50KB.
- **Resilient Networking**: Connection pooling with automatic exponential backoff retries on transient network errors.

---

## Installation

Install the package via `pip`:

```bash
pip install chatjimmy
```

Or install with development dependencies:

```bash
pip install chatjimmy[dev]
```

---

## Quick Start

### 1. Simplified Interface

```python
from chatjimmy import ChatJimmy

client = ChatJimmy()

response = client.chat("What is the capital of Japan?")
print(response)
# Output: The capital of Japan is Tokyo.
```

### 2. OpenAI-Compatible Interface

```python
from chatjimmy import ChatJimmy

client = ChatJimmy()

completion = client.chat.completions.create(
    model="llama3.1-8B",
    messages=[
        {"role": "system", "content": "You are a concise, helpful tutor."},
        {"role": "user", "content": "Explain transformers in machine learning in one sentence."},
    ]
)

print(completion.choices[0].message.content)
print(f"Usage: {completion.usage.total_tokens} total tokens")
```

---

## Model Discovery

Discover supported models using either the OpenAI-style resource or direct helper:

```python
from chatjimmy import ChatJimmy

client = ChatJimmy()

# OpenAI-style model list
models = client.models.list()
for model in models:
    print(f"Model: {model.id} (Owner: {model.owned_by})")

# Retrieve specific model
model_info = client.models.retrieve("llama3.1-8B")
print("Retrieved:", model_info.id)
```

---

## Multi-Turn Conversations

By default, `ChatJimmy` tracks conversation history automatically:

```python
from chatjimmy import ChatJimmy

client = ChatJimmy()

# First turn
r1 = client.chat("Hello! My name is Arthur Dent and my favorite number is 42.")
print("Assistant:", r1)

# Second turn (context is preserved)
r2 = client.chat("What is my name and favorite number?")
print("Assistant:", r2)
# Output remembers Arthur Dent and 42!

# Reset history at any time
client.reset_conversation()
```

---

## Real-Time Streaming

### OpenAI-Compatible Streaming

```python
from chatjimmy import ChatJimmy

client = ChatJimmy()

stream = client.chat.completions.create(
    model="llama3.1-8B",
    messages=[{"role": "user", "content": "Write a short poem about silicon processors."}],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)

# Access hardware stats from completed stream
if stream.stats:
    print(f"\n\nSpeed: {stream.stats.decode_rate:.0f} tokens/second")
```

### Simplified Token Streaming

```python
from chatjimmy import ChatJimmy

client = ChatJimmy()

for token in client.chat_stream("Count from 1 to 5"):
    print(token, end="", flush=True)
```

---

## Asynchronous Client (`AsyncChatJimmy`)

For asynchronous applications (e.g., FastAPI, Discord bots, async workers), use `AsyncChatJimmy`.

### Async Chat Completions

```python
import asyncio
from chatjimmy import AsyncChatJimmy

async def main():
    async with AsyncChatJimmy() as client:
        # Simplified async call
        resp = await client.chat("Hello from async!")
        print(resp.text)

        # OpenAI-style async completion
        comp = await client.chat.completions.create(
            model="llama3.1-8B",
            messages=[{"role": "user", "content": "What is 12 * 12?"}],
        )
        print("Answer:", comp.choices[0].message.content)

asyncio.run(main())
```

### Async Streaming

```python
import asyncio
from chatjimmy import AsyncChatJimmy

async def main():
    async with AsyncChatJimmy() as client:
        stream = await client.chat.completions.create(
            model="llama3.1-8B",
            messages=[{"role": "user", "content": "Count from 1 to 5"}],
            stream=True,
        )
        async for chunk in stream:
            content = chunk.choices[0].delta.content
            if content:
                print(content, end="", flush=True)

asyncio.run(main())
```

### Concurrent Requests with asyncio

```python
import asyncio
from chatjimmy import AsyncChatJimmy

async def query_city(city: str):
    async with AsyncChatJimmy() as client:
        resp = await client.chat(f"What is the capital of {city}?")
        return city, resp.text.strip()

async def main():
    cities = ["Japan", "France", "Germany", "Italy"]
    tasks = [query_city(c) for c in cities]
    results = await asyncio.gather(*tasks)

    for city, answer in results:
        print(f"{city}: {answer}")

asyncio.run(main())
```

---

## File Attachments (Up to 50KB)

ChatJimmy accepts file attachments containing source code or text:

```python
from chatjimmy import ChatJimmy, Attachment

client = ChatJimmy()

# Attach a local file
response = client.chat(
    "Review this script for performance bugs.",
    attachment="script.py",
)
print(response)

# Attach raw text in-memory
attachment = Attachment.from_text("def add(a, b): return a + b", name="math.py")
response = client.chat("What does this code do?", attachment=attachment)
print(response)
```

---

## Hardware Performance Metrics

ChatJimmy operates on custom hardware developed by Taalas Inc. Each response provides fine-grained hardware execution statistics:

```python
response = client.chat("Explain quantum entanglement.")

if response.stats:
    print(f"Time to First Token:   {response.stats.ttft * 1000:.2f} ms")
    print(f"Decode Generation Rate:{response.stats.decode_rate:.0f} tokens/s")
    print(f"Prefill Rate:          {response.stats.prefill_rate:.0f} tokens/s")
    print(f"Total Compute Time:    {response.stats.total_time * 1000:.2f} ms")
    print(f"Total Tokens:          {response.stats.total_tokens}")
    print(f"Exit Reason:           {response.stats.reason}")
```

| Metric Field | Description | Typical Value |
|---|---|---|
| `stats.ttft` | Time To First Token in seconds | `~0.0008s – 0.0015s` (sub-2ms) |
| `stats.decode_rate` | Output token generation speed | `15,000 – 18,500 tokens/s` |
| `stats.prefill_rate` | Context / prompt processing speed | `14,000 – 21,000 tokens/s` |
| `stats.device_compute_time`| Pure on-chip execution time | `< 0.05s for 800 tokens` |

---

## Configuration & Networking

```python
from chatjimmy import ChatJimmy

client = ChatJimmy(
    base_url="https://chatjimmy.ai",  # Override base URL if proxied
    model="llama3.1-8B",             # Default model ID
    top_k=8,                         # Top-K sampling (1 to 8)
    system_prompt="Be concise.",     # Default system instruction
    timeout=45.0,                    # Timeout in seconds
    max_retries=3,                   # Retries on 429, 502, 503, 504
    headers={"X-Custom": "Header"},  # Extra HTTP headers
    maintain_history=True,           # Auto-manage multi-turn history
)
```

---

## Error Handling

All SDK exceptions inherit from `ChatJimmyError`:

```python
from chatjimmy import (
    ChatJimmy,
    ChatJimmyAPIError,
    ChatJimmyConnectionError,
    ChatJimmyTimeoutError,
    ChatJimmyValidationError,
)

client = ChatJimmy(timeout=5.0)

try:
    response = client.chat("Hello!")
except ChatJimmyTimeoutError:
    print("The request or stream timed out.")
except ChatJimmyAPIError as e:
    print(f"Backend HTTP error {e.status_code}: {e.error_message}")
except ChatJimmyConnectionError:
    print("Network connectivity failed.")
except ChatJimmyValidationError as e:
    print(f"Input validation error: {e}")
```

---

## Testing

Run the test suite:

```bash
# Run all unit and live integration tests
python -m pytest -v

# Run only mocked unit tests
python -m pytest -v -m "not live"

# Run only live integration tests
python -m pytest -v -m "live"
```

---

## Known Limitations

1. **Available Models**: The platform is dedicated to `llama3.1-8B`. Requests specifying other model IDs are mapped to the default model.
2. **Attachment Size Limit**: The platform enforces a strict 50KB limit on file attachments.
3. **Context Length**: The backend enforces context limits; if reached, the generation terminates with reason `"max context limit <N> reached"`.
4. **Service Availability**: Because this library interfaces with a public web endpoint without an SLA, changes to `https://chatjimmy.ai` may require SDK updates.

---

## License

Distributed under the [MIT License](LICENSE).
