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.7.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.7-py3-none-any.whl (10.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: titangpt-0.1.7.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.7.tar.gz
Algorithm Hash digest
SHA256 30cafd4e49e981bba8d6f19d47416b6ae3eb812696d3f7abbcd61165da29e88d
MD5 989a15293bfaba4484bf5149c5c4d9ed
BLAKE2b-256 b32b6c0273e44381950a8399d36505ce1dcb5871195234181d8ae2516f24e45c

See more details on using hashes here.

File details

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

File metadata

  • Download URL: titangpt-0.1.7-py3-none-any.whl
  • Upload date:
  • Size: 10.8 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.7-py3-none-any.whl
Algorithm Hash digest
SHA256 4b1b5997783e5ee249a516b6a0d410c9221648d3ac00d0ea2d4102c6eeec98ba
MD5 ea6e51da605fab24bd5672c1ac037e67
BLAKE2b-256 1ce2554bf32da957fa75868423eb6fa322827f3d901a255dd561e6bf17d0d22e

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