GLChat Python Client
Project description
๐ค GLChat Python SDK ๐
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 authenticationGLCHAT_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,
agent_id: str | None = None,
exclude_events: list[str] | None = None,
stream_message_only: bool | None = None,
exclude_prefix: bool | None = None,
include_states: bool | None = None,
filters: str | None = None,
extra_headers: dict[str, str] | None = None,
**kwargs: Any
) -> 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) ๐agent_id: Agent identifier to use for the message (optional) ๐คexclude_events: Defines event types for the event emitter module. (optional) ๐ซstream_message_only: If true, only stream the message content without additional events (optional) ๐กexclude_prefix: If true, exclude the prefix from the response (optional) ๐ซinclude_states: If true, include state information in the response (optional) ๐filters: Stringified JSON representing filters to apply (optional) ๐๏ธextra_headers: Additional headers to include in the request (optional) ๐**kwargs: Additional arbitrary parameters to include in the request payload. Useful if you need to quickly pass parameters currently unsupported in this SDK ๐ฆ
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,
extra_headers: dict[str, 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 ๐งextra_headers: Additional headers to include in the request (optional) ๐
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_keyparameter when initializing the client, OR - Set the
GLCHAT_API_KEYenvironment 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file glchat_sdk-0.0.7-py3-none-any.whl.
File metadata
- Download URL: glchat_sdk-0.0.7-py3-none-any.whl
- Upload date:
- Size: 22.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
09825f4fc03b9bad52fd1a0ae191a4c309a915b53c903fb418221d35310e0860
|
|
| MD5 |
df9b217263b4ccbb66e08c063c51732f
|
|
| BLAKE2b-256 |
46cebb8462e0d076c90c6c587ab6de52bfaae6b18281645676aa981dce55ddd1
|