|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- encoding: utf-8 -*- |
| 3 | +""" |
| 4 | +@Description:gpt.py |
| 5 | +@Date :2023/03/31 |
| 6 | +@Author :xhunmon |
| 7 | +@Mail :xhunmon@126.com |
| 8 | +""" |
| 9 | + |
| 10 | +import time |
| 11 | +from datetime import datetime |
| 12 | + |
| 13 | +from utils import * |
| 14 | + |
| 15 | + |
| 16 | +class Gpt(object): |
| 17 | + func_ui_print = None |
| 18 | + |
| 19 | + def __init__(self, config: Config): |
| 20 | + self.session = [] |
| 21 | + self.api_prompt = [] |
| 22 | + self.update_config(config) |
| 23 | + self.content = "" |
| 24 | + self.is_change = False |
| 25 | + self.is_finish = True |
| 26 | + gpt_t = threading.Thread(target=self.start) |
| 27 | + gpt_t.setDaemon(True) |
| 28 | + gpt_t.start() |
| 29 | + |
| 30 | + def update_config(self, config: Config): |
| 31 | + self.cfg = config |
| 32 | + self.api_key = self.cfg.api_key |
| 33 | + self.api_base = self.cfg.api_base |
| 34 | + self.api_model = self.cfg.model |
| 35 | + self.api_stream = self.cfg.stream |
| 36 | + self.api_response = self.cfg.response |
| 37 | + self.proxy = self.cfg.proxy |
| 38 | + openai.api_key = self.api_key |
| 39 | + if self.api_base: |
| 40 | + openai.api_base = self.api_base |
| 41 | + openai.proxy = self.proxy |
| 42 | + |
| 43 | + def start(self): |
| 44 | + while True: |
| 45 | + if self.is_finish: |
| 46 | + while not self.is_change: |
| 47 | + time.sleep(0.3) |
| 48 | + self.print("\nMY:\n{}".format(self.content)) |
| 49 | + self.print("\nGPT:\n") |
| 50 | + self.is_change = False |
| 51 | + self.is_finish = False |
| 52 | + self.handle_input(self.content) |
| 53 | + time.sleep(1) |
| 54 | + |
| 55 | + def print(self, content): |
| 56 | + Gpt.func_ui_print(content) |
| 57 | + |
| 58 | + def query_openai_stream(self, data: dict) -> str: |
| 59 | + messages = [] |
| 60 | + messages.extend(self.api_prompt) |
| 61 | + messages.extend(data) |
| 62 | + answer = "" |
| 63 | + try: |
| 64 | + response = openai.ChatCompletion.create( |
| 65 | + model=self.api_model, |
| 66 | + messages=messages, |
| 67 | + stream=True) |
| 68 | + for part in response: |
| 69 | + finish_reason = part["choices"][0]["finish_reason"] |
| 70 | + if "content" in part["choices"][0]["delta"]: |
| 71 | + content = part["choices"][0]["delta"]["content"] |
| 72 | + answer += content |
| 73 | + self.print(content) |
| 74 | + elif finish_reason: |
| 75 | + pass |
| 76 | + |
| 77 | + except KeyboardInterrupt: |
| 78 | + self.print("Canceled") |
| 79 | + except openai.error.OpenAIError as e: |
| 80 | + self.print("OpenAIError:{}".format(e)) |
| 81 | + answer = "" |
| 82 | + return answer |
| 83 | + |
| 84 | + def content_change(self, content: str): |
| 85 | + if not content: |
| 86 | + return |
| 87 | + if self.content != content: |
| 88 | + self.content = content |
| 89 | + self.is_change = True |
| 90 | + |
| 91 | + def handle_input(self, content: str): |
| 92 | + if not content: |
| 93 | + return |
| 94 | + self.is_finish = False |
| 95 | + self.session.append({"role": "user", "content": content}) |
| 96 | + if self.api_stream: |
| 97 | + answer = self.query_openai_stream(self.session) |
| 98 | + else: |
| 99 | + answer = self.query_openai(self.session) |
| 100 | + if not answer: |
| 101 | + self.session.pop() |
| 102 | + elif self.api_response: |
| 103 | + self.session.append({"role": "assistant", "content": answer}) |
| 104 | + if answer: |
| 105 | + try: |
| 106 | + if self.cfg.folder and not os.path.exists(self.cfg.folder): |
| 107 | + os.makedirs(self.cfg.folder) |
| 108 | + wfile = os.path.join(self.cfg.folder, "gpt.md" if self.cfg.repeat else "gpt_{}.md".format( |
| 109 | + datetime.now().strftime("%Y%m%d%H%M:%S"))) |
| 110 | + if self.cfg.repeat: |
| 111 | + with open(wfile, mode='a', encoding="utf-8") as f: |
| 112 | + f.write("MY:\n{}\n".format(content)) |
| 113 | + f.write("\nGPT:\n{}\n\n".format(answer)) |
| 114 | + f.close() |
| 115 | + else: |
| 116 | + with open(wfile, mode='w', encoding="utf-8") as f: |
| 117 | + f.write("MY:\n{}\n".format(content)) |
| 118 | + f.write("\nGPT:{}".format(answer)) |
| 119 | + f.close() |
| 120 | + except Exception as e: |
| 121 | + self.print("Write error: {} ".format(e)) |
| 122 | + self.is_finish = True |
| 123 | + |
| 124 | + def query_openai(self, data: dict) -> str: |
| 125 | + messages = [] |
| 126 | + messages.extend(self.api_prompt) |
| 127 | + messages.extend(data) |
| 128 | + try: |
| 129 | + response = openai.ChatCompletion.create( |
| 130 | + model=self.api_model, |
| 131 | + messages=messages |
| 132 | + ) |
| 133 | + content = response["choices"][0]["message"]["content"] |
| 134 | + self.print(content) |
| 135 | + return content |
| 136 | + except openai.error.OpenAIError as e: |
| 137 | + self.print("OpenAI error: {} ".format(e)) |
| 138 | + return "" |
0 commit comments