Skip to content

Commit

Permalink
feat(nx-dev): move supabase analytics to edge
Browse files Browse the repository at this point in the history
  • Loading branch information
mandarini committed Aug 28, 2023
1 parent 56e13fe commit 27ce147
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 38 deletions.
24 changes: 0 additions & 24 deletions nx-dev/data-access-ai/src/lib/data-access-ai.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,3 @@
// based on:
// https://github.com/supabase-community/nextjs-openai-doc-search/blob/main/pages/api/vector-search.ts

import {
PostgrestSingleResponse,
SupabaseClient,
createClient,
} from '@supabase/supabase-js';
import { CreateCompletionResponseUsage } from 'openai';
import { MAX_HISTORY_LENGTH, ChatItem } from '@nx/nx-dev/util-ai';
import { getChatResponse } from './utils';
Expand Down Expand Up @@ -66,19 +58,3 @@ export function resetHistory() {
export function getHistory(): ChatItem[] {
return chatFullHistory;
}

//TODO(katerina): move this to the edge function
export async function sendFeedbackAnalytics(feedback: {}): Promise<
PostgrestSingleResponse<null>
> {
return {} as any;
// return supabaseClient.from('feedback').insert(feedback);
}

//TODO(katerina): move this to the edge function
export async function sendQueryAnalytics(queryInfo: {}) {
// const { error } = await supabaseClient.from('user_queries').insert(queryInfo);
// if (error) {
// console.error('Error storing the query info in Supabase: ', error);
// }
}
16 changes: 15 additions & 1 deletion nx-dev/data-access-ai/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export function getChatResponse(
query: string,
chatFullHistory: ChatItem[],
aiResponse?: string
) {
): Promise<Response> {
return fetch('/api/query-ai-handler', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
Expand All @@ -40,3 +40,17 @@ export function getChatResponse(
}),
});
}

export function sendAnalytics(
table: string,
analyticsData: { [key: string]: string | number | null }
): Promise<Response> {
return fetch('/api/ai-analytics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
table,
analyticsData,
}),
});
}
9 changes: 4 additions & 5 deletions nx-dev/feature-ai/src/lib/feed-container.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import {
ChatItem,
getProcessedHistory,
queryAi,
sendFeedbackAnalytics,
sendQueryAnalytics,
sendAnalytics,
} from '@nx/nx-dev/data-access-ai';
import { sendCustomEvent } from '@nx/nx-dev/feature-analytics';
import { RefObject, useEffect, useRef, useState } from 'react';
Expand All @@ -12,6 +10,7 @@ import { Feed } from './feed/feed';
import { LoadingState } from './loading-state';
import { Prompt } from './prompt';
import { formatMarkdownSources } from './utils';
import { ChatItem } from '@nx/nx-dev/util-ai';

interface LastQueryMetadata {
sources: string[];
Expand Down Expand Up @@ -86,7 +85,7 @@ export function FeedContainer(): JSX.Element {
query,
...aiResponse.usage,
});
sendQueryAnalytics({
sendAnalytics('user_queries', {
action: 'ai_query',
query,
...aiResponse.usage,
Expand All @@ -109,7 +108,7 @@ export function FeedContainer(): JSX.Element {
? JSON.stringify(lastQueryMetadata.sources)
: 'Could not retrieve last answer sources',
});
sendFeedbackAnalytics({
sendAnalytics('feedback', {
action: 'evaluation',
result: answer ? answer.content : 'Could not retrieve the answer',
query: question ? question.content : 'Could not retrieve the question',
Expand Down
42 changes: 42 additions & 0 deletions nx-dev/nx-dev/pages/api/ai-analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { checkEnvVariables } from '@nx/nx-dev/util-ai';
import { SupabaseClient, createClient } from '@supabase/supabase-js';
import { NextRequest } from 'next/server';

const supabaseUrl = process.env['NX_NEXT_PUBLIC_SUPABASE_URL'];
const supabaseServiceKey = process.env['NX_SUPABASE_SERVICE_ROLE_KEY'];
export const config = {
runtime: 'edge',
};

export default async function handler(request: NextRequest) {
checkEnvVariables('not-needed', supabaseUrl, supabaseServiceKey);
const { table, analyticsData } = await request.json();

const supabaseClient: SupabaseClient<any, 'public', any> = createClient(
supabaseUrl as string,
supabaseServiceKey as string
);

try {
const result = await supabaseClient.from(table).insert(analyticsData);

return new Response(JSON.stringify(result), {
status: 200,
headers: {
'content-type': 'application/json',
},
});
} catch (e) {
return new Response(
JSON.stringify({
error: 'Error saving feedback in Supabase.',
}),
{
status: 500,
headers: {
'content-type': 'application/json',
},
}
);
}
}
15 changes: 7 additions & 8 deletions nx-dev/nx-dev/pages/api/query-ai-handler.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// based on:
// https://github.com/supabase-community/nextjs-openai-doc-search/blob/main/pages/api/vector-search.ts

import { NextRequest } from 'next/server';
import {
ApplicationError,
Expand All @@ -23,7 +26,6 @@ import GPT3Tokenizer from 'gpt3-tokenizer';
const supabaseUrl = process.env['NX_NEXT_PUBLIC_SUPABASE_URL'];
const supabaseServiceKey = process.env['NX_SUPABASE_SERVICE_ROLE_KEY'];
const openAiKey = process.env['NX_OPENAI_KEY'];
let supabaseClient: SupabaseClient<any, 'public', any>;

export const config = {
runtime: 'edge',
Expand All @@ -33,13 +35,10 @@ export default async function handler(request: NextRequest) {
checkEnvVariables(openAiKey, supabaseUrl, supabaseServiceKey);
const { query, aiResponse, chatFullHistory } = await request.json();

// This does not make sense since Edge functions are containerized?
if (!supabaseClient) {
supabaseClient = createClient(
supabaseUrl as string,
supabaseServiceKey as string
);
}
const supabaseClient: SupabaseClient<any, 'public', any> = createClient(
supabaseUrl as string,
supabaseServiceKey as string
);

try {
if (!query) {
Expand Down

0 comments on commit 27ce147

Please sign in to comment.