Certainly! Let's start with the full backend code, which includes handling the getCurrentTime function when the status of the Assistant's Run is "requires_action". This backend is implemented in Python using Flask.
Full Backend Code
from flask import Flask, request, jsonify
import openai
from datetime import datetime
# Initialize Flask app
app = Flask(__name__)
# OpenAI API setup
openai.api_key = "YOUR_API_KEY"
# Function to create an assistant with custom functions
def create_assistant():
assistant = openai.Assistant.create(
instructions="I can tell the current time. Ask me what time is it.",
model="gpt-4-1106-preview",
tools=[
{
"name": "getCurrentTime",
"description": "Get the current time",
"parameters": {"type": "object", "properties": {}, "required": []}
}
]
)
return assistant
# Python function to get current time
def get_current_time():
return datetime.now().strftime("%H:%M:%S")
# Function to process the message with the Assistant
def process_with_assistant(user_id, message):
# Here, implement the logic to send the message to the Assistant and get the response
# This should include handling of the Run status and required actions
# Placeholder for actual implementation
pass
# Function to continue processing the Run after submitting tool outputs
def continue_processing_run(thread_id, run_id):
# Here, fetch the updated Run status and continue the interaction
# Placeholder for actual implementation
pass
# Function to submit tool outputs
def submit_tool_outputs(thread_id, run_id, tool_call_id, output):
run = openai.Thread.runs.submit_tool_outputs(
thread_id=thread_id,
run_id=run_id,
tool_outputs=[{"tool_call_id": tool_call_id, "output": output}]
)
return run
# Endpoint to receive and respond to user messages
@app.route("/message", methods=["POST"])
def receive_message():
data = request.json
user_id = data.get("user_id")
message = data.get("message")
# Process the message with the Assistant
response = process_with_assistant(user_id, message)
if response.status == "requires_action":
for action in response.required_action.submit_tool_outputs.tool_calls:
if action.function.name == "getCurrentTime":
current_time = get_current_time()
submit_tool_outputs(response.thread_id, response.id, action.id, current_time)
response = continue_processing_run(response.thread_id, response.id)
return jsonify({"response": response.choices[0].text.strip()})
if __name__ == "__main__":
app.run(debug=True, port=5000)
This backend code integrates with OpenAI's API, handling user messages and executing the getCurrentTime function as required.
Full Frontend Code
The frontend is a simple HTML page with JavaScript to facilitate user interaction with the chatbot.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GPT Assistant Chat</title>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
#chat { height: 300px; overflow: auto; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; }
#userInput { width: 80%; }
#sendButton { width: 19%; }
</style>
</head>
<body>
<div id="chat"></div>
<input type="text" id="userInput">
<button id="sendButton" onclick="sendMessage()">Send</button>
<script>
function sendMessage() {
var userInput = document.getElementById("userInput");
var message = userInput.value;
userInput.value = '';
updateChat('You', message);
fetch('/message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: 'unique_user_id', message: message })
})
.then(response => response.json())
.then(data => {
updateChat('Assistant', data.response);
})
.catch(error => console.error('Error:', error));
}
function updateChat(sender, message) {
var chat = document.getElementById("chat");
var messageElement = document.createElement("div");
messageElement.textContent = sender + ": " + message;
chat.appendChild(messageElement);
}
</script>
</body>
</html>
This frontend code provides a basic chat interface that interacts with the backend to send user messages and display responses.
To complete the setup:
- Deploy the backend Flask app to a server.
- Host the HTML file on a