Simple Flask App

Here we demonstrate how a simple Flask app with three endpoints can provide a personalized experience.

from flask import Flask, request, jsonify
from firstbatch import UserAction, Signal, FirstBatch, Config, Pinecone, AlgorithmLabel
import os
import pinecone

app = Flask(__name__)

config = Config(batch_size=20)
personalized = FirstBatch(api_key=os.environ["FIRSTBATCH_API_KEY"], config=config) # os.environ["FIRSTBATCH_API_KEY"]
pinecone.init(api_key=api_key, environment=env)
index = pinecone.Index("your_index")
personalized.add_vdb("my_db", Pinecone(index, embedding_size=1536))


@app.route("/api/new_session", methods=["POST"])
def new_session():
    data = request.json
    session_id = data["session_id"]
    if session_id is None or session_id == "":
        session = personalized.session(algorithm=AlgorithmLabel.CONTENT_CURATION, vdbid="my_db")
    else:
        session = personalized.session(session_id=session_id, algorithm=AlgorithmLabel.CONTENT_CURATION, vdbid="my_db")

    return jsonify(session.to_dict())


@app.route("/api/add_signal", methods=["POST"])
def add_signal():
    data = request.json
    session = data["session"]
    action = data["action"]
    content_id = data["content_id"]  # id of liked content

    signal = Signal.LIKE if action == "LIKE" else Signal.DEFAULT

    personalized.add_signal(session, UserAction(signal), content_id)

    return jsonify({"status": "success"})


@app.route("/api/new_batch", methods=["POST"])
def new_batch():
    data = request.json
    session = data["session"]
    ids, batch = personalized.batch(session)

    return jsonify({"ids": ids, "data": [b.data for b in batch]})


if __name__ == "__main__":
    app.run()

Last updated