User: Формат forgetapi изменился, вот forgetapi который сейчас
import requests
import logging
import json  # Добавляем импорт json для сериализации

logger = logging.getLogger(__name__)

class ForgetAPI:
    def __init__(self):
        self.base_url = "https://forgetapi.ru/v1"
        self.headers = {
            "Authorization": "Bearer XuliN5MZY5zWDry2aXap7N0JewQJSfVG"  # Замените на ваш реальный API ключ
        }
        self.session = requests.Session()
        self.session.headers.update(self.headers)

    def send_message(self, model: str, messages: list, temperature: float = 0.7, max_tokens: int = 10000, files=None):
        url = f"{self.base_url}/chat/completions"

        # Сериализуем список сообщений в строку JSON
        messages_str = json.dumps(messages, ensure_ascii=False)

        # Подготавливаем данные для отправки в формате multipart/form-data
        multipart_data = {
            'model': (None, model),
            'messages': (None, messages_str),
            'temperature': (None, str(temperature)),
            'max_tokens': (None, str(max_tokens))
        }

        # Если есть файлы, добавляем их
        if files:
            if isinstance(files, dict):
                for key, file_path in files.items():
                    multipart_data[key] = (file_path, open(file_path, 'rb'))
            elif isinstance(files, list):
                for idx, file_path in enumerate(files):
                    multipart_data[f'file_{idx}'] = (file_path, open(file_path, 'rb'))
            else:
                multipart_data['files'] = (files, open(files, 'rb'))

        try:
            response = self.session.post(url, files=multipart_data)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            logger.error(f"ForgetAPI request error: {e}")
            return None
        finally:
            # Закрываем открытые файлы, если они есть
            if files:
                for key, file_info in multipart_data.items():
                    if isinstance(file_info, tuple) and hasattr(file_info[1], 'close'):
                        file_info[1].close()
вот на такой изменился
import openai

# Установка API ключа
openai.api_key = 'YOUR_KEY'
openai.api_base = "https://forgetapi.ru/v1"


response = openai.ChatCompletion.create(
            model="claude-3.5-sonnet",
            messages = [{"role": "user", "content": "Ку."}]
        )


# Пример использования
if __name__ == "__main__":
    print(response.choices[0].message.content)
вот как forget используется в моем коде bot.py
elif api_name == 'forget':
                # Используем ForgetAPI
                conversation.append({"role": "user", "content": text})
                conversation = conversation[-10:]  # Ограничиваем контекст

                # Отправка запроса к ForgetAPI
                response = await asyncio.to_thread(
                    api_client.send_message,
                    model=model,
                    messages=conversation,
                    temperature=0.7,
                    max_tokens=10000
                )

                if not response:
                    await message.reply("Получен некорректный ответ от API")
                    return

                # Извлечение ответа ассистента
                choices = response.get('choices')
                if not choices:
                    await message.reply("Не удалось получить ответ от ассистента")
                    return

                assistant_message = choices[0].get('message')
                if not assistant_message:
                    await message.reply("Не удалось получить ответ от ассистента")
                    return

                content = assistant_message.get('content')
                if content:
                    conversation.append({"role": "assistant", "content": content})
                    self.conversations[user_id] = conversation

                    # Считаем количество токенов и обновляем баланс
                    tokens_used = len(content)
Assistant: It looks like the `forgetapi` has updated its interface to be compatible with the OpenAI API format. This means you can now use the `openai` Python library to interact with it. Below, I'll help you update your code to work with the new API format.

---

**Step 1: Update Your API Client Configuration**

Since `forgetapi` is now compatible with the OpenAI API format, you can remove your custom `ForgetAPI` class and use the `openai` library directly. Here's how to set it up:

```python
import openai

# Set your forgetapi API key and base URL
openai.api_key = 'YOUR_FORGETAPI_KEY'  # Replace with your actual API key
openai.api_base = 'https://forgetapi.ru/v1'
```

---

**Step 2: Modify Your `bot.py` Code**

Update the `elif api_name == 'forget':` block in your `bot.py` to use the `openai` library. Here's how you can modify it:

```python
import asyncio
import openai

# (Make sure openai.api_key and openai.api_base have been set as shown above)

...

elif api_name == 'forget':
    # Append the user's message to the conversation
    conversation.append({"role": "user", "content": text})
    conversation = conversation[-10:]  # Limit the context to the last 10 messages

    # Prepare the parameters for the API call
    model_name = model  # e.g., "claude-3.5-sonnet"
    temperature = 0.7
    max_tokens = 10000

    # Make the API call in an asynchronous thread
    try:
        response = await asyncio.to_thread(
            openai.ChatCompletion.create,
            model=model_name,
            messages=conversation,
            temperature=temperature,
            max_tokens=max_tokens,
        )
    except Exception as e:
        await message.reply(f"Ошибка при запросе к API: {e}")
        return

    # Extract the assistant's reply from the response
    if not response or 'choices' not in response or not response.choices:
        await message.reply("Не удалось получить ответ от ассистента")
        return

    assistant_message = response.choices[0].message
    if not assistant_message or 'content' not in assistant_message:
        await message.reply("Не удалось получить ответ от ассистента")
        return

    content = assistant_message['content']
    if content:
        # Append the assistant's reply to the conversation
        conversation.append({"role": "assistant", "content": content})
        self.conversations[user_id] = conversation

        # Optionally, count tokens used (if needed)
        # tokens_used = response['usage']['total_tokens']  # Uncomment if 'usage' is provided

        # Send the assistant's reply to the user
        await message.reply(content)
```

---

**Notes and Explanations:**

1. **Asynchronous Execution:**
   - Since `openai.ChatCompletion.create` is a synchronous function, we're using `await asyncio.to_thread` to run it in an asynchronous context without blocking the event loop.

2. **Handling the Response:**
   - The response from `openai.ChatCompletion.create` is an object with attributes, not a dictionary. Adjust your code to access attributes instead of dictionary keys:
     - Use `response.choices` instead of `response.get('choices')`.
     - Access the message content with `response.choices[0].message.content`.

3. **Error Handling:**
   - Wrap the API call in a try-except block to catch any exceptions and inform the user accordingly.

4. **Token Counting (Optional):**
   - If you need to track the number of tokens used, check if `response` includes a `'usage'` attribute with token counts.
   - You can uncomment the `tokens_used` line if `forgetapi` provides usage information.

5. **Updating Conversation History:**
   - Ensure that both user and assistant messages are appended to the `conversation` list with the correct roles (`"user"` and `"assistant"`).

6. **Sending the Reply:**
   - Use `await message.reply(content)` to send the assistant's reply back to the user.

---

**Example of the Modified Code Block:**

```python
elif api_name == 'forget':
    # Append the user's message to the conversation
    conversation.append({"role": "user", "content": text})
    conversation = conversation[-10:]  # Limit the context

    # Prepare API call parameters
    model_name = model  # e.g., "claude-3.5-sonnet"
    temperature = 0.7
    max_tokens = 10000

    # Asynchronously call the API
    try:
        response = await asyncio.to_thread(
            openai.ChatCompletion.create,
            model=model_name,
            messages=conversation,
            temperature=temperature,
            max_tokens=max_tokens,
        )
    except Exception as e:
        await message.reply(f"API request error: {e}")
        return

    # Check if the response is valid
    if not response or not response.choices:
        await message.reply("No response from assistant")
        return

    assistant_message = response.choices[0].message
    content = assistant_message.get('content') if isinstance(assistant_message, dict) else getattr(assistant_message, 'content', None)

    if content:
        # Append assistant's response to the conversation
        conversation.append({"role": "assistant", "content": content})
        self.conversations[user_id] = conversation

        # Optionally, you can count tokens used (if provided in the response)
        # tokens_used = response.usage.total_tokens  # Uncomment if 'usage' is provided

        # Send the assistant's reply to the user
        await message.reply(content)
    else:
        await message.reply("Assistant did not provide a valid response")
```

---

**Additional Tips:**

- **Initialize the OpenAI Client Once:**
  - Ensure that `openai.api_key` and `openai.api_base` are set before you make any API calls. You might want to set them at the start of your bot script.

- **Handle Model Names Appropriately:**
  - Verify that the model names you're using (e.g., `"claude-3.5-sonnet"`) are valid and supported by `forgetapi`.

- **File Uploads (if needed):**
  - If your original `send_message` function handled file uploads, you might need to adjust the code to accommodate that, as the standard OpenAI ChatCompletion API does not support file uploads directly. You might need to handle files separately or check `forgetapi`'s documentation for how to include files.

- **Check the `forgetapi` Documentation:**
  - Since `forgetapi` aims to be compatible with the OpenAI API, most of the OpenAI documentation should apply. However, there might be specific differences, so it's a good idea to review `forgetapi`'s documentation for any nuances.

---

By making these changes, your `bot.py` should now be compatible with the updated `forgetapi`. This will allow your bot to interact with the API using the new format.

**Remember to replace `'YOUR_FORGETAPI_KEY'` with your actual API key** and verify that the rest of your code aligns with these changes.

Let me know if you have any questions or need further assistance!
User: current_tokens = self.get_user_tokens(user_id)
                    if current_tokens != -1:
                        if tokens_used > current_tokens:
                            await message.reply("У вас недостаточно токенов для этого ответа.")
                            return
                        self.set_user_tokens(user_id, current_tokens - tokens_used)

                    # Отправка ответа пользователю
                    await send_long_message(message, content)
                else:
                    await message.reply("Не удалось получить текст ответа")
            else:
                await message.reply("Неизвестная модель или API. Пожалуйста, выберите модель из списка.")
                return

        except Exception as e:
            logger.error(f"Ошибка в process_message: {str(e)}", exc_info=True)
            await message.reply(f"Произошла ошибка при обработке вашего сообщения: {str(e)}")
        finally:
            if user_id in self.waiting_messages:
                await self.waiting_messages[user_id].delete()
                del self.waiting_messages[user_id]