Skip to main content

Official Python client for TitanGPT API

Reason this release was yanked:

error in sync client (api endpoint)

Project description

TitanGPT Python Client

PyPI version License: MIT

🇬🇧 English Version | 🇷🇺 Русская версия


🇬🇧 English Version

The official Python library for the TitanGPT API. Designed to be fully compatible with the OpenAI v1+ syntax, allowing for seamless integration into existing projects.

Features

  • 🚀 Full Compatibility: Follows the OpenAI syntax structure (client.chat.completions.create).
  • 🌍 UTF-8 Support: Correctly handles API keys containing non-ASCII characters (e.g., Cyrillic) by automatically encoding headers.
  • Sync & Async: Includes both TitanGPT and AsyncTitanGPT clients.
  • 🎨 Image Generation: Support for Flux style generation.
  • 🎵 Music Search: Unique module for searching tracks via internal API.
  • 🔧 Flexibility: Supports custom parameters like verbosity, reasoning_effort (for o-series models), etc.

Installation

pip install titangpt

Quick Start

Synchronous Client

from titangpt import TitanGPT

# Initialize client (api_key is optional if TITANGPT_API_KEY env var is set)
client = TitanGPT(api_key="YOUR_API_KEY")

# 1. Chat Completion
response = client.chat.completions.create(
    model="gpt-5.2-2025-12-11",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain quantum physics in 1 sentence."}
    ]
)

print(response.choices[0].message.content)

# 2. Image Generation
image = client.images.generate(
    prompt="A futuristic cyberpunk city, neon lights, rain",
    model="flux",
    size="1024x1024"
)

# Output base64 or URL (depending on server response)
print(image.data[0].b64_json[:50] + "...") 

Asynchronous Client

Ideal for high-load applications (FastAPI, Bots).

import asyncio
from titangpt import AsyncTitanGPT

async def main():
    # Uses aiohttp under the hood
    client = AsyncTitanGPT(api_key="YOUR_API_KEY")

    response = await client.chat.completions.create(
        model="gpt-5.2-2025-12-11",
        messages=[{"role": "user", "content": "Write a haiku about Python."}]
    )
    print(response.choices[0].message.content)
    
    await client.close()

if __name__ == "__main__":
    asyncio.run(main())

Advanced Usage

You can pass any arbitrary parameters (like reasoning_effort or custom dictionaries) using **kwargs.

response = client.chat.completions.create(
    model="gpt-5.2-2025-12-11", 
    messages=[{"role": "user", "content": "Solve this logic puzzle..."}],
    
    # Specific parameter for reasoning models
    reasoning_effort="high",
    
    # Custom parameter accepted by TitanGPT backend
    text={
        "verbosity": "high"
    }
)

Music & Audio

# Music Search
track = client.music.search(query="Linkin Park Numb")
print(f"Title: {track.title}, URL: {track.url}")

# Audio Transcription (Whisper)
with open("speech.mp3", "rb") as f:
    transcription = client.audio.transcriptions.create(model="whisper-1", file=f)
    print(transcription.text)

🔗 Links & Support

If you have any questions or need support, join our Telegram channel.

🇷🇺 Русская версия

Официальная Python библиотека для работы с API TitanGPT. Библиотека спроектирована так, чтобы быть максимально совместимой с синтаксисом OpenAI (v1+), что позволяет легко использовать её в существующих проектах, просто меняя import.

Особенности

  • 🚀 Полная совместимость: Синтаксис идентичен OpenAI (client.chat.completions.create).
  • 🇷🇺 Поддержка UTF-8: Исправлена проблема с кодировкой заголовков. API-ключи с кириллицей или спецсимволами работают корректно.
  • Синхронный и Асинхронный клиенты (TitanGPT и AsyncTitanGPT).
  • 🎨 Генерация изображений: Поддержка Flux style.
  • 🎵 Поиск музыки: Уникальный модуль для поиска треков.
  • 🔧 Гибкость: Поддержка любых кастомных параметров (verbosity, reasoning_effort и др.).

Установка

pip install titangpt

Быстрый старт

Синхронный клиент

from titangpt import TitanGPT

# Инициализация (ключ можно не передавать, если задан TITANGPT_API_KEY в env)
client = TitanGPT(api_key="ВАШ_КЛЮЧ")

# 1. Чат (Генерация текста)
response = client.chat.completions.create(
    model="gpt-5.2-2025-12-11",
    messages=[
        {"role": "system", "content": "Ты полезный помощник."},
        {"role": "user", "content": "Привет! Расскажи коротко о квантовой физике."}
    ]
)

# Доступ к полям через точку
print(response.choices[0].message.content)

# 2. Генерация изображений
image = client.images.generate(
    prompt="Футуристичный киберпанк город, неон, дождь",
    model="flux",
    size="1024x1024"
)

print(image.data[0].b64_json[:50] + "...") 

Асинхронный клиент

Идеально для FastAPI и Telegram-ботов.

import asyncio
from titangpt import AsyncTitanGPT

async def main():
    # Используется aiohttp под капотом
    client = AsyncTitanGPT(api_key="ВАШ_КЛЮЧ")

    response = await client.chat.completions.create(
        model="gpt-5.2-2025-12-11",
        messages=[{"role": "user", "content": "Напиши хокку про Python."}]
    )
    print(response.choices[0].message.content)
    
    # Закрытие сессии обязательно
    await client.close()

if __name__ == "__main__":
    asyncio.run(main())

Продвинутые возможности

Библиотека поддерживает передачу любых параметров, которые принимает API, через **kwargs.

response = client.chat.completions.create(
    model="gpt-5.2-2025-12-11", 
    messages=[{"role": "user", "content": "Реши задачу..."}],
    
    # Параметр для o-серии моделей
    reasoning_effort="high",
    
    # Кастомный параметр text (например, для управления детализацией)
    text={
        "verbosity": "low"
    }
)

Музыка и Аудио

# Поиск музыки
track = client.music.search(query="Linkin Park Numb")
print(f"Трек: {track.title}")
print(f"Ссылка: {track.url}")

# Транскрибация (Whisper)
with open("speech.mp3", "rb") as f:
    transcription = client.audio.transcriptions.create(model="whisper-1", file=f)
    print(transcription.text)

Конфигурация

Вы можете настроить базовый URL, таймауты и количество повторных попыток (retries).

client = TitanGPT(
    api_key="...",
    base_url="https://api.titangpt.ru",  # По умолчанию
    timeout=60,                          # Таймаут в секундах
    max_retries=3                        # Количество попыток при ошибках сети
)

🔗 Ссылки и Поддержка

Если у вас есть вопросы или нужна помощь, присоединяйтесь к нашему Telegram каналу.


License

MIT License.

Developed for TitanGPT API.

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

titangpt-0.2.0.tar.gz (14.4 kB view details)

Uploaded Source

Built Distribution

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

titangpt-0.2.0-py3-none-any.whl (13.4 kB view details)

Uploaded Python 3

File details

Details for the file titangpt-0.2.0.tar.gz.

File metadata

  • Download URL: titangpt-0.2.0.tar.gz
  • Upload date:
  • Size: 14.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for titangpt-0.2.0.tar.gz
Algorithm Hash digest
SHA256 ac28bd96804ff19bf66f57ee48cc72872e4e8f293d5bc3b255c383dfd5471590
MD5 f03b6f349356c039f0c265e27448e684
BLAKE2b-256 fbabe8a0078303b27cbf305d3f0cc8bd417dc16108fe857924873519e7ddd86a

See more details on using hashes here.

File details

Details for the file titangpt-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: titangpt-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 13.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for titangpt-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5affd090b750b6ace97ce452920379377218515b6f831279e9535bab339d21f9
MD5 0123e16919de4c570247f49e35a7baf5
BLAKE2b-256 64512f46d294ee9c823bfc41ba0751e8d0a3bd2c2e98a487aa0b65b6a641386c

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