Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

import requests import json import secrets class ModelClient: def init(self):…

  1. User

    import requests import json import secrets

    class ModelClient: def init(self): self.supports_streaming = True self.history = [] self.session_hash = None self.stream_url = None self.join_url = "https://yuntian-deng-chatgpt.hf.space/queue/join?__theme=light" self.headers = { "accept": "/", "accept-language": "ru,en;q=0.9", "content-type": "application/json", "priority": "u=1, i", "sec-ch-ua": ""Not/A)Brand";v="8", "Chromium";v="126", "YaBrowser";v="24.7", " ""Yowser";v="2.5"", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": ""Windows"", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin" }

    @staticmethod
    def _generate_random_hash(length=10):
        """Генерирует случайный хэш указанной длины"""
        characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return ''.join(secrets.choice(characters) for _ in range(length))
    
    def _make_join_request(self, body):
        try:
            response = requests.post(self.join_url, headers=self.headers, json=body)
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            print(f"HTTP error occurred: {e}")
        except Exception as e:
            print(f"An error occurred: {e}")
        return None
    
    def _make_stream_request(self):
        try:
            response = requests.get(self.stream_url, headers={**self.headers, 'accept': "text/event-stream"},
                                    stream=True)
            response.raise_for_status()
            return response
        except requests.exceptions.HTTPError as e:
            print(f"HTTP error occurred: {e}")
        except Exception as e:
            print(f"An error occurred: {e}")
        return None
    
    @staticmethod
    def _process_stream_response(response):
        response_message = ""
        if response:
            for chunk in response.iter_lines():
                if chunk:
                    try:
                        event_data = json.loads(chunk.decode('utf-8').replace("data: ", ""))
                        if event_data.get('msg') == "process_generating":
                            if event_data['output']['data'][0]:
                                output = event_data['output']['data'][0][-1]
                                response_message += output[-1]  # аккумулируем текст
                                yield response_message  # отдаём текущее состояние текста
                    except json.JSONDecodeError:
                        continue
        yield response_message  # Возвращаем окончательный ответ
    
    def get_response(self, message, sys_prompt):
        if not self.history:
            self.session_hash = self._generate_random_hash()
            self.stream_url = f"https://yuntian-deng-chatgpt.hf.space/queue/data?session_hash={self.session_hash}"
            input_message = sys_prompt + "\n" + message
        else:
            input_message = message
    
        body = {
            "data": [input_message, 1, 1, len(self.history), self.history, None],
            "event_data": None,
            "fn_index": 3,
            "trigger_id": 5,
            "session_hash": self.session_hash
        }
        self._make_join_request(body)
        stream_response = self._make_stream_request()
    
        # Используем цикл for для последовательной обработки
        for chunk in self._process_stream_response(stream_response):
            yield chunk  # Теперь передаём каждый кусок данных Gradio
        
        self.history.append((input_message, ))
    

    Как мне в конце стрима записать полный ответ? self.history.append((input_message, сюда))

  2. Assistant

    Чтобы сохранить полный ответ в self.history в конце обработки данных стрима, вам нужно немного изменить свою функцию _process_stream_response. В частности, необходимо сохранить окончательное значение response_message, как только весь поток данных будет обработан.

    Вот как можно это сделать:

    1. Нужно создать переменную для хранения окончательного ответа.
    2. Вычислить значение response_message и сохранить его в self.history после завершения обработки потока ответа.

    Изменим ваш код следующим образом:

    def _process_stream_response(self, response):
        response_message = ""
        if response:
            for chunk in response.iter_lines():
                if chunk:
                    try:
                        event_data = json.loads(chunk.decode('utf-8').replace("data: ", ""))
                        if event_data.get('msg') == "process_generating":
                            if event_data['output']['data'][0]:
                                output = event_data['output']['data'][0][-1]
                                response_message += output[-1]  # аккумулируем текст
                                yield response_message  # отдаём текущее состояние текста
                    except json.JSONDecodeError:
                        continue
    
        # Возвращаем окончательный ответ
        yield response_message
    
    def get_response(self, message, sys_prompt):
        if not self.history:
            self.session_hash = self._generate_random_hash()
            self.stream_url = f"https://yuntian-deng-chatgpt.hf.space/queue/data?session_hash={self.session_hash}"
            input_message = sys_prompt + "\n" + message
        else:
            input_message = message
    
        body = {
            "data": [input_message, 1, 1, len(self.history), self.history, None],
            "event_data": None,
            "fn_index": 3,
            "trigger_id": 5,
            "session_hash": self.session_hash
        }
        self._make_join_request(body)
        stream_response = self._make_stream_request()
    
        # Variable to hold the final response
        final_response = ""
    
        # Используем цикл for для последовательной обработки
        for chunk in self._process_stream_response(stream_response):
            yield chunk  # Теперь передаём каждый кусок данных Gradio
            final_response = chunk  # Сохраняем текущий ответ как окончательный
    
        # В конце добавляем полный ответ в историю
        self.history.append((input_message, final_response))
    

    Обратите внимание на переменную final_response, которая обновляется в цикле и в конце добавляется в self.history. Теперь весь ваш ответ будет сохранён в истории после завершения стрима.