diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..cbac569 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "deno.enable": true +} diff --git a/code/supabase/functions/hello-anilog/index.ts b/code/supabase/functions/hello-anilog/index.ts index caaaaf0..a2706ec 100644 --- a/code/supabase/functions/hello-anilog/index.ts +++ b/code/supabase/functions/hello-anilog/index.ts @@ -1,16 +1,48 @@ import "jsr:@supabase/functions-js/edge-runtime.d.ts"; - -console.log("Hello from Functions!"); +import OpenAI from "https://deno.land/x/openai@v4.69.0/mod.ts"; Deno.serve(async (req) => { - const { name } = await req.json(); - const data = { - message: `Hello ${name}!`, - }; - - return new Response(JSON.stringify(data), { - headers: { "Content-Type": "application/json" }, - }); + try { + const { imageUrl } = await req.json(); + + const openai = new OpenAI({ + apiKey: Deno.env.get("OPENAI_KEY"), + }); + + let assistantId = "asst_86rYwd4L2Ux25rWec1mRSEoY"; + + const thread = await openai.beta.threads.create({ + messages: [ + { + role: "user", + content: imageUrl, + }, + ], + }); + + const run = await openai.beta.threads.runs.createAndPoll(thread.id, { + assistant_id: assistantId, + }); + + if (run.status == "completed") { + const messages = await openai.beta.threads.messages.list(thread.id); + const assistantResponse = messages.data[0]?.content[0].text.value; + + return new Response(assistantResponse, { + headers: { "Content-Type": "application/json" }, + }); + } + } catch (error) {} + + return new Response( + JSON.stringify({ + error: "Unknown error", + }), + { + headers: { "Content-Type": "application/json" }, + status: 500, + } + ); }); /* To invoke locally: @@ -21,6 +53,6 @@ Deno.serve(async (req) => { curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/hello-anilog' \ --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0' \ --header 'Content-Type: application/json' \ - --data '{"name":"Functions"}' + --data '{"imageUrl": "https:example.com"}' */ diff --git a/code/supabase/readme.md b/code/supabase/readme.md index 4f86bb2..70252b5 100644 --- a/code/supabase/readme.md +++ b/code/supabase/readme.md @@ -1,3 +1,17 @@ # Supabase Edge Functions +Copy the .env.example and fill in the OPENAI_KEY +`cp .env.example .env` + To start locally, Docker Desktop must be installed. The cloud functions can be started by running `npx supabase start` and are accessible at `http://127.0.0.1:54321/functions/v1/[function-name]` + +## Update env varibales in production + +Login to your supabase account +`npx supabase login` + +Sync the .env file to production +`npx supabase secrets set --env-file .env` + +Check the synced env keys +`npx supabase secrets list`