Certainly! Below is the refactored version of your yandexgpt class with the following improvements:
- Asynchronous Implementation: Utilizes
aiohttp for non-blocking HTTP requests.
- Cookie Management: Keeps track of the number of requests and refreshes cookies after 99 requests.
- Single Request Handling: Combines the two-step request (
send_request and fetch_until_final) into a single asynchronous method.
- Error Handling: Returns error messages in case of failures instead of the response text.
- Code Cleanliness: Improved structure, naming conventions, and overall readability.
Prerequisites
Make sure to install aiohttp before running the code:
pip install aiohttp
Refactored Asynchronous yandexgpt Class
import aiohttp
import asyncio
import time
import uuid
from typing import Any, Dict
class YandexGPT:
MAX_REQUESTS = 99 # Maximum requests before refreshing cookies
def __init__(self):
self.headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "ru-RU,ru;q=0.9",
"Cache-Control": "no-cache",
"Content-Type": "application/json",
"Device-Memory": "8",
"Downlink": "5.4",
"DPR": "1.5",
"ECT": "4g",
"Origin": "https://ya.ru",
"Pragma": "no-cache",
"Priority": "u=1, i",
"Referer": "https://ya.ru/search/?text=example",
"RTT": "100",
"Sec-CH-UA": "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
"Sec-CH-UA-Arch": "\"x86\"",
"Sec-CH-UA-Bitness": "\"64\"",
"Sec-CH-UA-Full-Version": "\"129.0.6668.101\"",
"Sec-CH-UA-Full-Version-List": "\"Google Chrome\";v=\"129.0.6668.101\", \"Not=A?Brand\";v=\"8.0.0.0\", \"Chromium\";v=\"129.0.6668.101\"",
"Sec-CH-UA-Mobile": "?0",
"Sec-CH-UA-Model": "\"\"",
"Sec-CH-UA-Platform": "\"Windows\"",
"Sec-CH-UA-Platform-Version": "\"15.0.0\"",
"Sec-CH-UA-WoW64": "?0",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/129.0.0.0 Safari/537.36",
"Viewport-Width": "736",
"X-Requested-With": "XMLHttpRequest",
"X-Retpath-Y": "https://ya.ru/search/?text=example"
}
self.session = aiohttp.ClientSession(headers=self.headers)
self.request_count = 0
self.lock = asyncio.Lock() # To ensure thread-safe updates to request_count
async def _initialize_session(self):
"""Initializes or refreshes the session by making a GET request to establish cookies."""
async with self.session.get("https://ya.ru") as response:
if response.status != 200:
print(f"Failed to initialize session: {response.status}")
else:
print("Session initialized with cookies.")
async def _refresh_session(self):
"""Refreshes the session by closing the current session and creating a new one."""
await self.session.close()
self.session = aiohttp.ClientSession(headers=self.headers)
await self._initialize_session()
async with self.lock:
self.request_count = 0
print("Session refreshed and cookies updated.")
async def send_prompt(self, prompt: str) -> str:
"""Sends a prompt to Yandex GPT and returns the response or an error message."""
await self._check_and_refresh_session()
# Generate unique reqid using UUID and current time
timestamp = int(time.time() * 1_000_000)
unique_id = uuid.uuid4().hex
reqid = f"{timestamp}-{unique_id}-BAL"
url = (
f"https://ya.ru/neuralsearch/api/send_to_dialog?"
f"lr=11091&"
f"suggest_reqid=&"
f"primary_reqid={timestamp}-13515373250909564767-balancer-l7leveler-kubr-yp-sas-27-BAL&"
f"reqid={reqid}&from=button"
)
body = {
"UserRequest": prompt
}
try:
async with self.session.post(url, json=body) as response:
if response.status != 200:
return f"текст ошибки: HTTP {response.status}"
data = await response.json()
response_message_id = data.get("ResponseMessageId")
if not response_message_id:
return "текст ошибки: Missing ResponseMessageId in response."
# Wait for the final response
final_response = await self._fetch_final_response(response_message_id)
return final_response
except aiohttp.ClientError as e:
return f"текст ошибки: {str(e)}"
async def _fetch_final_response(self, response_message_id: str) -> str:
"""Fetches the final response text using the ResponseMessageId."""
url = (
f"https://ya.ru/neuralsearch/api/get_fresh_message?"
f"lr=11091&"
f"suggest_reqid=620775595168845935386354600584464&"
f"msid={response_message_id}&"
f"reqid={response_message_id}"
)
body = {
"ResponseMessageId": response_message_id
}
try:
while True:
async with self.session.post(url, json=body) as response:
if response.status != 200:
return f"текст ошибки: HTTP {response.status}"
data = await response.json()
if data.get("IsFinalMarkdownText"):
return data.get("Text", "текст ошибки: Missing Text in final response.")
await asyncio.sleep(1) # Wait before retrying
except aiohttp.ClientError as e:
return f"текст ошибки: {str(e)}"
async def _check_and_refresh_session(self):
"""Checks the request count and refreshes the session if necessary."""
async with self.lock:
if self.request_count >= self.MAX_REQUESTS:
await self._refresh_session()
self.request_count += 1
async def close(self):
"""Closes the aiohttp session."""
await self.session.close()
# Example usage
async def main():
gpt = YandexGPT()
await gpt._initialize_session() # Initialize session with cookies
try:
response = await gpt.send_prompt("мой промпт")
print("Final Response:", response)
finally:
await gpt.close()
# Run the example
if __name__ == "__main__":
asyncio.run(main())
Explanation of the Improvements
-
Asynchronous Operations with aiohttp:
- Replaced
requests with aiohttp to perform non-blocking HTTP requests.
- All network operations are now
async functions, allowing for concurrent executions without blocking the event loop.
-
Session Management and Cookie Refreshing:
- The
YandexGPT class initializes an aiohttp.ClientSession with the provided headers.
- A request counter (
self.request_count) keeps track of the number of requests made.
- Once
self.request_count reaches MAX_REQUESTS (99), the session is refreshed by closing the current session and creating a new one, thereby updating the cookies.
- A lock (
self.lock) ensures that incrementing the request count and refreshing the session are thread-safe operations.
-
Single Method for Sending Prompt and Receiving Response:
- The
send_prompt method handles both sending the prompt and fetching the final response.
- It first sends the prompt and retrieves a
ResponseMessageId.
- Then, it continuously polls for the final response using
_fetch_final_response until IsFinalMarkdownText is True.
-
Error Handling:
- If any HTTP request fails (non-200 status code), the method returns an error message prefixed with
"текст ошибки: ".
- Network-related exceptions are caught and returned as error messages.
- Missing expected fields in the response also result in appropriate error messages.
-
Code Cleanliness and Maintainability:
- Improved naming conventions for better readability.
- Added type hints for better code clarity and potential static analysis.
- Encapsulated functionality into smaller helper methods for modularity.
-
Example Usage:
- Provided an
async main function demonstrating how to initialize the class, send a prompt, and handle the response.
- Ensures that the
aiohttp session is properly closed after usage.
Additional Notes
-
Concurrency: This implementation is suitable for concurrent usage. If you plan to make multiple send_prompt calls simultaneously, the class handles session refreshing safely using asyncio locks.
-
UUID for reqid: To ensure uniqueness of reqid, the uuid library is used alongside a timestamp.
-
Polling Interval: The _fetch_final_response method waits for 1 second between each poll. You can adjust this interval based on your requirements and the API's response time characteristics.
-
Session Initialization: The example usage explicitly calls _initialize_session to perform the initial GET request to establish cookies. This can be integrated into the class constructor or handled differently based on your specific needs.
Feel free to integrate this refactored class into your project and adjust the configurations as necessary.