|
2 | 2 | // https://deno.land/manual/getting_started/setup_your_environment |
3 | 3 | // This enables autocomplete, go to definition, etc. |
4 | 4 |
|
5 | | -import { serve } from "https://deno.land/std@0.168.0/http/server.ts" |
| 5 | +import "https://deno.land/x/xhr@0.3.0/mod.ts" |
| 6 | +import { getLogger } from "https://deno.land/std@0.183.0/log/mod.ts" |
| 7 | +import { serve } from "https://deno.land/std@0.183.0/http/server.ts" |
| 8 | +import { Configuration, OpenAIApi } from "https://esm.sh/openai@3.2.1" |
6 | 9 |
|
7 | | -console.log("Hello from Functions!") |
| 10 | +const configuration = new Configuration({ |
| 11 | + apiKey: Deno.env.get("OPENAI_API_KEY"), |
| 12 | +}); |
| 13 | +const openai = new OpenAIApi(configuration); |
8 | 14 |
|
9 | 15 | serve(async (req) => { |
10 | | - const { name } = await req.json() |
11 | | - const data = { |
12 | | - message: `Hello ${name}!`, |
13 | | - } |
| 16 | + const { query } = await req.json(); |
| 17 | + try { |
| 18 | + const response = await openai.createCompletion({ |
| 19 | + model: "text-davinci-003", |
| 20 | + prompt: query, |
| 21 | + max_tokens: 256, |
| 22 | + temperature: 0, |
| 23 | + }); |
| 24 | + |
| 25 | + const { |
| 26 | + data: { |
| 27 | + id, |
| 28 | + choices: [{ text }] |
| 29 | + }, |
| 30 | + } = response; |
14 | 31 |
|
15 | | - return new Response( |
16 | | - JSON.stringify(data), |
17 | | - { headers: { "Content-Type": "application/json" } }, |
18 | | - ) |
| 32 | + return new Response( |
| 33 | + JSON.stringify({ id, text }), |
| 34 | + { headers: { "Content-Type": "application/json" } }, |
| 35 | + ) |
| 36 | + } catch (error) { |
| 37 | + const logger = getLogger() |
| 38 | + logger.error(error) |
| 39 | + |
| 40 | + return new Response( |
| 41 | + JSON.stringify({ error }), |
| 42 | + { headers: { "Content-Type": "application/json" } }, |
| 43 | + ) |
| 44 | + } |
19 | 45 | }) |
20 | 46 |
|
21 | 47 | // To invoke: |
22 | 48 | // curl -i --location --request POST 'http://localhost:54321/functions/v1/' \ |
23 | 49 | // --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0' \ |
24 | 50 | // --header 'Content-Type: application/json' \ |
25 | | -// --data '{"name":"Functions"}' |
| 51 | +// --data '{"query":"What is Supabase?"}' |
0 commit comments