Python SDK
Используйте официальный OpenAI Python SDK с GonkaGate. Специальный SDK не требуется.
Установка
Установите официальный OpenAI Python SDK:
terminal
pip install openaiНастройка
Настройте клиент для использования API GonkaGate:
config.py
from openai import OpenAI
client = OpenAI(
base_url="https://api.gonkagate.com/v1",
api_key="gp-your-api-key" # Get from dashboard
)Базовое использование
Выполните первый запрос к чату:
basic_usage.py
from openai import OpenAI
client = OpenAI(
base_url="https://api.gonkagate.com/v1",
api_key="gp-your-api-key"
)
response = client.chat.completions.create(
model="Qwen/Qwen3-235B-A22B-Instruct-2507-FP8",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"}
],
temperature=0.7,
max_tokens=1000
)
print(response.choices[0].message.content)Потоковая передача
Потоковые ответы для вывода в реальном времени:
streaming.py
from openai import OpenAI
client = OpenAI(
base_url="https://api.gonkagate.com/v1",
api_key="gp-your-api-key"
)
stream = client.chat.completions.create(
model="Qwen/Qwen3-235B-A22B-Instruct-2507-FP8",
messages=[{"role": "user", "content": "Write a poem about AI"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
# Final chunk contains usage
if chunk.usage:
print(f"\n\nCost: ${chunk.usage.total_cost_usd:.6f}")Отслеживание стоимости
Отслеживайте использование и стоимость каждого запроса:
Дополнительные поля usage — GonkaGate добавляет base_cost_usd, platform_fee_usd и total_cost_usd к стандартному объекту usage.
cost_tracking.py
response = client.chat.completions.create(
model="Qwen/Qwen3-235B-A22B-Instruct-2507-FP8",
messages=[{"role": "user", "content": "Hello!"}]
)
# Access cost information
usage = response.usage
print(f"Prompt tokens: {usage.prompt_tokens}")
print(f"Completion tokens: {usage.completion_tokens}")
print(f"Total tokens: {usage.total_tokens}")
print(f"Base cost: ${usage.base_cost_usd:.6f}")
print(f"Platform fee: ${usage.platform_fee_usd:.6f}")
print(f"Total cost: ${usage.total_cost_usd:.6f}")Обработка ошибок
Корректно обрабатывайте типичные ошибки API:
error_handling.py
from openai import OpenAI, APIError, RateLimitError, AuthenticationError
client = OpenAI(
base_url="https://api.gonkagate.com/v1",
api_key="gp-your-api-key"
)
try:
response = client.chat.completions.create(
model="Qwen/Qwen3-235B-A22B-Instruct-2507-FP8",
messages=[{"role": "user", "content": "Hello!"}]
)
except AuthenticationError as e:
print(f"Invalid API key: {e}")
except RateLimitError as e:
print(f"Rate limited. Retry after: {e.response.headers.get('Retry-After')} seconds")
except APIError as e:
if e.status_code == 402:
print("Insufficient balance. Please add funds.")
else:
print(f"API error: {e}")Асинхронное использование
Используйте async/await для неблокирующих запросов:
async_usage.py
import asyncio
from openai import AsyncOpenAI
async def main():
client = AsyncOpenAI(
base_url="https://api.gonkagate.com/v1",
api_key="gp-your-api-key"
)
response = await client.chat.completions.create(
model="Qwen/Qwen3-235B-A22B-Instruct-2507-FP8",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
asyncio.run(main())