Skip to main content

Official Python SDK for Mia21 Chat API - Build AI chatbots in minutes with tool calling support

Project description

🐍 Mia21 Python SDK

Official Python client library for the Mia21 Chat API.

PyPI version Python License


🚀 Quick Start

Installation

pip install mia21

Basic Usage

from mia21 import Mia21Client

# Initialize client
client = Mia21Client(api_key="your-api-key-here")

# Start chat session
client.initialize(space_id="customer_support")

# Send a message
response = client.chat("How do I reset my password?")
print(response.message)

# Close session
client.close()

Streaming Chat

from mia21 import Mia21Client

client = Mia21Client(api_key="your-api-key-here")
client.initialize()

# Stream response in real-time
print("AI: ", end='', flush=True)
for chunk in client.stream_chat("Tell me a story"):
    print(chunk, end='', flush=True)
print()  # New line

client.close()

Context Manager (Auto-Close)

from mia21 import Mia21Client

with Mia21Client(api_key="your-api-key") as client:
    client.initialize(space_id="sales_assistant")
    response = client.chat("What are your pricing plans?")
    print(response.message)
# Chat automatically closed

📚 API Reference

Mia21Client

Constructor

client = Mia21Client(
    api_key: str,              # Required: Your Mia21 API key
    base_url: str = "...",     # Optional: API base URL
    user_id: str = None,       # Optional: User ID (auto-generated if not provided)
    timeout: int = 90          # Optional: Request timeout in seconds
)

Methods

list_spaces()

spaces = client.list_spaces()
# Returns: List[Space]

for space in spaces:
    print(f"{space.id}: {space.name} - {space.description}")

initialize()

response = client.initialize(
    space_id="customer_support",    # Optional: Space to use
    llm_type="openai",              # Optional: "openai" or "gemini"
    user_name="John",               # Optional: User's name
    language="en",                  # Optional: Force language
    generate_first_message=True,    # Optional: Generate greeting
    incognito_mode=False            # Optional: Privacy mode
)
# Returns: InitializeResponse

print(response.message)  # AI's first message

chat()

response = client.chat(
    message="Hello!",               # Required: User message
    space_id="customer_support",    # Optional: Which space
    temperature=0.7,                # Optional: 0.0-2.0
    max_tokens=1024                 # Optional: Max response length
)
# Returns: ChatResponse

print(response.message)  # AI's response
print(response.tool_calls)  # Tools executed (if any)

stream_chat()

for chunk in client.stream_chat(
    message="Tell me a story",
    space_id="storyteller",
    temperature=0.9
):
    print(chunk, end='', flush=True)
# Yields: str (text chunks)

close()

client.close(
    space_id="customer_support"     # Optional: Which space to close
)
# Saves conversation to database

🎯 Advanced Examples

Multi-Space Conversation

from mia21 import Mia21Client

client = Mia21Client(api_key="your-api-key")

# Initialize multiple spaces
client.initialize(space_id="support")
client.initialize(space_id="sales")
client.initialize(space_id="technical")

# Chat with different spaces independently
support_response = client.chat("I have a bug", space_id="support")
sales_response = client.chat("Pricing info?", space_id="sales")
tech_response = client.chat("API docs?", space_id="technical")

# Each space maintains separate conversation history

Error Handling

from mia21 import Mia21Client, ChatNotInitializedError, APIError

client = Mia21Client(api_key="your-api-key")

try:
    # This will raise ChatNotInitializedError
    client.chat("Hello")  # Forgot to initialize!
except ChatNotInitializedError as e:
    print(f"Error: {e}")
    client.initialize()  # Fix it
    client.chat("Hello")  # Now works

try:
    response = client.chat("What's the weather?")
except APIError as e:
    print(f"API Error: {e}")

Async Integration (with asyncio)

import asyncio
from mia21 import Mia21Client

async def chat_async():
    client = Mia21Client(api_key="your-api-key")
    client.initialize()
    
    # Run in executor to avoid blocking
    loop = asyncio.get_event_loop()
    response = await loop.run_in_executor(
        None, 
        client.chat, 
        "Hello from async!"
    )
    
    print(response.message)
    client.close()

asyncio.run(chat_async())

🛠️ Configuration

Environment Variables

# Set API key via environment
export MIA21_API_KEY="your-api-key-here"
export MIA21_BASE_URL="https://mia-api-staging-795279012747.us-central1.run.app"
import os
from mia21 import Mia21Client

# Reads from environment variables
client = Mia21Client(
    api_key=os.getenv("MIA21_API_KEY"),
    base_url=os.getenv("MIA21_BASE_URL")
)

🧪 Testing

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest tests/

# Run with coverage
pytest --cov=mia21 tests/

📄 License

MIT License - see LICENSE file for details.


🆘 Support


🎉 Examples

See the examples/ directory for complete working examples:

  • basic_chat.py - Simple chat example
  • streaming_chat.py - Streaming response example
  • multi_space.py - Multiple spaces conversation
  • async_chat.py - Asyncio integration

Made with ❤️ by Mia21

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mia21-1.3.0.tar.gz (16.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mia21-1.3.0-py3-none-any.whl (15.3 kB view details)

Uploaded Python 3

File details

Details for the file mia21-1.3.0.tar.gz.

File metadata

  • Download URL: mia21-1.3.0.tar.gz
  • Upload date:
  • Size: 16.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for mia21-1.3.0.tar.gz
Algorithm Hash digest
SHA256 f95760b6a56b0b5ce30f52921a78d2517d730857fd02763c35ff5032604231ef
MD5 d8ccf4a9c38793165723926820fab698
BLAKE2b-256 a993fca29fdeccde82e7ae3b3369d86449f4ccbedc61159220c0f429f68ac5c5

See more details on using hashes here.

File details

Details for the file mia21-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: mia21-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 15.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for mia21-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8cbd9031533ff25a33213d1bea8fb077f95adda77cecb34c5c4794c39fac60b1
MD5 f61e4a4c874d4089fd7ae488be45cdc0
BLAKE2b-256 7cd0266a8ce5b7a12de80003cb9ec9316f2fead321ca0841c45705b56ce095c3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page