TESTBT / src /qwen_api /resources /new_chat.py
LucaR84's picture
Added app
0eb03b6
import requests
import aiohttp
import time
from typing import Optional, List
from ..core.types.chat_model import ChatModel
from ..core.exceptions import QwenAPIError, RateLimitError
from ..core.types.endpoint_api import EndpointAPI
class NewChat:
def __init__(self, client):
self._client = client
def create(
self,
title: str = "New Chat",
models: Optional[List[ChatModel]] = None,
chat_mode: str = "normal",
chat_type: str = "t2t",
) -> str:
"""
Create a new chat session and return the chat ID.
"""
chat_mode = "local"
payload = {
"title": title,
"models": models,
"chat_mode": chat_mode,
"chat_type": chat_type,
"timestamp": int(time.time() * 1000)
}
headers = self._client._build_headers()
headers["Content-Type"] = "application/json"
response = requests.post(
url=self._client.base_url + EndpointAPI.new_chat,
headers=headers,
json=payload,
timeout=self._client.timeout,
)
if not response.ok:
try:
error_text = response.json()
except Exception:
error_text = response.text
self._client.logger.error(f"New chat API error: {response.status_code} {error_text}")
if response.status_code == 429:
raise RateLimitError("Too many requests")
raise QwenAPIError(f"New chat failed: {response.status_code} {error_text}")
try:
data = response.json()
if not data.get("success"):
raise QwenAPIError(f"New chat not successful: {data}")
return data["data"]["id"]
except (KeyError, TypeError) as e:
self._client.logger.error(f"Invalid new_chat response format: {e}")
raise QwenAPIError("Unexpected response format from new_chat endpoint")
async def acreate(
self,
title: str = "New Chat",
models: Optional[List[ChatModel]] = None,
chat_mode: str = "normal",
chat_type: str = "t2t",
) -> str:
"""
Async version of new_chat.
"""
if models is None:
models = ["qwen-max-latest"]
payload = {
"title": title,
"models": models,
"chat_mode": chat_mode,
"chat_type": chat_type,
"timestamp": int(time.time() * 1000),
}
headers = self._client._build_headers()
headers["Content-Type"] = "application/json"
async with aiohttp.ClientSession() as session:
response = await session.post(
url=self._client.base_url + EndpointAPI.new_chat,
headers=headers,
json=payload,
timeout=aiohttp.ClientTimeout(total=self._client.timeout),
)
if not response.ok:
error_text = await response.text()
self._client.logger.error(f"New chat API error: {response.status} {error_text}")
if response.status == 429:
raise RateLimitError("Too many requests")
raise QwenAPIError(f"New chat failed: {response.status} {error_text}")
try:
data = await response.json()
if not data.get("success"):
raise QwenAPIError(f"New chat not successful: {data}")
return data["data"]["id"]
except (KeyError, TypeError, ValueError) as e:
self._client.logger.error(f"Invalid anew_chat response format: {e}")
raise QwenAPIError("Unexpected response format from new_chat endpoint")