|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +from uuid import uuid4 as uuid |
| 5 | +import json |
| 6 | +import requests |
| 7 | +from .errors import CallError |
| 8 | + |
| 9 | + |
| 10 | +class Conversation: |
| 11 | + DEFAULT_MODEL_NAME = 'text-davinci-002-render' |
| 12 | + |
| 13 | + def __init__( |
| 14 | + self, |
| 15 | + model_name: str = None, |
| 16 | + conversation_id: str = None, |
| 17 | + parent_message_id: str = None, |
| 18 | + access_token: str = None, |
| 19 | + ): |
| 20 | + self.load_config() |
| 21 | + |
| 22 | + self._model_name = model_name or self.DEFAULT_MODEL_NAME |
| 23 | + |
| 24 | + if self._access_token is None: |
| 25 | + self._access_token = access_token |
| 26 | + |
| 27 | + if self._conversation_id is None: |
| 28 | + self._conversation_id = conversation_id |
| 29 | + |
| 30 | + if self._first_parent_message_id is None: |
| 31 | + self._first_parent_message_id = parent_message_id |
| 32 | + self._message_id = parent_message_id |
| 33 | + |
| 34 | + def load_config(self, config_path: str = None): |
| 35 | + if config_path is None: |
| 36 | + config_path = 'config.json' |
| 37 | + |
| 38 | + with open(config_path, 'r') as f: |
| 39 | + config = json.load(f) |
| 40 | + |
| 41 | + self._access_token = config['access_token'] |
| 42 | + self._conversation_id = config['conversation_id'] |
| 43 | + self._first_parent_message_id = config['parent_message_id'] |
| 44 | + |
| 45 | + def chat(self, message: str): |
| 46 | + self._parent_message_id = self._message_id |
| 47 | + self._message_id = str(uuid()) |
| 48 | + |
| 49 | + url = "https://chat.openai.com/backend-api/conversation" |
| 50 | + |
| 51 | + payload = json.dumps( |
| 52 | + { |
| 53 | + "action": "next", |
| 54 | + "messages": [ |
| 55 | + { |
| 56 | + "id": self._message_id, |
| 57 | + "role": "user", |
| 58 | + "content": { |
| 59 | + "content_type": "text", |
| 60 | + "parts": [message] |
| 61 | + } |
| 62 | + } |
| 63 | + ], |
| 64 | + "conversation_id": self._conversation_id, |
| 65 | + "parent_message_id": self._parent_message_id, |
| 66 | + "model": self._model_name |
| 67 | + } |
| 68 | + ) |
| 69 | + headers = { |
| 70 | + 'Authorization': f'Bearer {self._access_token}', |
| 71 | + } |
| 72 | + |
| 73 | + response = requests.request("POST", url, headers=headers, data=payload) |
| 74 | + payload = response.text |
| 75 | + |
| 76 | + try: |
| 77 | + last_item = payload.split(('data:'))[-2] |
| 78 | + text_items = json.loads(last_item)['message']['content']['parts'] |
| 79 | + text = '\n'.join(text_items) |
| 80 | + postprocessed_text = text.replace(r'\n+', '\n') |
| 81 | + return postprocessed_text |
| 82 | + except IndexError: |
| 83 | + error_message = json.loads(payload)['detail'] |
| 84 | + raise CallError(error_message) |
| 85 | + |
| 86 | + def reset(self): |
| 87 | + self._message_id = self._first_parent_message_id |
0 commit comments