import sys import json import os import urllib3 from pathlib import Path from reader import read_json_and_xml http = urllib3.PoolManager() def play(message: dict, api_key=os.environ["OPENAI_API_KEY"]) -> str: method = message["method"] relative_url = message["url"] request_body = message["body"] base_url = "https://api.openai.com" full_url = base_url + relative_url headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } encoded_body = json.dumps(request_body, ensure_ascii=False) print(request_body) response = http.request( method=method, url=full_url, body=encoded_body.encode("utf-8"), headers=headers ) response_data = response.data.decode("utf-8").strip() return response_data def play_list(input_filename: str | Path, api_key=os.environ["OPENAI_API_KEY"]) -> Path: input_filename = Path(input_filename) last_index_filename = input_filename.with_suffix('.state') output_filename = input_filename.with_suffix('.responses') start_index = -1 if os.path.exists(last_index_filename): with open(last_index_filename, 'r') as f: content = f.read().strip() if content: start_index = int(content) print('resuming from', start_index) messages = [] with open(input_filename, 'r') as f: for line in f: line = line.strip() if line: messages.append(json.loads(line)) with open(output_filename, 'a') as f: for i, message in enumerate(messages): if i <= start_index: continue response_data = play(message, api_key) print(response_data, file=f, flush=True) print(response_data, flush=True) with open(last_index_filename, 'w') as idx_file: idx_file.write(str(i)) return output_filename def replay_list(input_filename: str | Path, api_key=os.environ["OPENAI_API_KEY"]) -> Path: input_filename = Path(input_filename) last_index_filename = input_filename.with_suffix('.state') output_filename = input_filename.with_suffix('.responses') output2_filename = input_filename.with_suffix('.responses2') if output2_filename.exists(): return output2_filename with open(input_filename) as f: with open(output_filename) as o: with open(output2_filename, 'w') as o2: for line, response in zip(f, read_json_and_xml(o)): line = line.strip() message = json.loads(line) if isinstance(response, dict): # good response print(json.dumps(response, ensure_ascii=False), file=o2) else: # bad response: try again response_data = play(message, api_key) response = json.loads(response_data) response_data = json.dumps(response, ensure_ascii=False) print(response_data, file=o2, flush=True) print(response_data, flush=True) return output2_filename if __name__ == '__main__': input_data = sys.stdin.read() message = json.loads(input_data) print(play(message))