Skip to content

Commit

Permalink
Merge pull request #129 from eye-on-surveillance/AI/request-flow
Browse files Browse the repository at this point in the history
Ai/fix-request flow
ayyubibrahimi authored Nov 7, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
2 parents 9784905 + 92393f1 commit 70bebea
Showing 4 changed files with 55 additions and 27 deletions.
4 changes: 3 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -50,4 +50,6 @@ jobs:
--entry-point=getanswer \
--trigger-http \
--allow-unauthenticated \
--set-env-vars OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY_STAGING }}
--set-env-vars OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY_STAGING }},\
SUPABASE_URL=${{ secrets.SUPABASE_URL_STAGING }},\
SUPABASE_SERVICE_KEY=${{ secrets.SUPABASE_SERVICE_KEY_STAGING }}
26 changes: 20 additions & 6 deletions packages/googlecloud/functions/getanswer/main.py
Original file line number Diff line number Diff line change
@@ -4,9 +4,11 @@

import google.cloud.logging
import functions_framework
from supabase_py import create_client

from helper import parse_field, get_dbs
from inquirer import answer_query
import os

logging_client = google.cloud.logging.Client()
logging_client.setup_logging()
@@ -15,6 +17,16 @@

db_general, db_in_depth, voting_roll_df = get_dbs()

# Setup Supabase client
supabase_url = os.environ.get("SUPABASE_URL_STAGING")
supabase_key = os.environ.get("SUPABASE_SERVICE_KEY_STAGING")
supabase = create_client(supabase_url, supabase_key)

def update_supabase(response):
# Assume you have a table named 'answers' with a column named 'answer'
response = supabase.table('cards').insert({'response': response}).execute()
if response.error:
logging.error(f"Failed to update Supabase: {response.error}")

@functions_framework.http
def getanswer(request):
@@ -23,13 +35,9 @@ def getanswer(request):
request (flask.Request): The request object.
<https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
Returns:
The response text, or any set of values that can be turned into a
A success message and status, or any set of values that can be turned into a
Response object using `make_response`
<https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
Note:
For more information on how Flask integrates with Cloud
Functions, see the `Writing HTTP functions` page.
<https://cloud.google.com/functions/docs/writing/http#http_frameworks>
"""
# Set CORS headers for the preflight request
if request.method == "OPTIONS":
@@ -46,6 +54,7 @@ def getanswer(request):

# Set CORS headers for the main request
headers = {"Access-Control-Allow-Origin": "*"}

logging.info(f"getanswer {API_VERSION}")
start = time.time()

@@ -59,12 +68,17 @@ def getanswer(request):
response_type = parse_field(request_json, "response_type")
else:
raise ValueError("Unknown content type: {}".format(content_type))

logging.info("Request parsed")

answer = answer_query(query, response_type, voting_roll_df, db_general, db_in_depth)

# Update Supabase instead of returning the answer to the client
update_supabase(answer)

end = time.time()
elapsed = math.ceil(end - start)
logging.info(f"Completed getanswer in {elapsed} seconds")
print(f"\n\t--------- Completed getanswer in {elapsed} seconds --------\n")
return (answer, 200, headers)

return ("Answer successfully submitted to Supabase", 200, headers)
3 changes: 2 additions & 1 deletion packages/googlecloud/functions/getanswer/requirements.txt
Original file line number Diff line number Diff line change
@@ -13,4 +13,5 @@ tiktoken
faiss-cpu
wikipedia
pandas
tabulate
tabulate
supabase_py
49 changes: 30 additions & 19 deletions packages/web/components/NewQuery.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,20 @@
import { ECardStatus, ECardType, ICard } from "@/lib/api";
import { APP_NAME } from "@/lib/copy";
import { API_NEW_CARD_PATH } from "@/lib/paths";
import { TABLES } from "@/lib/supabase/db";
import { supabase } from "@/lib/supabase/supabaseClient";
import { faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useState } from "react";
import { useCardResults } from "./CardResultsProvider";
import { ABOUT_BETA_PATH } from "@/lib/paths";
import Link from "next/link";
import { useEffect, useState } from "react";
import { supabase } from "@/lib/supabase/supabaseClient"
import { ECardStatus, ECardType, ICard } from "@/lib/api";;

function YouTubeEmbed({ url }: { url: string }) {
const videoId = url.split("v=")[1]?.split("&")[0];
if (!videoId) return null;
type SupabaseRealtimePayload<T = any> = {
old: T;
new: T;
};

return (
<iframe
width="560"
height="315"
src={`https://www.youtube.com/embed/${videoId}`}
frameBorder="0"
title="YouTube Video"
allowFullScreen
></iframe>
);
}

function YouTubeThumbnail({ url }: { url: string }) {
const videoId = url.split("v=")[1]?.split("&")[0];
@@ -127,11 +117,32 @@ export default function NewQuery() {
}
};

useEffect(() => {
if (!card) {
return;
}

const channel = (supabase.channel(`cards:id=eq.${card.id}`) as any)
.on('postgres_changes', {
event: "INSERT",
schema: "public",
}, (payload: SupabaseRealtimePayload<ICard>) => {
if (payload.new.id === card.id) {
setCard((prevCard) => ({ ...prevCard, ...payload.new }));
}
})
.subscribe();

return () => {
channel.unsubscribe();
};
}, [card]);


const submitQuery = async (e?: React.FormEvent<HTMLFormElement>) => {
e?.preventDefault();

if (query.length <= 10) return;

const startedProcessingAt = Date.now();
setIsProcessing(true);
const newCard = await insertSupabaseCard();

0 comments on commit 70bebea

Please sign in to comment.