From 08437f46b101c23ba53b1fa02367cedc988eb67d Mon Sep 17 00:00:00 2001 From: innocent-charles Date: Sun, 23 Aug 2026 16:44:03 +0300 Subject: [PATCH] Add runnable usage examples from pip install to API responses. Include getting_started.py and examples README covering chat, streaming, embeddings, models, error handling, raw responses, and async usage. Co-authored-by: Cursor --- README.md | 2 + examples/README.md | 78 ++++++++++++++ examples/getting_started.py | 207 ++++++++++++++++++++++++++++++++++++ 3 files changed, 287 insertions(+) create mode 100644 examples/README.md create mode 100644 examples/getting_started.py diff --git a/README.md b/README.md index 4b8c684..37b06cd 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..78383b8 --- /dev/null +++ b/examples/README.md @@ -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) diff --git a/examples/getting_started.py b/examples/getting_started.py new file mode 100644 index 0000000..e724ad3 --- /dev/null +++ b/examples/getting_started.py @@ -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()