将以上代码分成外置类调用
时间: 2024-05-10 21:19:23 浏览: 8
这里提供一个简单的示例,将以上代码封装成一个外置类 `Chatbot`,通过调用类的方法来与AI进行对话。
```python
import openai
import re
class Chatbot:
def __init__(self, api_key, engine_id):
self.api_key = api_key
self.engine_id = engine_id
openai.api_key = api_key
def ask(self, question, chat_history=None):
prompt = self._build_prompt(question, chat_history)
response = openai.Completion.create(
engine=self.engine_id,
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.7,
)
message = response.choices[0].text.strip()
return message
def _build_prompt(self, question, chat_history=None):
if chat_history is None:
chat_history = []
prompt = f'The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.\n\n' \
+ 'Human: ' + question + '\n'
for history in chat_history:
prompt += 'AI: ' + history['message'] + '\n' \
+ 'Human: ' + history['question'] + '\n'
return prompt
```
使用示例:
```python
api_key = "your_api_key"
engine_id = "your_engine_id"
chatbot = Chatbot(api_key, engine_id)
chat_history = []
while True:
user_input = input("User: ")
if user_input.lower() in ['quit', 'exit', 'bye']:
print('Chatbot: Goodbye!')
break
chat_history.append({'message': chatbot.ask(user_input, chat_history), 'question': user_input})
print('Chatbot:', chat_history[-1]['message'])
```
注:以上代码仅供参考,具体实现可以根据需求进行修改。