diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index fc2cf909..551c6d81 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -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 }} diff --git a/packages/googlecloud/functions/getanswer/main.py b/packages/googlecloud/functions/getanswer/main.py index 61618a14..76b315a0 100644 --- a/packages/googlecloud/functions/getanswer/main.py +++ b/packages/googlecloud/functions/getanswer/main.py @@ -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. 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` . - Note: - For more information on how Flask integrates with Cloud - Functions, see the `Writing HTTP functions` page. - """ # 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) diff --git a/packages/googlecloud/functions/getanswer/requirements.txt b/packages/googlecloud/functions/getanswer/requirements.txt index 06fb9b67..8f3c1ae5 100644 --- a/packages/googlecloud/functions/getanswer/requirements.txt +++ b/packages/googlecloud/functions/getanswer/requirements.txt @@ -13,4 +13,5 @@ tiktoken faiss-cpu wikipedia pandas -tabulate \ No newline at end of file +tabulate +supabase_py \ No newline at end of file diff --git a/packages/web/components/NewQuery.tsx b/packages/web/components/NewQuery.tsx index acae16bc..abf046ab 100644 --- a/packages/web/components/NewQuery.tsx +++ b/packages/web/components/NewQuery.tsx @@ -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 = { + old: T; + new: T; +}; - return ( - - ); -} 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) => { + if (payload.new.id === card.id) { + setCard((prevCard) => ({ ...prevCard, ...payload.new })); + } + }) + .subscribe(); + + return () => { + channel.unsubscribe(); + }; + }, [card]); + + const submitQuery = async (e?: React.FormEvent) => { e?.preventDefault(); - if (query.length <= 10) return; - + const startedProcessingAt = Date.now(); setIsProcessing(true); const newCard = await insertSupabaseCard();