xiaoxx970 / chatgpt-in-terminal

Use ChatGPT in terminal
MIT License
201 stars 27 forks source link

重构代码以适用于外部调用模块 #43

Open xiaoxx970 opened 1 year ago

xiaoxx970 commented 1 year ago

使用效果(以 claude API 为例):

import anthropic
from gpt_term import Term

api_key = "xxx"

class ClaudeTerm(Term):
    def __init__(self, api_key):
        super().__init__(api_key) 
        self.model = 'claude-v1.3-100k'
        self.c = anthropic.Client(api_key)
        self.count_tokens = anthropic.count_tokens

    def get_claude_prompt(self):
        # 转换 {"role": "user|assistant", "content": message} 到 user: message assistant: message
        claude_prompt = ""
        for message in self.messages:
            claude_prompt += (": ").join(message.values()) + '\n'
        return claude_prompt

    def send_request(self, data):
        # 重构send_request函数来返回claude的response
        response = self.c.completion_stream(
            prompt=self.get_claude_prompt(),
            stop_sequences=[anthropic.HUMAN_PROMPT],
            max_tokens_to_sample=200,
            model=data["model"],
            stream=data["stream"],
        )
        return response

    def process_stream_response(self, response):
        for data in response:
            yield data

claude_term = ClaudeTerm(api_key)
claude_term.run()

不知不觉写了好多,原则就是通过重构 gpt_term 中负责终端交互的类能复用这个终端。

至于“负责终端交互的类(Term)”,就需要从现有的代码抽取出来,保证最小功能,包括最小的斜杠命令。

Lemon-2333 commented 1 year ago

好耶!欢呼!