Skip to main content

Official Python client for TitanGPT API

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.1,
    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.1",
        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.1", 
    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.1",
    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.1",
        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.1", 
    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.1.8.tar.gz (12.6 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.1.8-py3-none-any.whl (10.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for titangpt-0.1.8.tar.gz
Algorithm Hash digest
SHA256 75f8eb06bffd7d7cd1a792c58ace42abdbc4cec0fe291674b8fb0e6f46134fb2
MD5 5a598e13fcf081f77bdce7ca04ae8af6
BLAKE2b-256 3f8c9aac09432505095ce5fd5acb971eff9b39d571fdf743deadb773c924b03b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: titangpt-0.1.8-py3-none-any.whl
  • Upload date:
  • Size: 10.9 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.1.8-py3-none-any.whl
Algorithm Hash digest
SHA256 83d3b24ae5ba029b21ecd381ada11b65118470d785f6bed4404d132146ac3d2a
MD5 eed5545c42d39485648d6bc1a5a76b0a
BLAKE2b-256 f2ef3f4edee9cb85243ff23720aadbc05ac3cb35bd2758345507c26b7798694f

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