2023-09-03 08:26:26 +00:00
|
|
|
from __future__ import annotations
|
2024-01-26 06:54:13 +00:00
|
|
|
|
2024-01-14 06:45:41 +00:00
|
|
|
import asyncio
|
|
|
|
import uuid
|
|
|
|
import json
|
2024-02-28 06:36:43 +00:00
|
|
|
import base64
|
2024-03-08 10:01:38 +00:00
|
|
|
import time
|
2024-02-28 06:36:43 +00:00
|
|
|
from aiohttp import ClientWebSocketResponse
|
2024-03-26 05:42:47 +00:00
|
|
|
from copy import copy
|
2023-09-03 08:26:26 +00:00
|
|
|
|
2024-03-14 12:53:57 +00:00
|
|
|
try:
|
|
|
|
import webview
|
|
|
|
has_webview = True
|
|
|
|
except ImportError:
|
|
|
|
has_webview = False
|
|
|
|
|
2024-01-26 06:54:13 +00:00
|
|
|
try:
|
|
|
|
from selenium.webdriver.common.by import By
|
|
|
|
from selenium.webdriver.support.ui import WebDriverWait
|
|
|
|
from selenium.webdriver.support import expected_conditions as EC
|
|
|
|
except ImportError:
|
2024-01-26 11:49:52 +00:00
|
|
|
pass
|
2024-01-01 00:51:49 +00:00
|
|
|
|
2024-01-23 18:44:48 +00:00
|
|
|
from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
|
2024-02-26 22:41:06 +00:00
|
|
|
from ...webdriver import get_browser
|
2024-04-18 18:18:51 +00:00
|
|
|
from ...typing import AsyncResult, Messages, Cookies, ImageType, AsyncIterator
|
2024-04-28 20:19:51 +00:00
|
|
|
from ...requests import get_args_from_browser, raise_for_status
|
2024-02-23 10:33:38 +00:00
|
|
|
from ...requests.aiohttp import StreamSession
|
2024-05-18 21:13:57 +00:00
|
|
|
from ...image import ImageResponse, ImageRequest, to_image, to_bytes, is_accepted_format
|
2024-04-05 19:00:35 +00:00
|
|
|
from ...errors import MissingAuthError, ResponseError
|
2024-03-26 05:42:47 +00:00
|
|
|
from ...providers.conversation import BaseConversation
|
2024-04-21 13:15:55 +00:00
|
|
|
from ..helper import format_cookies
|
2024-04-05 19:00:35 +00:00
|
|
|
from ..openai.har_file import getArkoseAndAccessToken, NoValidHarFileError
|
2024-04-28 20:19:51 +00:00
|
|
|
from ..openai.proofofwork import generate_proof_token
|
2024-02-23 10:33:38 +00:00
|
|
|
from ... import debug
|
2023-09-03 08:26:26 +00:00
|
|
|
|
2024-04-28 20:19:51 +00:00
|
|
|
DEFAULT_HEADERS = {
|
|
|
|
"accept": "*/*",
|
|
|
|
"accept-encoding": "gzip, deflate, br, zstd",
|
|
|
|
"accept-language": "en-US,en;q=0.5",
|
2024-05-15 00:27:51 +00:00
|
|
|
"referer": "https://chatgpt.com/",
|
2024-04-28 20:19:51 +00:00
|
|
|
"sec-ch-ua": "\"Brave\";v=\"123\", \"Not:A-Brand\";v=\"8\", \"Chromium\";v=\"123\"",
|
|
|
|
"sec-ch-ua-mobile": "?0",
|
|
|
|
"sec-ch-ua-platform": "\"Windows\"",
|
|
|
|
"sec-fetch-dest": "empty",
|
|
|
|
"sec-fetch-mode": "cors",
|
|
|
|
"sec-fetch-site": "same-origin",
|
|
|
|
"sec-gpc": "1",
|
|
|
|
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
|
|
|
|
}
|
|
|
|
|
2024-01-23 18:44:48 +00:00
|
|
|
class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin):
|
2024-01-14 06:45:41 +00:00
|
|
|
"""A class for creating and managing conversations with OpenAI chat service"""
|
2024-03-09 02:10:59 +00:00
|
|
|
|
2024-04-18 18:18:51 +00:00
|
|
|
label = "OpenAI ChatGPT"
|
2024-05-15 00:27:51 +00:00
|
|
|
url = "https://chatgpt.com"
|
2024-01-14 06:45:41 +00:00
|
|
|
working = True
|
2023-08-25 04:41:32 +00:00
|
|
|
supports_gpt_35_turbo = True
|
2024-01-14 06:45:41 +00:00
|
|
|
supports_gpt_4 = True
|
2024-02-26 22:41:06 +00:00
|
|
|
supports_message_history = True
|
2024-02-28 06:36:43 +00:00
|
|
|
supports_system_message = True
|
2024-01-23 18:44:48 +00:00
|
|
|
default_model = None
|
2024-05-15 00:27:51 +00:00
|
|
|
default_vision_model = "gpt-4o"
|
2024-05-18 05:37:37 +00:00
|
|
|
models = ["gpt-3.5-turbo", "gpt-4", "gpt-4-gizmo", "gpt-4o", "auto"]
|
2024-04-21 13:15:55 +00:00
|
|
|
model_aliases = {
|
|
|
|
"text-davinci-002-render-sha": "gpt-3.5-turbo",
|
|
|
|
"": "gpt-3.5-turbo",
|
|
|
|
"gpt-4-turbo-preview": "gpt-4",
|
|
|
|
"dall-e": "gpt-4",
|
|
|
|
}
|
2024-02-28 06:36:43 +00:00
|
|
|
_api_key: str = None
|
|
|
|
_headers: dict = None
|
|
|
|
_cookies: Cookies = None
|
2024-03-08 10:01:38 +00:00
|
|
|
_expires: int = None
|
2023-11-19 04:36:04 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
async def create(
|
|
|
|
cls,
|
|
|
|
prompt: str = None,
|
|
|
|
model: str = "",
|
|
|
|
messages: Messages = [],
|
2024-04-05 19:00:35 +00:00
|
|
|
action: str = "next",
|
2023-11-19 04:36:04 +00:00
|
|
|
**kwargs
|
|
|
|
) -> Response:
|
2024-01-14 14:35:58 +00:00
|
|
|
"""
|
|
|
|
Create a new conversation or continue an existing one
|
2024-01-14 06:45:41 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
prompt: The user input to start or continue the conversation
|
|
|
|
model: The name of the model to use for generating responses
|
|
|
|
messages: The list of previous messages in the conversation
|
|
|
|
history_disabled: A flag indicating if the history and training should be disabled
|
|
|
|
action: The type of action to perform, either "next", "continue", or "variant"
|
|
|
|
conversation_id: The ID of the existing conversation, if any
|
|
|
|
parent_id: The ID of the parent message, if any
|
|
|
|
image: The image to include in the user input, if any
|
|
|
|
**kwargs: Additional keyword arguments to pass to the generator
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A Response object that contains the generator, action, messages, and options
|
|
|
|
"""
|
|
|
|
# Add the user input to the messages list
|
2024-03-09 02:10:59 +00:00
|
|
|
if prompt is not None:
|
2023-11-20 13:00:40 +00:00
|
|
|
messages.append({
|
|
|
|
"role": "user",
|
|
|
|
"content": prompt
|
|
|
|
})
|
2023-11-19 04:36:04 +00:00
|
|
|
generator = cls.create_async_generator(
|
|
|
|
model,
|
|
|
|
messages,
|
2024-03-26 05:42:47 +00:00
|
|
|
return_conversation=True,
|
2023-11-19 04:36:04 +00:00
|
|
|
**kwargs
|
|
|
|
)
|
|
|
|
return Response(
|
|
|
|
generator,
|
|
|
|
action,
|
|
|
|
messages,
|
|
|
|
kwargs
|
|
|
|
)
|
2024-03-09 02:10:59 +00:00
|
|
|
|
2024-01-13 14:37:36 +00:00
|
|
|
@classmethod
|
2024-01-23 18:44:48 +00:00
|
|
|
async def upload_image(
|
2024-01-13 14:37:36 +00:00
|
|
|
cls,
|
|
|
|
session: StreamSession,
|
|
|
|
headers: dict,
|
2024-02-08 21:02:52 +00:00
|
|
|
image: ImageType,
|
|
|
|
image_name: str = None
|
2024-01-26 06:54:13 +00:00
|
|
|
) -> ImageRequest:
|
2024-01-14 14:35:58 +00:00
|
|
|
"""
|
|
|
|
Upload an image to the service and get the download URL
|
2024-01-14 06:45:41 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
session: The StreamSession object to use for requests
|
|
|
|
headers: The headers to include in the requests
|
|
|
|
image: The image to upload, either a PIL Image object or a bytes object
|
|
|
|
|
|
|
|
Returns:
|
2024-01-26 06:54:13 +00:00
|
|
|
An ImageRequest object that contains the download URL, file name, and other data
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
# Convert the image to a PIL Image object and get the extension
|
2024-01-13 14:37:36 +00:00
|
|
|
data_bytes = to_bytes(image)
|
2024-05-18 21:13:57 +00:00
|
|
|
image = to_image(data_bytes)
|
|
|
|
extension = image.format.lower()
|
2024-01-13 14:37:36 +00:00
|
|
|
data = {
|
2024-05-18 21:13:57 +00:00
|
|
|
"file_name": "" if image_name is None else image_name,
|
2024-01-13 14:37:36 +00:00
|
|
|
"file_size": len(data_bytes),
|
|
|
|
"use_case": "multimodal"
|
|
|
|
}
|
2024-01-14 06:45:41 +00:00
|
|
|
# Post the image data to the service and get the image data
|
2024-01-13 14:37:36 +00:00
|
|
|
async with session.post(f"{cls.url}/backend-api/files", json=data, headers=headers) as response:
|
2024-05-18 21:13:57 +00:00
|
|
|
cls._update_request_args(session)
|
2024-03-14 12:53:57 +00:00
|
|
|
await raise_for_status(response)
|
2024-01-13 14:37:36 +00:00
|
|
|
image_data = {
|
|
|
|
**data,
|
|
|
|
**await response.json(),
|
2024-05-18 21:13:57 +00:00
|
|
|
"mime_type": is_accepted_format(data_bytes),
|
2024-01-13 14:37:36 +00:00
|
|
|
"extension": extension,
|
|
|
|
"height": image.height,
|
|
|
|
"width": image.width
|
|
|
|
}
|
2024-01-14 06:45:41 +00:00
|
|
|
# Put the image bytes to the upload URL and check the status
|
2024-01-13 14:37:36 +00:00
|
|
|
async with session.put(
|
|
|
|
image_data["upload_url"],
|
|
|
|
data=data_bytes,
|
|
|
|
headers={
|
|
|
|
"Content-Type": image_data["mime_type"],
|
|
|
|
"x-ms-blob-type": "BlockBlob"
|
|
|
|
}
|
|
|
|
) as response:
|
2024-03-14 12:53:57 +00:00
|
|
|
await raise_for_status(response)
|
2024-01-14 06:45:41 +00:00
|
|
|
# Post the file ID to the service and get the download URL
|
2024-01-13 14:37:36 +00:00
|
|
|
async with session.post(
|
|
|
|
f"{cls.url}/backend-api/files/{image_data['file_id']}/uploaded",
|
|
|
|
json={},
|
|
|
|
headers=headers
|
|
|
|
) as response:
|
2024-03-14 12:53:57 +00:00
|
|
|
cls._update_request_args(session)
|
|
|
|
await raise_for_status(response)
|
2024-01-29 17:14:46 +00:00
|
|
|
image_data["download_url"] = (await response.json())["download_url"]
|
|
|
|
return ImageRequest(image_data)
|
2024-03-09 02:10:59 +00:00
|
|
|
|
2024-01-13 14:37:36 +00:00
|
|
|
@classmethod
|
2024-01-23 18:44:48 +00:00
|
|
|
async def get_default_model(cls, session: StreamSession, headers: dict):
|
2024-01-14 14:35:58 +00:00
|
|
|
"""
|
|
|
|
Get the default model name from the service
|
2024-01-14 06:45:41 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
session: The StreamSession object to use for requests
|
|
|
|
headers: The headers to include in the requests
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The default model name as a string
|
|
|
|
"""
|
2024-01-23 18:44:48 +00:00
|
|
|
if not cls.default_model:
|
2024-04-05 19:00:35 +00:00
|
|
|
url = f"{cls.url}/backend-anon/models" if cls._api_key is None else f"{cls.url}/backend-api/models"
|
|
|
|
async with session.get(url, headers=headers) as response:
|
2024-02-26 22:41:06 +00:00
|
|
|
cls._update_request_args(session)
|
2024-04-05 19:00:35 +00:00
|
|
|
if response.status == 401:
|
|
|
|
raise MissingAuthError('Add a "api_key" or a .har file' if cls._api_key is None else "Invalid api key")
|
2024-03-14 12:53:57 +00:00
|
|
|
await raise_for_status(response)
|
2024-01-23 18:44:48 +00:00
|
|
|
data = await response.json()
|
|
|
|
if "categories" in data:
|
|
|
|
cls.default_model = data["categories"][-1]["default_model"]
|
2024-02-23 10:33:38 +00:00
|
|
|
return cls.default_model
|
2024-04-05 19:00:35 +00:00
|
|
|
raise ResponseError(data)
|
2024-01-23 18:44:48 +00:00
|
|
|
return cls.default_model
|
2024-03-09 02:10:59 +00:00
|
|
|
|
2024-01-13 14:37:36 +00:00
|
|
|
@classmethod
|
2024-02-26 22:41:06 +00:00
|
|
|
def create_messages(cls, messages: Messages, image_request: ImageRequest = None):
|
2024-01-14 14:35:58 +00:00
|
|
|
"""
|
|
|
|
Create a list of messages for the user input
|
2024-01-14 06:45:41 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
prompt: The user input as a string
|
|
|
|
image_response: The image response object, if any
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A list of messages with the user input and the image, if any
|
|
|
|
"""
|
2024-02-26 22:41:06 +00:00
|
|
|
# Create a message object with the user role and the content
|
|
|
|
messages = [{
|
|
|
|
"id": str(uuid.uuid4()),
|
|
|
|
"author": {"role": message["role"]},
|
|
|
|
"content": {"content_type": "text", "parts": [message["content"]]},
|
|
|
|
} for message in messages]
|
|
|
|
|
2024-01-14 06:45:41 +00:00
|
|
|
# Check if there is an image response
|
2024-03-26 05:42:47 +00:00
|
|
|
if image_request is not None:
|
2024-02-26 22:41:06 +00:00
|
|
|
# Change content in last user message
|
|
|
|
messages[-1]["content"] = {
|
2024-01-13 14:37:36 +00:00
|
|
|
"content_type": "multimodal_text",
|
|
|
|
"parts": [{
|
2024-01-29 17:14:46 +00:00
|
|
|
"asset_pointer": f"file-service://{image_request.get('file_id')}",
|
|
|
|
"height": image_request.get("height"),
|
|
|
|
"size_bytes": image_request.get("file_size"),
|
|
|
|
"width": image_request.get("width"),
|
2024-02-26 22:41:06 +00:00
|
|
|
}, messages[-1]["content"]["parts"][0]]
|
2024-01-13 14:37:36 +00:00
|
|
|
}
|
2024-01-14 06:45:41 +00:00
|
|
|
# Add the metadata object with the attachments
|
2024-02-26 22:41:06 +00:00
|
|
|
messages[-1]["metadata"] = {
|
2024-01-13 14:37:36 +00:00
|
|
|
"attachments": [{
|
2024-01-29 17:14:46 +00:00
|
|
|
"height": image_request.get("height"),
|
|
|
|
"id": image_request.get("file_id"),
|
|
|
|
"mimeType": image_request.get("mime_type"),
|
|
|
|
"name": image_request.get("file_name"),
|
|
|
|
"size": image_request.get("file_size"),
|
|
|
|
"width": image_request.get("width"),
|
2024-01-13 14:37:36 +00:00
|
|
|
}]
|
|
|
|
}
|
|
|
|
return messages
|
2024-02-26 22:41:06 +00:00
|
|
|
|
2024-01-13 14:37:36 +00:00
|
|
|
@classmethod
|
2024-01-23 18:44:48 +00:00
|
|
|
async def get_generated_image(cls, session: StreamSession, headers: dict, line: dict) -> ImageResponse:
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Retrieves the image response based on the message content.
|
|
|
|
|
2024-01-14 14:35:58 +00:00
|
|
|
This method processes the message content to extract image information and retrieves the
|
|
|
|
corresponding image from the backend API. It then returns an ImageResponse object containing
|
|
|
|
the image URL and the prompt used to generate the image.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
session (StreamSession): The StreamSession object used for making HTTP requests.
|
|
|
|
headers (dict): HTTP headers to be used for the request.
|
|
|
|
line (dict): A dictionary representing the line of response that contains image information.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
ImageResponse: An object containing the image URL and the prompt, or None if no image is found.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
RuntimeError: If there'san error in downloading the image, including issues with the HTTP request or response.
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
if "parts" not in line["message"]["content"]:
|
|
|
|
return
|
|
|
|
first_part = line["message"]["content"]["parts"][0]
|
|
|
|
if "asset_pointer" not in first_part or "metadata" not in first_part:
|
|
|
|
return
|
2024-05-18 21:13:57 +00:00
|
|
|
if first_part["metadata"] is None or first_part["metadata"]["dalle"] is None:
|
2024-02-23 10:33:38 +00:00
|
|
|
return
|
2024-01-14 06:45:41 +00:00
|
|
|
prompt = first_part["metadata"]["dalle"]["prompt"]
|
2024-02-23 10:33:38 +00:00
|
|
|
file_id = first_part["asset_pointer"].split("file-service://", 1)[1]
|
2024-01-14 06:45:41 +00:00
|
|
|
try:
|
|
|
|
async with session.get(f"{cls.url}/backend-api/files/{file_id}/download", headers=headers) as response:
|
2024-03-14 12:53:57 +00:00
|
|
|
cls._update_request_args(session)
|
|
|
|
await raise_for_status(response)
|
2024-01-14 06:45:41 +00:00
|
|
|
download_url = (await response.json())["download_url"]
|
|
|
|
return ImageResponse(download_url, prompt)
|
|
|
|
except Exception as e:
|
|
|
|
raise RuntimeError(f"Error in downloading image: {e}")
|
|
|
|
|
|
|
|
@classmethod
|
2024-01-23 18:44:48 +00:00
|
|
|
async def delete_conversation(cls, session: StreamSession, headers: dict, conversation_id: str):
|
2024-01-14 14:35:58 +00:00
|
|
|
"""
|
|
|
|
Deletes a conversation by setting its visibility to False.
|
|
|
|
|
|
|
|
This method sends an HTTP PATCH request to update the visibility of a conversation.
|
|
|
|
It's used to effectively delete a conversation from being accessed or displayed in the future.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
session (StreamSession): The StreamSession object used for making HTTP requests.
|
|
|
|
headers (dict): HTTP headers to be used for the request.
|
|
|
|
conversation_id (str): The unique identifier of the conversation to be deleted.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
HTTPError: If the HTTP request fails or returns an unsuccessful status code.
|
|
|
|
"""
|
2024-01-14 06:45:41 +00:00
|
|
|
async with session.patch(
|
|
|
|
f"{cls.url}/backend-api/conversation/{conversation_id}",
|
|
|
|
json={"is_visible": False},
|
|
|
|
headers=headers
|
|
|
|
) as response:
|
2024-03-14 12:53:57 +00:00
|
|
|
cls._update_request_args(session)
|
2024-02-28 08:59:31 +00:00
|
|
|
...
|
2023-08-25 04:41:32 +00:00
|
|
|
|
|
|
|
@classmethod
|
2023-10-03 20:12:56 +00:00
|
|
|
async def create_async_generator(
|
2023-08-25 04:41:32 +00:00
|
|
|
cls,
|
|
|
|
model: str,
|
2023-10-09 11:33:20 +00:00
|
|
|
messages: Messages,
|
2023-08-25 04:41:32 +00:00
|
|
|
proxy: str = None,
|
2024-04-18 18:18:51 +00:00
|
|
|
timeout: int = 180,
|
2024-02-23 10:33:38 +00:00
|
|
|
api_key: str = None,
|
2024-01-26 06:54:13 +00:00
|
|
|
cookies: Cookies = None,
|
2023-11-12 09:12:05 +00:00
|
|
|
auto_continue: bool = False,
|
2023-11-19 04:36:04 +00:00
|
|
|
history_disabled: bool = True,
|
|
|
|
action: str = "next",
|
|
|
|
conversation_id: str = None,
|
2024-03-26 05:42:47 +00:00
|
|
|
conversation: Conversation = None,
|
2023-11-19 04:36:04 +00:00
|
|
|
parent_id: str = None,
|
2024-01-13 14:37:36 +00:00
|
|
|
image: ImageType = None,
|
2024-02-28 06:36:43 +00:00
|
|
|
image_name: str = None,
|
2024-03-26 05:42:47 +00:00
|
|
|
return_conversation: bool = False,
|
2024-05-18 13:37:46 +00:00
|
|
|
max_retries: int = 3,
|
2023-10-09 11:33:20 +00:00
|
|
|
**kwargs
|
|
|
|
) -> AsyncResult:
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Create an asynchronous generator for the conversation.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
model (str): The model name.
|
|
|
|
messages (Messages): The list of previous messages.
|
|
|
|
proxy (str): Proxy to use for requests.
|
|
|
|
timeout (int): Timeout for requests.
|
2024-02-23 10:33:38 +00:00
|
|
|
api_key (str): Access token for authentication.
|
2024-01-14 06:45:41 +00:00
|
|
|
cookies (dict): Cookies to use for authentication.
|
|
|
|
auto_continue (bool): Flag to automatically continue the conversation.
|
|
|
|
history_disabled (bool): Flag to disable history and training.
|
|
|
|
action (str): Type of action ('next', 'continue', 'variant').
|
|
|
|
conversation_id (str): ID of the conversation.
|
2024-01-14 14:35:58 +00:00
|
|
|
parent_id (str): ID of the parent message.
|
2024-01-14 06:45:41 +00:00
|
|
|
image (ImageType): Image to include in the conversation.
|
2024-03-26 05:42:47 +00:00
|
|
|
return_conversation (bool): Flag to include response fields in the output.
|
2024-01-14 06:45:41 +00:00
|
|
|
**kwargs: Additional keyword arguments.
|
|
|
|
|
|
|
|
Yields:
|
|
|
|
AsyncResult: Asynchronous results from the generator.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
RuntimeError: If an error occurs during processing.
|
|
|
|
"""
|
2023-11-19 04:36:04 +00:00
|
|
|
async with StreamSession(
|
2024-04-21 20:39:00 +00:00
|
|
|
proxy=proxy,
|
2024-02-23 10:33:38 +00:00
|
|
|
impersonate="chrome",
|
2024-02-26 22:41:06 +00:00
|
|
|
timeout=timeout
|
2023-11-19 04:36:04 +00:00
|
|
|
) as session:
|
2024-04-07 14:02:49 +00:00
|
|
|
if cls._expires is not None and cls._expires < time.time():
|
|
|
|
cls._headers = cls._api_key = None
|
2024-03-25 20:06:51 +00:00
|
|
|
arkose_token = None
|
2024-05-18 05:37:37 +00:00
|
|
|
proofTokens = None
|
2024-05-18 21:13:57 +00:00
|
|
|
try:
|
|
|
|
arkose_token, api_key, cookies, headers, proofTokens = await getArkoseAndAccessToken(proxy)
|
|
|
|
cls._create_request_args(cookies, headers)
|
|
|
|
cls._set_api_key(api_key)
|
|
|
|
except NoValidHarFileError as e:
|
2024-04-18 18:18:51 +00:00
|
|
|
if cls._api_key is None and cls.needs_auth:
|
2024-05-18 21:13:57 +00:00
|
|
|
raise e
|
2024-05-19 03:09:55 +00:00
|
|
|
cls._create_request_args()
|
2024-05-18 21:13:57 +00:00
|
|
|
|
|
|
|
if cls.default_model is None:
|
2024-02-28 06:36:43 +00:00
|
|
|
cls.default_model = cls.get_model(await cls.get_default_model(session, cls._headers))
|
2024-02-26 22:41:06 +00:00
|
|
|
|
2024-01-13 14:37:36 +00:00
|
|
|
try:
|
2024-02-28 06:36:43 +00:00
|
|
|
image_request = await cls.upload_image(session, cls._headers, image, image_name) if image else None
|
2024-01-13 14:37:36 +00:00
|
|
|
except Exception as e:
|
2024-05-15 00:27:51 +00:00
|
|
|
image_request = None
|
2024-02-28 06:36:43 +00:00
|
|
|
if debug.logging:
|
|
|
|
print("OpenaiChat: Upload image failed")
|
|
|
|
print(f"{e.__class__.__name__}: {e}")
|
2024-02-26 22:41:06 +00:00
|
|
|
|
2024-04-21 20:39:00 +00:00
|
|
|
model = cls.get_model(model)
|
|
|
|
model = "text-davinci-002-render-sha" if model == "gpt-3.5-turbo" else model
|
2024-04-05 19:00:35 +00:00
|
|
|
if conversation is None:
|
|
|
|
conversation = Conversation(conversation_id, str(uuid.uuid4()) if parent_id is None else parent_id)
|
|
|
|
else:
|
|
|
|
conversation = copy(conversation)
|
|
|
|
if cls._api_key is None:
|
|
|
|
auto_continue = False
|
|
|
|
conversation.finish_reason = None
|
|
|
|
while conversation.finish_reason is None:
|
2024-05-18 13:37:46 +00:00
|
|
|
async with session.post(
|
|
|
|
f"{cls.url}/backend-anon/sentinel/chat-requirements"
|
|
|
|
if cls._api_key is None else
|
|
|
|
f"{cls.url}/backend-api/sentinel/chat-requirements",
|
|
|
|
json={"p": generate_proof_token(True, user_agent=cls._headers["user-agent"], proofTokens=proofTokens)},
|
|
|
|
headers=cls._headers
|
|
|
|
) as response:
|
|
|
|
cls._update_request_args(session)
|
|
|
|
await raise_for_status(response)
|
|
|
|
requirements = await response.json()
|
|
|
|
need_arkose = requirements.get("arkose", {}).get("required")
|
|
|
|
chat_token = requirements["token"]
|
|
|
|
|
|
|
|
if need_arkose and arkose_token is None:
|
|
|
|
arkose_token, api_key, cookies, headers, proofTokens = await getArkoseAndAccessToken(proxy)
|
|
|
|
cls._create_request_args(cookies, headers)
|
|
|
|
cls._set_api_key(api_key)
|
|
|
|
if arkose_token is None:
|
|
|
|
raise MissingAuthError("No arkose token found in .har file")
|
|
|
|
|
|
|
|
if "proofofwork" in requirements:
|
|
|
|
proofofwork = generate_proof_token(
|
|
|
|
**requirements["proofofwork"],
|
|
|
|
user_agent=cls._headers["user-agent"],
|
|
|
|
proofTokens=proofTokens
|
2024-05-19 03:09:55 +00:00
|
|
|
)
|
2024-05-18 13:37:46 +00:00
|
|
|
if debug.logging:
|
|
|
|
print(
|
|
|
|
'Arkose:', False if not need_arkose else arkose_token[:12]+"...",
|
|
|
|
'Proofofwork:', False if proofofwork is None else proofofwork[:12]+"...",
|
|
|
|
)
|
|
|
|
ws = None
|
|
|
|
if need_arkose:
|
2024-05-18 21:13:57 +00:00
|
|
|
async with session.post(f"{cls.url}/backend-api/register-websocket", headers=cls._headers) as response:
|
2024-05-18 13:37:46 +00:00
|
|
|
wss_url = (await response.json()).get("wss_url")
|
|
|
|
if wss_url:
|
|
|
|
ws = await session.ws_connect(wss_url)
|
2024-03-14 12:53:57 +00:00
|
|
|
websocket_request_id = str(uuid.uuid4())
|
2023-11-20 13:00:40 +00:00
|
|
|
data = {
|
|
|
|
"action": action,
|
2024-02-09 05:36:28 +00:00
|
|
|
"conversation_mode": {"kind": "primary_assistant"},
|
|
|
|
"force_paragen": False,
|
|
|
|
"force_rate_limit": False,
|
2024-04-05 19:00:35 +00:00
|
|
|
"conversation_id": conversation.conversation_id,
|
|
|
|
"parent_message_id": conversation.message_id,
|
2024-01-26 06:54:13 +00:00
|
|
|
"model": model,
|
2024-03-26 20:45:53 +00:00
|
|
|
"history_and_training_disabled": history_disabled and not auto_continue and not return_conversation,
|
2024-03-14 12:53:57 +00:00
|
|
|
"websocket_request_id": websocket_request_id
|
2023-11-20 13:00:40 +00:00
|
|
|
}
|
|
|
|
if action != "continue":
|
2024-02-28 06:36:43 +00:00
|
|
|
messages = messages if conversation_id is None else [messages[-1]]
|
2024-03-14 12:53:57 +00:00
|
|
|
data["messages"] = cls.create_messages(messages, image_request)
|
|
|
|
headers = {
|
2024-04-28 20:19:51 +00:00
|
|
|
"accept": "text/event-stream",
|
|
|
|
"Openai-Sentinel-Chat-Requirements-Token": chat_token,
|
2024-03-14 12:53:57 +00:00
|
|
|
**cls._headers
|
|
|
|
}
|
|
|
|
if need_arkose:
|
2024-04-28 20:19:51 +00:00
|
|
|
headers["Openai-Sentinel-Arkose-Token"] = arkose_token
|
|
|
|
if proofofwork is not None:
|
|
|
|
headers["Openai-Sentinel-Proof-Token"] = proofofwork
|
2024-01-13 14:37:36 +00:00
|
|
|
async with session.post(
|
2024-05-18 21:13:57 +00:00
|
|
|
f"{cls.url}/backend-anon/conversation"
|
|
|
|
if cls._api_key is None else
|
2024-01-13 14:37:36 +00:00
|
|
|
f"{cls.url}/backend-api/conversation",
|
|
|
|
json=data,
|
2024-03-14 12:53:57 +00:00
|
|
|
headers=headers
|
2024-01-13 14:37:36 +00:00
|
|
|
) as response:
|
2024-02-26 22:41:06 +00:00
|
|
|
cls._update_request_args(session)
|
2024-05-18 13:37:46 +00:00
|
|
|
if response.status == 403 and max_retries > 0:
|
|
|
|
max_retries -= 1
|
|
|
|
if debug.logging:
|
|
|
|
print(f"Retry: Error {response.status}: {await response.text()}")
|
|
|
|
await asyncio.sleep(5)
|
|
|
|
continue
|
2024-03-14 12:53:57 +00:00
|
|
|
await raise_for_status(response)
|
2024-05-18 13:37:46 +00:00
|
|
|
async for chunk in cls.iter_messages_chunk(response.iter_lines(), session, conversation, ws):
|
2024-03-26 05:42:47 +00:00
|
|
|
if return_conversation:
|
2024-03-28 10:36:25 +00:00
|
|
|
history_disabled = False
|
2024-03-26 05:42:47 +00:00
|
|
|
return_conversation = False
|
2024-04-05 19:00:35 +00:00
|
|
|
yield conversation
|
2024-02-28 06:36:43 +00:00
|
|
|
yield chunk
|
2024-04-05 19:00:35 +00:00
|
|
|
if auto_continue and conversation.finish_reason == "max_tokens":
|
|
|
|
conversation.finish_reason = None
|
|
|
|
action = "continue"
|
|
|
|
await asyncio.sleep(5)
|
|
|
|
else:
|
2023-11-20 13:00:40 +00:00
|
|
|
break
|
2024-03-28 10:36:25 +00:00
|
|
|
if history_disabled and auto_continue:
|
2024-04-05 19:00:35 +00:00
|
|
|
await cls.delete_conversation(session, cls._headers, conversation.conversation_id)
|
2024-02-28 06:36:43 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2024-03-14 12:53:57 +00:00
|
|
|
async def iter_messages_ws(ws: ClientWebSocketResponse, conversation_id: str, is_curl: bool) -> AsyncIterator:
|
2024-02-28 06:36:43 +00:00
|
|
|
while True:
|
2024-03-14 12:53:57 +00:00
|
|
|
if is_curl:
|
|
|
|
message = json.loads(ws.recv()[0])
|
|
|
|
else:
|
|
|
|
message = await ws.receive_json()
|
2024-03-08 10:01:38 +00:00
|
|
|
if message["conversation_id"] == conversation_id:
|
|
|
|
yield base64.b64decode(message["body"])
|
2024-02-28 06:36:43 +00:00
|
|
|
|
|
|
|
@classmethod
|
2024-03-14 12:53:57 +00:00
|
|
|
async def iter_messages_chunk(
|
|
|
|
cls,
|
|
|
|
messages: AsyncIterator,
|
|
|
|
session: StreamSession,
|
2024-05-18 13:37:46 +00:00
|
|
|
fields: Conversation,
|
|
|
|
ws = None
|
2024-03-14 12:53:57 +00:00
|
|
|
) -> AsyncIterator:
|
2024-02-28 06:36:43 +00:00
|
|
|
last_message: int = 0
|
|
|
|
async for message in messages:
|
|
|
|
if message.startswith(b'{"wss_url":'):
|
2024-03-08 10:01:38 +00:00
|
|
|
message = json.loads(message)
|
2024-05-18 13:37:46 +00:00
|
|
|
ws = await session.ws_connect(message["wss_url"]) if ws is None else ws
|
2024-03-14 12:53:57 +00:00
|
|
|
try:
|
|
|
|
async for chunk in cls.iter_messages_chunk(
|
|
|
|
cls.iter_messages_ws(ws, message["conversation_id"], hasattr(ws, "recv")),
|
|
|
|
session, fields
|
|
|
|
):
|
2024-02-28 06:36:43 +00:00
|
|
|
yield chunk
|
2024-03-14 12:53:57 +00:00
|
|
|
finally:
|
2024-03-25 20:06:51 +00:00
|
|
|
await ws.aclose() if hasattr(ws, "aclose") else await ws.close()
|
2024-02-28 06:36:43 +00:00
|
|
|
break
|
|
|
|
async for chunk in cls.iter_messages_line(session, message, fields):
|
|
|
|
if fields.finish_reason is not None:
|
|
|
|
break
|
|
|
|
elif isinstance(chunk, str):
|
|
|
|
if len(chunk) > last_message:
|
|
|
|
yield chunk[last_message:]
|
|
|
|
last_message = len(chunk)
|
|
|
|
else:
|
|
|
|
yield chunk
|
|
|
|
if fields.finish_reason is not None:
|
|
|
|
break
|
|
|
|
|
|
|
|
@classmethod
|
2024-03-26 05:42:47 +00:00
|
|
|
async def iter_messages_line(cls, session: StreamSession, line: bytes, fields: Conversation) -> AsyncIterator:
|
2024-02-28 06:36:43 +00:00
|
|
|
if not line.startswith(b"data: "):
|
|
|
|
return
|
|
|
|
elif line.startswith(b"data: [DONE]"):
|
2024-03-09 02:10:59 +00:00
|
|
|
if fields.finish_reason is None:
|
|
|
|
fields.finish_reason = "error"
|
2024-02-28 06:36:43 +00:00
|
|
|
return
|
|
|
|
try:
|
|
|
|
line = json.loads(line[6:])
|
|
|
|
except:
|
|
|
|
return
|
|
|
|
if "message" not in line:
|
|
|
|
return
|
|
|
|
if "error" in line and line["error"]:
|
|
|
|
raise RuntimeError(line["error"])
|
|
|
|
if "message_type" not in line["message"]["metadata"]:
|
|
|
|
return
|
2024-05-18 21:13:57 +00:00
|
|
|
image_response = await cls.get_generated_image(session, cls._headers, line)
|
|
|
|
if image_response is not None:
|
|
|
|
yield image_response
|
2024-02-28 06:36:43 +00:00
|
|
|
if line["message"]["author"]["role"] != "assistant":
|
|
|
|
return
|
|
|
|
if line["message"]["content"]["content_type"] != "text":
|
|
|
|
return
|
|
|
|
if line["message"]["metadata"]["message_type"] not in ("next", "continue", "variant"):
|
|
|
|
return
|
2024-04-19 12:07:56 +00:00
|
|
|
if line["message"]["recipient"] != "all":
|
|
|
|
return
|
2024-02-28 06:36:43 +00:00
|
|
|
if fields.conversation_id is None:
|
|
|
|
fields.conversation_id = line["conversation_id"]
|
|
|
|
fields.message_id = line["message"]["id"]
|
|
|
|
if "parts" in line["message"]["content"]:
|
|
|
|
yield line["message"]["content"]["parts"][0]
|
|
|
|
if "finish_details" in line["message"]["metadata"]:
|
|
|
|
fields.finish_reason = line["message"]["metadata"]["finish_details"]["type"]
|
2023-10-03 20:12:56 +00:00
|
|
|
|
2024-03-14 12:53:57 +00:00
|
|
|
@classmethod
|
|
|
|
async def webview_access_token(cls) -> str:
|
|
|
|
window = webview.create_window("OpenAI Chat", cls.url)
|
|
|
|
await asyncio.sleep(3)
|
|
|
|
prompt_input = None
|
|
|
|
while not prompt_input:
|
|
|
|
try:
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
prompt_input = window.dom.get_element("#prompt-textarea")
|
|
|
|
except:
|
|
|
|
...
|
|
|
|
window.evaluate_js("""
|
|
|
|
this._fetch = this.fetch;
|
|
|
|
this.fetch = async (url, options) => {
|
|
|
|
const response = await this._fetch(url, options);
|
2024-05-15 00:27:51 +00:00
|
|
|
if (url == "https://chatgpt.com/backend-api/conversation") {
|
2024-03-14 12:53:57 +00:00
|
|
|
this._headers = options.headers;
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
return response;
|
|
|
|
};
|
|
|
|
""")
|
|
|
|
window.evaluate_js("""
|
|
|
|
document.querySelector('.from-token-main-surface-secondary').click();
|
|
|
|
""")
|
|
|
|
headers = None
|
|
|
|
while headers is None:
|
|
|
|
headers = window.evaluate_js("this._headers")
|
|
|
|
await asyncio.sleep(1)
|
2024-03-15 10:46:06 +00:00
|
|
|
headers["User-Agent"] = window.evaluate_js("this.navigator.userAgent")
|
2024-03-14 12:53:57 +00:00
|
|
|
cookies = [list(*cookie.items()) for cookie in window.get_cookies()]
|
|
|
|
window.destroy()
|
|
|
|
cls._cookies = dict([(name, cookie.value) for name, cookie in cookies])
|
|
|
|
cls._headers = headers
|
|
|
|
cls._expires = int(time.time()) + 60 * 60 * 4
|
|
|
|
cls._update_cookie_header()
|
|
|
|
|
2024-04-07 14:02:49 +00:00
|
|
|
@classmethod
|
2024-05-15 19:07:49 +00:00
|
|
|
async def nodriver_access_token(cls, proxy: str = None):
|
2024-04-07 14:02:49 +00:00
|
|
|
try:
|
|
|
|
import nodriver as uc
|
|
|
|
except ImportError:
|
|
|
|
return
|
|
|
|
try:
|
|
|
|
from platformdirs import user_config_dir
|
|
|
|
user_data_dir = user_config_dir("g4f-nodriver")
|
|
|
|
except:
|
|
|
|
user_data_dir = None
|
2024-04-18 18:18:51 +00:00
|
|
|
if debug.logging:
|
|
|
|
print(f"Open nodriver with user_dir: {user_data_dir}")
|
2024-05-15 19:07:49 +00:00
|
|
|
browser = await uc.start(
|
|
|
|
user_data_dir=user_data_dir,
|
|
|
|
browser_args=None if proxy is None else [f"--proxy-server={proxy}"],
|
|
|
|
)
|
2024-05-15 00:27:51 +00:00
|
|
|
page = await browser.get("https://chatgpt.com/")
|
2024-04-21 05:22:59 +00:00
|
|
|
await page.select("[id^=headlessui-menu-button-]", 240)
|
2024-04-07 14:02:49 +00:00
|
|
|
api_key = await page.evaluate(
|
|
|
|
"(async () => {"
|
|
|
|
"let session = await fetch('/api/auth/session');"
|
|
|
|
"let data = await session.json();"
|
|
|
|
"let accessToken = data['accessToken'];"
|
|
|
|
"let expires = new Date(); expires.setTime(expires.getTime() + 60 * 60 * 4 * 1000);"
|
|
|
|
"document.cookie = 'access_token=' + accessToken + ';expires=' + expires.toUTCString() + ';path=/';"
|
|
|
|
"return accessToken;"
|
|
|
|
"})();",
|
|
|
|
await_promise=True
|
|
|
|
)
|
|
|
|
cookies = {}
|
|
|
|
for c in await page.browser.cookies.get_all():
|
2024-05-15 00:27:51 +00:00
|
|
|
if c.domain.endswith("chatgpt.com"):
|
2024-04-07 14:02:49 +00:00
|
|
|
cookies[c.name] = c.value
|
2024-04-18 18:18:51 +00:00
|
|
|
user_agent = await page.evaluate("window.navigator.userAgent")
|
2024-04-07 14:02:49 +00:00
|
|
|
await page.close()
|
2024-04-21 13:15:55 +00:00
|
|
|
cls._create_request_args(cookies, user_agent=user_agent)
|
2024-04-07 14:02:49 +00:00
|
|
|
cls._set_api_key(api_key)
|
|
|
|
|
2023-10-03 20:12:56 +00:00
|
|
|
@classmethod
|
2024-02-28 06:36:43 +00:00
|
|
|
def browse_access_token(cls, proxy: str = None, timeout: int = 1200) -> None:
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Browse to obtain an access token.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
proxy (str): Proxy to use for browsing.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
tuple[str, dict]: A tuple containing the access token and cookies.
|
|
|
|
"""
|
2024-02-09 05:36:28 +00:00
|
|
|
driver = get_browser(proxy=proxy)
|
|
|
|
try:
|
2024-01-13 14:37:36 +00:00
|
|
|
driver.get(f"{cls.url}/")
|
2024-01-14 14:35:58 +00:00
|
|
|
WebDriverWait(driver, timeout).until(EC.presence_of_element_located((By.ID, "prompt-textarea")))
|
2024-01-14 06:45:41 +00:00
|
|
|
access_token = driver.execute_script(
|
|
|
|
"let session = await fetch('/api/auth/session');"
|
|
|
|
"let data = await session.json();"
|
|
|
|
"let accessToken = data['accessToken'];"
|
2024-02-26 22:41:06 +00:00
|
|
|
"let expires = new Date(); expires.setTime(expires.getTime() + 60 * 60 * 4 * 1000);"
|
2024-01-14 06:45:41 +00:00
|
|
|
"document.cookie = 'access_token=' + accessToken + ';expires=' + expires.toUTCString() + ';path=/';"
|
|
|
|
"return accessToken;"
|
2024-01-13 14:37:36 +00:00
|
|
|
)
|
2024-02-23 10:33:38 +00:00
|
|
|
args = get_args_from_browser(f"{cls.url}/", driver, do_bypass_cloudflare=False)
|
2024-02-28 06:36:43 +00:00
|
|
|
cls._headers = args["headers"]
|
|
|
|
cls._cookies = args["cookies"]
|
|
|
|
cls._update_cookie_header()
|
|
|
|
cls._set_api_key(access_token)
|
2024-02-09 05:36:28 +00:00
|
|
|
finally:
|
2024-03-14 12:53:57 +00:00
|
|
|
driver.close()
|
2024-01-13 14:37:36 +00:00
|
|
|
|
2024-02-26 22:41:06 +00:00
|
|
|
@classmethod
|
|
|
|
async def fetch_access_token(cls, session: StreamSession, headers: dict):
|
|
|
|
async with session.get(
|
|
|
|
f"{cls.url}/api/auth/session",
|
|
|
|
headers=headers
|
|
|
|
) as response:
|
|
|
|
if response.ok:
|
|
|
|
data = await response.json()
|
|
|
|
if "accessToken" in data:
|
|
|
|
return data["accessToken"]
|
|
|
|
|
2024-04-05 19:00:35 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_default_headers() -> dict:
|
|
|
|
return {
|
2024-04-21 05:22:59 +00:00
|
|
|
**DEFAULT_HEADERS,
|
2024-04-05 19:00:35 +00:00
|
|
|
"content-type": "application/json",
|
|
|
|
}
|
|
|
|
|
2024-02-26 22:41:06 +00:00
|
|
|
@classmethod
|
2024-04-21 13:15:55 +00:00
|
|
|
def _create_request_args(cls, cookies: Cookies = None, headers: dict = None, user_agent: str = None):
|
|
|
|
cls._headers = cls.get_default_headers() if headers is None else headers
|
2024-04-18 18:18:51 +00:00
|
|
|
if user_agent is not None:
|
|
|
|
cls._headers["user-agent"] = user_agent
|
2024-04-21 13:15:55 +00:00
|
|
|
cls._cookies = {} if cookies is None else {k: v for k, v in cookies.items() if k != "access_token"}
|
2024-02-28 06:36:43 +00:00
|
|
|
cls._update_cookie_header()
|
2024-02-26 22:41:06 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _update_request_args(cls, session: StreamSession):
|
|
|
|
for c in session.cookie_jar if hasattr(session, "cookie_jar") else session.cookies.jar:
|
2024-03-26 05:42:47 +00:00
|
|
|
cls._cookies[c.key if hasattr(c, "key") else c.name] = c.value
|
2024-02-28 06:36:43 +00:00
|
|
|
cls._update_cookie_header()
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _set_api_key(cls, api_key: str):
|
|
|
|
cls._api_key = api_key
|
2024-03-08 10:01:38 +00:00
|
|
|
cls._expires = int(time.time()) + 60 * 60 * 4
|
2024-04-21 05:22:59 +00:00
|
|
|
cls._headers["authorization"] = f"Bearer {api_key}"
|
2024-02-28 06:36:43 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _update_cookie_header(cls):
|
2024-04-21 13:15:55 +00:00
|
|
|
cls._headers["cookie"] = format_cookies(cls._cookies)
|
2024-04-28 20:19:51 +00:00
|
|
|
if "oai-did" in cls._cookies:
|
|
|
|
cls._headers["oai-device-id"] = cls._cookies["oai-did"]
|
2024-02-26 22:41:06 +00:00
|
|
|
|
2024-03-26 05:42:47 +00:00
|
|
|
class Conversation(BaseConversation):
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Class to encapsulate response fields.
|
|
|
|
"""
|
2024-02-28 06:36:43 +00:00
|
|
|
def __init__(self, conversation_id: str = None, message_id: str = None, finish_reason: str = None):
|
2023-11-19 04:36:04 +00:00
|
|
|
self.conversation_id = conversation_id
|
|
|
|
self.message_id = message_id
|
2024-02-28 06:36:43 +00:00
|
|
|
self.finish_reason = finish_reason
|
2024-01-14 14:35:58 +00:00
|
|
|
|
2023-11-19 04:36:04 +00:00
|
|
|
class Response():
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Class to encapsulate a response from the chat service.
|
|
|
|
"""
|
2023-11-19 04:36:04 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
generator: AsyncResult,
|
|
|
|
action: str,
|
|
|
|
messages: Messages,
|
|
|
|
options: dict
|
|
|
|
):
|
2024-01-13 14:37:36 +00:00
|
|
|
self._generator = generator
|
2024-01-14 06:45:41 +00:00
|
|
|
self.action = action
|
|
|
|
self.is_end = False
|
2024-01-13 14:37:36 +00:00
|
|
|
self._message = None
|
2023-11-19 04:36:04 +00:00
|
|
|
self._messages = messages
|
|
|
|
self._options = options
|
2024-01-13 14:37:36 +00:00
|
|
|
self._fields = None
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2024-03-09 02:10:59 +00:00
|
|
|
async def generator(self) -> AsyncIterator:
|
|
|
|
if self._generator is not None:
|
2024-01-13 14:37:36 +00:00
|
|
|
self._generator = None
|
|
|
|
chunks = []
|
|
|
|
async for chunk in self._generator:
|
2024-03-26 05:42:47 +00:00
|
|
|
if isinstance(chunk, Conversation):
|
2024-01-13 14:37:36 +00:00
|
|
|
self._fields = chunk
|
|
|
|
else:
|
|
|
|
yield chunk
|
|
|
|
chunks.append(str(chunk))
|
|
|
|
self._message = "".join(chunks)
|
2024-03-09 02:10:59 +00:00
|
|
|
if self._fields is None:
|
2024-01-13 14:37:36 +00:00
|
|
|
raise RuntimeError("Missing response fields")
|
2024-03-09 02:10:59 +00:00
|
|
|
self.is_end = self._fields.finish_reason == "stop"
|
2023-11-19 04:36:04 +00:00
|
|
|
|
|
|
|
def __aiter__(self):
|
2024-01-13 14:37:36 +00:00
|
|
|
return self.generator()
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2024-03-09 02:10:59 +00:00
|
|
|
async def get_message(self) -> str:
|
2024-01-14 06:45:41 +00:00
|
|
|
await self.generator()
|
2024-01-13 14:37:36 +00:00
|
|
|
return self._message
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2024-03-09 02:10:59 +00:00
|
|
|
async def get_fields(self) -> dict:
|
2024-01-14 06:45:41 +00:00
|
|
|
await self.generator()
|
2024-03-09 02:10:59 +00:00
|
|
|
return {
|
|
|
|
"conversation_id": self._fields.conversation_id,
|
|
|
|
"parent_id": self._fields.message_id
|
|
|
|
}
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2024-03-09 02:10:59 +00:00
|
|
|
async def create_next(self, prompt: str, **kwargs) -> Response:
|
2023-11-19 04:36:04 +00:00
|
|
|
return await OpenaiChat.create(
|
|
|
|
**self._options,
|
|
|
|
prompt=prompt,
|
2024-03-09 02:10:59 +00:00
|
|
|
messages=await self.get_messages(),
|
2023-11-19 04:36:04 +00:00
|
|
|
action="next",
|
2024-01-13 14:37:36 +00:00
|
|
|
**await self.get_fields(),
|
2023-11-19 04:36:04 +00:00
|
|
|
**kwargs
|
|
|
|
)
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2023-11-19 04:36:04 +00:00
|
|
|
async def do_continue(self, **kwargs) -> Response:
|
2024-01-13 14:37:36 +00:00
|
|
|
fields = await self.get_fields()
|
|
|
|
if self.is_end:
|
2023-11-19 04:36:04 +00:00
|
|
|
raise RuntimeError("Can't continue message. Message already finished.")
|
|
|
|
return await OpenaiChat.create(
|
|
|
|
**self._options,
|
2024-03-09 02:10:59 +00:00
|
|
|
messages=await self.get_messages(),
|
2023-11-19 04:36:04 +00:00
|
|
|
action="continue",
|
2024-01-13 14:37:36 +00:00
|
|
|
**fields,
|
2023-11-19 04:36:04 +00:00
|
|
|
**kwargs
|
|
|
|
)
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2024-03-09 02:10:59 +00:00
|
|
|
async def create_variant(self, **kwargs) -> Response:
|
2023-11-19 04:36:04 +00:00
|
|
|
if self.action != "next":
|
2023-11-20 13:00:40 +00:00
|
|
|
raise RuntimeError("Can't create variant from continue or variant request.")
|
2023-11-19 04:36:04 +00:00
|
|
|
return await OpenaiChat.create(
|
|
|
|
**self._options,
|
|
|
|
messages=self._messages,
|
|
|
|
action="variant",
|
2024-01-13 14:37:36 +00:00
|
|
|
**await self.get_fields(),
|
2023-11-19 04:36:04 +00:00
|
|
|
**kwargs
|
|
|
|
)
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2024-03-09 02:10:59 +00:00
|
|
|
async def get_messages(self) -> list:
|
2023-11-19 04:36:04 +00:00
|
|
|
messages = self._messages
|
2024-03-09 02:10:59 +00:00
|
|
|
messages.append({"role": "assistant", "content": await self.message()})
|
2024-04-13 20:28:12 +00:00
|
|
|
return messages
|