Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export PAWA_AI_API_KEY="your_api_key_here"

Get your key from the [Builders Dashboard](https://builder.pawa-ai.com/dashboard?page=keys).

See **[examples/](examples/)** for a full walkthrough from `pip install` to typed responses.

### Chat

```python
Expand Down
78 changes: 78 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Examples

Runnable examples for the [pawa-ai](https://pypi.org/project/pawa-ai/) package.

## 1. Install

```bash
pip install pawa-ai
```

Or install from source while developing this repo:

```bash
pip install -e ".[dev]"
```

## 2. Set your API key

Get a key from the [Pawa AI Builders Dashboard](https://builder.pawa-ai.com/dashboard?page=keys).

```bash
export PAWA_AI_API_KEY="your_api_key_here"
```

Or pass it in code:

```python
from pawa_ai import PawaAI

client = PawaAI(api_key="your_api_key_here")
```

## 3. Run the examples

```bash
python examples/getting_started.py
```

This script runs:

| Example | What you get back |
|---------|-------------------|
| Chat | `ChatCompletion` with `.text` and optional `.usage` |
| Streaming | Token deltas printed live, then full text via `.collect()` |
| Embeddings | `EmbeddingResponse` with `.embeddings` (list of vectors) |
| Models | `ModelList` with `.models` |
| Error handling | Catches `AuthenticationError`, `RateLimitError`, etc. |
| Raw JSON | Plain `dict` when you pass `raw=True` |
| Async chat | Same as chat, using `AsyncPawaAI` |

## 4. Minimal chat example

```python
from pawa_ai import PawaAI

client = PawaAI()

response = client.chat.create(
model="pawa-v1-ember-20240924",
messages=[
{
"role": "user",
"content": [{"type": "text", "text": "Hello!"}],
}
],
)

print(response.text)
```

## 5. More capabilities

See the [main README](../README.md) for text-to-speech, speech-to-text, documents, agents, and knowledge base usage.

## Links

- [Pawa AI Docs](https://docs.pawa-ai.com)
- [API Reference](https://docs.pawa-ai.com/api-reference/introduction)
207 changes: 207 additions & 0 deletions examples/getting_started.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
#!/usr/bin/env python3
"""
Pawa AI Python SDK — getting started examples.

Install:
pip install pawa-ai

Set your API key:
export PAWA_AI_API_KEY="your_api_key_here"

Run:
python examples/getting_started.py
"""

from __future__ import annotations

import asyncio
import os
import sys


def require_api_key() -> str:
api_key = os.environ.get("PAWA_AI_API_KEY")
if not api_key:
print("Error: set PAWA_AI_API_KEY before running this script.", file=sys.stderr)
print(' export PAWA_AI_API_KEY="your_api_key_here"', file=sys.stderr)
sys.exit(1)
return api_key


def example_chat() -> None:
"""Basic chat completion — returns a typed ChatCompletion response."""
from pawa_ai import PawaAI

client = PawaAI()

response = client.chat.create(
model="pawa-v1-ember-20240924",
messages=[
{
"role": "system",
"content": [
{
"type": "text",
"text": "You are a helpful assistant for developers in Africa.",
}
],
},
{
"role": "user",
"content": [
{"type": "text", "text": "Hello! How can I use AI in my app?"}
],
},
],
stream=False,
)

print("=== Chat completion ===")
print(f"Success: {response.success}")
print(f"Model: {response.model}")
print(f"Reply: {response.text}")
if response.usage:
print(f"Tokens: in={response.usage.tokens_in}, out={response.usage.tokens_out}")
print()


def example_streaming() -> None:
"""Stream chat tokens as they arrive, then collect the full reply."""
from pawa_ai import PawaAI

client = PawaAI()

print("=== Streaming chat ===")
print("Reply: ", end="", flush=True)

with client.chat.create(
model="pawa-v1-ember-20240924",
messages=[
{
"role": "user",
"content": [{"type": "text", "text": "Explain RAG in one short paragraph."}],
}
],
stream=True,
) as stream:
for delta in stream.text_deltas():
print(delta, end="", flush=True)

print()
print(f"Collected: {stream.collect().text[:80]}...")
print()


def example_embeddings() -> None:
"""Create embeddings for a list of sentences."""
from pawa_ai import PawaAI

client = PawaAI()

response = client.vectors.create(
model="pawa-embeddings-v1-20241001",
sentences=["Embed this sentence.", "And this one too."],
lang="multi",
)

print("=== Embeddings ===")
print(f"Success: {response.success}")
print(f"Count: {len(response.embeddings)} vectors")
if response.embeddings:
print(f"Dimensions: {len(response.embeddings[0])}")
print()


def example_list_models() -> None:
"""List available models on the platform."""
from pawa_ai import PawaAI

client = PawaAI()

models = client.models.list(limit=5)

print("=== Models ===")
print(f"Success: {models.success}")
for model in models.models[:5]:
name = model.name or "unknown"
model_type = model.model_type or "unknown"
print(f" - {name} ({model_type})")
print()


def example_error_handling() -> None:
"""Handle common API errors."""
from pawa_ai import AuthenticationError, PawaAI, RateLimitError

client = PawaAI()

try:
client.chat.create(
model="pawa-v1-ember-20240924",
messages=[], # invalid — triggers a 400 from the API
)
except AuthenticationError as exc:
print(f"Auth error ({exc.status_code}): {exc.message}")
except RateLimitError as exc:
print(f"Rate limited ({exc.status_code}): {exc.message}")
except Exception as exc:
print(f"Expected validation error: {exc.__class__.__name__}: {exc}")
print()


async def example_async_chat() -> None:
"""Async chat completion."""
from pawa_ai import AsyncPawaAI

async with AsyncPawaAI() as client:
response = await client.chat.create(
model="pawa-v1-ember-20240924",
messages=[
{"role": "user", "content": [{"type": "text", "text": "Habari yako?"}]}
],
)

print("=== Async chat ===")
print(f"Reply: {response.text}")
print()


def example_raw_response() -> None:
"""Get the original JSON dict instead of typed models."""
from pawa_ai import PawaAI

client = PawaAI()

payload = client.chat.create(
model="pawa-v1-ember-20240924",
messages=[
{"role": "user", "content": [{"type": "text", "text": "Say hi in Swahili."}]}
],
raw=True,
)

print("=== Raw JSON response ===")
print(f"Keys: {list(payload.keys())}")
print(f"Message field: {payload.get('message')}")
print()


def main() -> None:
require_api_key()

print("Pawa AI Python SDK examples\n")

example_chat()
example_streaming()
example_embeddings()
example_list_models()
example_error_handling()
example_raw_response()

asyncio.run(example_async_chat())

print("Done.")


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