Skip to the content.

Frostbyte blog

The process of building our website, my contributions

Purpose of our group’s program:

  • Create a social media site that connects people who are interested in camping and national parks.

    Purpose of your individual feature(s)

  • My feature: Integrate Gemini AI into our website so that users can interact and receive responses about camping.

Using frontend show API request and present API response. (live demo)

  • message through frontend, show terminal, response will be returned from the backend.

    Using postman to show raw API request and RESTful response (error code(s) and JSON)

  • put in requests from postman, show what happens when there is an error

    Using db_init, db_restore, db_backup to show tester data creation and data recovery.

  • after the files are run, a table is created and data will be recovered

    List requests. Use of list, dictionaries and database. Code descriptions of area where you work with list (rows) and dictionaries (columns) of the database.

  • The model file uses list, dictionaries and creates a database. A row is created by the dictionary, and by putting in different categories into a list under that dictionary, it creates a row

    Discuss formatting response data (JSON) from API into DOM

  • a request is sent into the back end, data is read. this data is changed by JSON to DOM which is shown by the front end.

    Discuss queries from database where you extract a Python List (rows). Mention how these queries are provide by a 3rd. party library.

  • message = AIMessage.query.get(message_id)
  • calls to my table for a message id

Discuss methods in “class” you created to work with columns (create, read, update, delete)

  • Create: inputting a message
  • Read: showing the message, chatbot responds
  • Update: updating a message, able to change the text
  • Delete: delete a message

    Algorithmic code request. Show the definition of code blocks to handle a request.

  • receive request from the frontend, process input, make a response

    Discuss API class (code block) you used to perform get, post, put, and delete methods.

  • model code

    Discuss a method/procedure in class that contains sequencing, selection, and iteration.

  • sequencing: going in order
    • example: making the dictionary and lists
  • selection: testing conditions
    • example: if not
  • iteration: constantly happening
    • example: updating message history

      Discuss the parameters (body of request) and return type (jasonify) of the function.

  • user input as a string
  • returns AI messages as JSON

    Call to Algorithm request. Show the definition of code block to make a request.

  • def generate_ai_response

    Discuss the call/request to the method with Algorithm (fetch to endpoint).

  • from front end, fetch to /api/chatbot
  • fetches JSON

    Discuss the return/response from the method with Algorithm (fetch) and how you handle data.

  • return with JSON using class chatbot

    Show how changing data or method triggers a different response, specifically normal conditions and error conditions.

College Board Requirements Met:

  • Use of HTTP and RESTful APIs: I created the gemini API that interacts with the backend using GET, POST, PUT, and DELETE functions (see below). This ties into our camping page by providing information about camping when the user interacts with the AI.
  • Performance Optimization: I index database records for faster lookups (AIMessage.query.get(message_id))
  • Monitoring and Logging: Logging occurs through the console log, where I can see errors or success codes that I can use to debug or check if my code is being processed correctly.
  • Security and Authentication: Each action in my API requires the authentication token, which means the user must be logged in to be able to access my features.

A bit of code about college board requirements class Chatbot(Resource): @token_required()

def __init__(self):
    self.history = []
    self.chat_session = model.start_chat(history=self.history)  # Persistent session

def generate_ai_response(self, user_input):
    """Generates a response from the Google Generative AI model."""
    try:
        response = self.chat_session.send_message(user_input)
        return response.text.rstrip("\n")
    except Exception as e:
        print(f"Error generating AI response: {str(e)}")
        return "Sorry, I couldn't process that."

def update_history(self, role: str, message: str):
    """Update the conversation history and save messages to the database."""
    if len(self.history) >= self.MAX_HISTORY:
        self.history.pop(0)  # Maintain a maximum history length
    self.history.append({"role": role, "parts": [message]})

    ai_message = AIMessage(
        message=message,
        author=role,
        category="response" if role == "assistant" else "user"
    )
    ai_message.create()
    return ai_message.id  # Return the ID of the created message

def post(self):
    """Handles POST requests to send a message and get a response."""
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "Invalid JSON"}), 400

        user_input = data.get("user_input")
        if not user_input:
            return jsonify({"error": "User input is required"}), 400

        # Save the user's message to the database and get its ID
        user_message = AIMessage(message=user_input, author="user", category="user_message")
        db.session.add(user_message)
        db.session.commit()
        user_message_id = user_message.id  # Get the auto-generated ID

        # Generate AI response using Google Generative AI
        response_text = self.generate_ai_response(user_input)

        # Save the AI's response to the database and get its ID
        ai_message = AIMessage(message=response_text, author="assistant", category="ai_response")
        db.session.add(ai_message)
        db.session.commit()
        ai_message_id = ai_message.id  # Get the auto-generated ID

        return jsonify({
            "user_message_id": user_message_id,  # ID of the user's message
            "ai_message_id": ai_message_id,  # ID of the AI's response
            "user_input": user_input,
            "model_response": response_text
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def put(self):
    """Handles PUT requests to update an existing message by ID."""
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "Invalid JSON"}), 400

        message_id = data.get("id")
        new_message = data.get("user_input")

        if not message_id or not new_message:
            return jsonify({"error": "Message ID and new message content are required"}), 400

        # Find the message by ID
        message = AIMessage.query.get(message_id)
        if not message:
            return jsonify({"error": "Message not found"}), 404

        # Update the message content
        message.message = new_message
        db.session.commit()

        return jsonify({"message": "Message updated successfully"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def delete(self):
    """Handles DELETE requests to delete a message by ID."""
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "Invalid JSON"}), 400

        message_id = data.get("id")
        if not message_id:
            return jsonify({"error": "Message ID is required"}), 400

        # Find the message by ID
        message = AIMessage.query.get(message_id)
        if not message:
            return jsonify({"error": "Message not found"}), 404

        # Delete the message
        db.session.delete(message)
        db.session.commit()

        return '', 204  # Return a 204 No Content to indicate successful deletion
    except Exception as e:
        return jsonify({"error": str(e)}), 500 </code>