Skip to main content

GLChat Python Client

Project description

GLAIR

๐Ÿค– GLChat Python SDK ๐Ÿ

PyPI Latest Release License

A lightweight, flexible Python client for interacting with the GLChat Backend API, providing a simple interface to send messages and receive streaming responses. Built with an OpenAI-like API design for familiarity and ease of use.

๐Ÿ“‹ Overview

GLChat Python Client is a Python library that simplifies interaction with the GLChat service. It provides a clean, intuitive API for sending messages, handling file attachments, and processing streaming responses, enabling rapid development of chat applications.

๐Ÿ“‹ Requirements

Python 3.11.x or higher is required.

โœจ Features

  • ๐Ÿ”Œ OpenAI-like API: Familiar interface following the OpenAI SDK pattern
  • ๐Ÿ” Authentication Support: Built-in API key authentication
  • ๐Ÿš€ Simple API: Send messages and receive responses with minimal code
  • โšก Streaming Support: Process responses in real-time as they arrive
  • ๐Ÿ“Ž File Integration: Easily attach and send files with your messages
  • ๐Ÿ’ฌ Conversation Management: Create and manage conversations with chatbots
  • ๐ŸŽฏ Type Safety: Comprehensive type hints for better development experience
  • ๐Ÿ”„ Flexible Response Handling: Choose between streaming or complete text responses
  • ๐Ÿ’พ Memory Efficient: Optimized file handling for large files

๐Ÿ“ฆ Installation

To install the package:

pip install glchat-sdk

After installation, you can verify it works by trying to import it from any directory:

from glchat_sdk import GLChat

๐Ÿš€ Quick Start

Creating a chat client with GLChat is incredibly simple:

from glchat_sdk import GLChat

# Initialize the GLChat client with your API key
client = GLChat(api_key="your-api-key")

# Send a message to the chatbot and receive a streaming response
for chunk in client.message.create(
    application_id="your-application-id",
    message="Hello!"
):
    print(chunk.decode("utf-8"), end="")

# Create a new conversation
conversation = client.conversation.create(
    user_id="your-user-id",
    application_id="your-application-id",
    title="My First Conversation"
)
print(f"Created conversation: {conversation['conversation_id']}")

Note: Make sure you have the correct chatbot ID and API key before running example.

๐Ÿ” Environment Variables

GLChat uses os.getenv() to read environment variables. You are responsible for loading environment variables in your application before initializing the GLChat client. You can use libraries like python-dotenv, python-decouple, or set them directly in your shell.

Available environment variables:

  • GLCHAT_API_KEY: Your GLChat API key for authentication
  • GLCHAT_BASE_URL: Custom base URL for the GLChat API (optional)

Example using python-dotenv:

First, install python-dotenv:

pip install python-dotenv

Create a .env file:

GLCHAT_API_KEY=your-api-key
GLCHAT_BASE_URL=https://your-custom-endpoint.com/api/

Load environment variables in your code:

from dotenv import load_dotenv
from glchat_sdk import GLChat

# Load environment variables from .env file
load_dotenv()

# Will automatically use environment variables
client = GLChat()

Example using shell export:

export GLCHAT_API_KEY="your-api-key"
export GLCHAT_BASE_URL="https://your-custom-endpoint.com/api/"

Then initialize the client without parameters:

from glchat_sdk import GLChat

# Will automatically use environment variables
client = GLChat()

๐Ÿ”ง Advanced Usage

๐Ÿ“ค Sending Messages with Files

from pathlib import Path
from glchat_sdk import GLChat

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

# Send message with file attachment
for chunk in client.message.create(
    application_id="your-application-id",
    message="What's in this file?",
    files=[Path("/path/to/your/file.txt")],
    user_id="user@example.com",
    conversation_id="your-conversation-id",
    model_name="openai/gpt-4o-mini"
):
    print(chunk.decode("utf-8"), end="")

๐Ÿ“ Using Different File Types

from glchat_sdk import GLChat
import io

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

# File path
file_path = "/path/to/file.txt"

# File-like object
file_obj = io.BytesIO(b"file content")

# Raw bytes
file_bytes = b"file content"

# Send with different file types
for chunk in client.message.create(
    application_id="your-application-id",
    message="Process these files",
    files=[file_path, file_obj, file_bytes]
):
    print(chunk.decode("utf-8"), end="")

๐Ÿ“š API Reference

GLChat

The main client class for interacting with the GLChat API.

๐Ÿ”ง Initialization

client = GLChat(
    api_key: str | None = None,
    base_url: str | None = None,
    timeout: float = 60.0,
)

Parameters:

  • api_key: Your GLChat API key for authentication (set GLCHAT_API_KEY env var) ๐Ÿ”‘
  • base_url: Custom base URL for the GLChat API (optional, or set GLCHAT_BASE_URL env var) ๐ŸŒ
  • timeout: Request timeout in seconds (optional, default: 60.0) โฑ๏ธ

Methods

๐Ÿ’ฌ message.create

Creates a streaming response from the GLChat API.

response_stream = client.message.create(
    application_id: str | None = None,
    chatbot_id: str | None = None,  # (DEPRECATED) Use application_id instead
    message: str,
    parent_id: str | None = None,
    source: str | None = None,
    quote: str | None = None,
    user_id: str | None = None,
    conversation_id: str | None = None,
    user_message_id: str | None = None,
    assistant_message_id: str | None = None,
    chat_history: str | None = None,
    files: List[Union[str, Path, BinaryIO, bytes]] | None = None,
    stream_id: str | None = None,
    metadata: str | None = None,
    model_name: str | None = None,
    anonymize_em: bool | None = None,
    anonymize_lm: bool | None = None,
    use_cache: bool | None = None,
    search_type: str | None = None
) -> Iterator[bytes]

Parameters:

  • application_id: Application identifier (recommended) ๐Ÿ†”
  • chatbot_id: (DEPRECATED) Chatbot identifier - use application_id instead ๐Ÿค–
  • message: Required user message ๐Ÿ’ฌ
  • parent_id: Parent message ID for threading (optional) ๐Ÿงต
  • source: Source identifier for the message (optional) ๐Ÿ“
  • quote: Quoted message content (optional) ๐Ÿ’ญ
  • user_id: User identifier (optional) ๐Ÿ‘ค
  • conversation_id: Conversation identifier (optional) ๐Ÿ’ฌ
  • user_message_id: User message identifier (optional) ๐Ÿ†”
  • assistant_message_id: Assistant message identifier (optional) ๐Ÿค–
  • chat_history: Chat history context (optional) ๐Ÿ“š
  • files: List of files (filepath, binary, file object, or bytes) (optional) ๐Ÿ“Ž
  • stream_id: Stream identifier (optional) ๐ŸŒŠ
  • metadata: Additional metadata (optional) ๐Ÿ“‹
  • model_name: Model name to use for generation (optional) ๐Ÿง 
  • anonymize_em: Whether to anonymize embeddings (optional) ๐Ÿ•ต๏ธ
  • anonymize_lm: Whether to anonymize language model (optional) ๐Ÿ•ต๏ธ
  • use_cache: Whether to use cached responses (optional) ๐Ÿ’พ
  • search_type: Type of search to perform (optional) ๐Ÿ”

Returns:

  • Iterator[bytes]: Streaming response chunks ๐Ÿ“ก
๐Ÿ’ฌ conversation.create

Creates a new conversation with the GLChat API.

conversation = client.conversation.create(
    user_id: str,
    application_id: str | None = None,
    chatbot_id: str | None = None,  # (DEPRECATED) Use application_id instead
    title: str | None = None,
    model_name: str | None = None
) -> dict[str, Any]

Parameters:

  • user_id: Required user identifier ๐Ÿ‘ค
  • application_id: Application identifier (recommended) ๐Ÿ†”
  • chatbot_id: (DEPRECATED) Chatbot identifier - use application_id instead ๐Ÿค–
  • title: Optional conversation title ๐Ÿ“
  • model_name: Optional model name to use ๐Ÿง 

Returns:

  • dict[str, Any]: Conversation response data including conversation_id ๐Ÿ’ฌ
๐Ÿค– chatbots.list

Lists available chatbots from the GLChat API.

chatbots = client.chatbots.list(
    user_id: str | None = None,
    extra_headers: dict[str, str] | None = None
) -> dict[str, Any]

Parameters:

  • user_id: Optional user identifier to filter chatbots (optional) ๐Ÿ‘ค
  • extra_headers: Additional headers to include in the request (optional) ๐Ÿ“‹

Returns:

  • dict[str, Any]: Dictionary containing chatbots response data ๐Ÿค–
๐Ÿ” auth.whatsapp.register

Registers new users with WhatsApp.

response = client.auth.whatsapp.register(
    whatsapp_id: str,
    email: str,
    profile_name: str | None = None,
    extra_headers: dict[str, str] | None = None
) -> dict[str, Any]

Parameters:

  • whatsapp_id: WhatsApp ID of the user (required) ๐Ÿ“ฑ
  • email: Email address of the user (required) ๐Ÿ“ง
  • profile_name: Profile name of the user (optional) ๐Ÿ‘ค
  • extra_headers: Additional headers for WhatsApp authentication and multi-tenancy (optional) ๐Ÿ”‘

Returns:

  • dict[str, Any]: Dictionary containing the registration response data โœ…
๐Ÿ‘ค users.verification.username.list

Gets username by phone number.

response = client.users.verification.username.list(
    phone_number: str,
    extra_headers: dict[str, str] | None = None
) -> dict[str, Any]

Parameters:

  • phone_number: Phone number in international format (e.g., +62812345678 or 62812345678) (required) ๐Ÿ“ž
  • extra_headers: Additional headers for WhatsApp authentication and multi-tenancy (optional) ๐Ÿ”‘

Returns:

  • dict[str, Any]: Dictionary containing the username response data ๐Ÿ‘ค
๐Ÿ“ง users.verification.resend

Resends verification code.

response = client.users.verification.resend(
    challenge_id: str,
    channel: str,
    extra_headers: dict[str, str] | None = None
) -> dict[str, Any]

Parameters:

  • challenge_id: Challenge ID (required) ๐Ÿ†”
  • channel: Verification channel ("SMS", "WHATSAPP", or "EMAIL") (required) ๐Ÿ“ฑ
  • extra_headers: Additional headers to include in the request (optional) ๐Ÿ“‹

Returns:

  • dict[str, Any]: Dictionary containing the resend verification response data ๐Ÿ“ง
โŒ users.verification.cancel

Cancels verification challenge.

client.users.verification.cancel(
    challenge_id: str,
    extra_headers: dict[str, str] | None = None
) -> None

Parameters:

  • challenge_id: Challenge ID (required) ๐Ÿ†”
  • extra_headers: Additional headers to include in the request (optional) ๐Ÿ“‹

Returns:

  • None: No return value
โœ… users.verification.verify_and_bind

Verifies OTP code and binds phone or email to user.

client.users.verification.verify_and_bind(
    challenge_id: str,
    code: str,
    extra_headers: dict[str, str] | None = None
) -> None

Parameters:

  • challenge_id: Challenge ID (required) ๐Ÿ†”
  • code: OTP code to verify (required) ๐Ÿ”ข
  • extra_headers: Additional headers to include in the request (optional) ๐Ÿ“‹

Returns:

  • None: No return value
๐Ÿ“จ users.verification.request_verification

Requests phone number or email verification.

response = client.users.verification.request_verification(
    username: str,
    contact: str,
    channel: str,
    extra_headers: dict[str, str] | None = None
) -> dict[str, Any]

Parameters:

  • username: Username to bind with phone number (required) ๐Ÿ‘ค
  • contact: Phone number in international format or email address (required) ๐Ÿ“ž
  • channel: Verification channel ("SMS", "WHATSAPP", or "EMAIL") (required) ๐Ÿ“ฑ
  • extra_headers: Additional headers to include in the request (optional) ๐Ÿ“‹

Returns:

  • dict[str, Any]: Dictionary containing the request verification response data ๐Ÿ“จ

๐Ÿ“ File Support

The client supports various file input types with optimized memory handling:

  • ๐Ÿ“‚ File paths (string or Path object)
  • ๐Ÿ’พ Binary data (bytes)
  • ๐Ÿ“„ File-like objects (with read() method) - passed directly to avoid memory issues

๐Ÿ” Authentication

The client supports API key authentication with flexible configuration options. The API key can be provided either as a parameter during initialization or through environment variables.

๐Ÿ”‘ API Key Configuration

Option 1: Direct Parameter

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

Option 2: Environment Variable

export GLCHAT_API_KEY="your-api-key"
client = GLChat()  # Automatically uses GLCHAT_API_KEY environment variable

Option 3: Priority System

# Parameter takes priority over environment variable
client = GLChat(api_key="explicit-api-key")  # Uses explicit key even if env var is set

๐Ÿ”’ Authentication Headers

When an API key is provided (via parameter or environment variable), it's automatically included in the Authorization header for all requests:

# API key is automatically used in requests ๐Ÿ”‘
client = GLChat(api_key="your-api-key")
for chunk in client.message.create(application_id="your-application-id", message="Hello!"):
    print(chunk.decode("utf-8"), end="")

๐Ÿ“ฑ WhatsApp API and Multi-Tenancy

For WhatsApp operations and multi-tenant setups, you can pass additional headers using the extra_headers parameter:

# WhatsApp user registration with tenant ID
extra_headers = {
    "X-API-Key": "your-whatsapp-api-key",
    "X-Tenant-ID": "your-tenant-id"
}
response = client.auth.whatsapp.register(
    whatsapp_id="62812345678",
    email="user@example.com",
    extra_headers=extra_headers
)

# Get username by phone with WhatsApp API key
extra_headers = {"X-API-Key": "your-whatsapp-api-key"}
response = client.users.verification.username.list(
    phone_number="62812345678",
    extra_headers=extra_headers
)

Note: The extra_headers parameter will override any existing headers with the same key from default_headers.

โš ๏ธ Required Configuration

API key is required - you must provide it either:

  • As the api_key parameter when initializing the client, OR
  • Set the GLCHAT_API_KEY environment variable

If neither is provided, the client will raise a ValueError:

client = GLChat()  # Raises ValueError if GLCHAT_API_KEY is not set

โš ๏ธ Error Handling

The client uses httpx for HTTP requests and will raise appropriate exceptions for HTTP errors. Make sure to handle these exceptions in your code.

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

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

glchat_sdk-0.0.3-py3-none-any.whl (21.7 kB view details)

Uploaded Python 3

File details

Details for the file glchat_sdk-0.0.3-py3-none-any.whl.

File metadata

  • Download URL: glchat_sdk-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 21.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.22

File hashes

Hashes for glchat_sdk-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 52171993c378b1147fedf07bfe8bc0f066ee173ffa351f085af9455647180271
MD5 60eefe8bc34e8eb3324d98094cbe31de
BLAKE2b-256 27237699e419371927262994e33347d650e1c28939803d4c9a751b00b69ed6f0

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