1
0

Persist message history in chatbot

This commit is contained in:
vlad 2024-10-09 11:20:20 -07:00
parent f1c5597025
commit 1b9130c4a5

View File

@ -15,9 +15,37 @@ class GameInterface:
scrot = subprocess.run(['scrot', '-'], capture_output = True)
return scrot.stdout
class ChatBot:
def __init__(self):
self.api = OpenAI(api_key = os.environ['OPENAI_KEY'])
self.message_history = []
def prompt(self, text, image=None):
message = {
"role": "user",
"content": [ {"type": "text", "text": text} ],
}
if image:
image64 = base64.b64encode(image).decode('utf-8')
image_content_part = {"type": "image_url", "image_url": { "url": f"data:image/png;base64,{image64}" } }
message['content'].append(image_content_part)
self.message_history.append(message)
response = self.api.chat.completions.create(
model="gpt-4o-mini",
messages=self.message_history
)
response_message = response.choices[0].message.content
self.message_history.append( {
"role": "assistant",
"content": [ {"type": "text", "text": response_message} ],
})
return response_message
app = Flask(__name__)
openai_client = OpenAI(api_key = os.environ['OPENAI_KEY'])
game = GameInterface()
chatbot = ChatBot()
@app.route('/')
def index():
@ -35,20 +63,18 @@ def click(x, y):
@app.route('/ask-for-next-move')
def nextmove():
screenshot = game.screenshot()
screenshot64 = base64.b64encode(screenshot).decode('utf-8')
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[ {
"role": "user",
"content": [
{"type": "text", "text": "we're playing Into the Breach. Describe the state of the board. Then tell me the best moves for our mechs to make."},
{"type": "image_url", "image_url": { "url": f"data:image/png;base64,{screenshot64}", }, },
],
} ]
return chatbot.prompt(
text = "we're playing Into the Breach. Describe the state of the board. Then tell me the best moves for our mechs to make.",
image = screenshot
)
return response.choices[0].message.content
@app.route('/promp-in-context')
def prompt():
screenshot = game.screenshot()
return chatbot.prompt(
text = "we're playing Into the Breach. Describe the state of the board. Then tell me the best moves for our mechs to make.",
image = screenshot
)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)