From ba8d61efbae5da0606d6a0b8f3d1cd9da8b05ce8 Mon Sep 17 00:00:00 2001 From: Harish Mohan Raj Date: Wed, 22 Nov 2023 22:16:53 +0530 Subject: [PATCH] WIP --- src/client/components/ConversationWrapper.tsx | 2 +- src/server/actions.ts | 159 ++++++++++-------- 2 files changed, 91 insertions(+), 70 deletions(-) diff --git a/src/client/components/ConversationWrapper.tsx b/src/client/components/ConversationWrapper.tsx index a0a93df..d7559c3 100644 --- a/src/client/components/ConversationWrapper.tsx +++ b/src/client/components/ConversationWrapper.tsx @@ -102,7 +102,7 @@ export default function ConversationWrapper() { // 2. call backend python server to get agent response setIsLoading(true); const response = await getAgentResponse({ - message: userQuery, + message: payload.conversations, conv_id: payload.conversation_id, }); // 3. add agent response as new conversation in the table diff --git a/src/server/actions.ts b/src/server/actions.ts index bc38b86..751f456 100644 --- a/src/server/actions.ts +++ b/src/server/actions.ts @@ -1,57 +1,67 @@ -import fetch from 'node-fetch'; -import HttpError from '@wasp/core/HttpError.js'; +import fetch from "node-fetch"; +import HttpError from "@wasp/core/HttpError.js"; // import type { RelatedObject } from '@wasp/entities'; -import type { Chat } from '@wasp/entities'; -import type { Conversation } from '@wasp/entities'; -import type { GenerateGptResponse, StripePayment, CreateChat, UpdateConversation, GetAgentResponse } from '@wasp/actions/types'; -import type { StripePaymentResult, OpenAIResponse } from './types'; -import Stripe from 'stripe'; +import type { Chat } from "@wasp/entities"; +import type { Conversation } from "@wasp/entities"; +import type { + GenerateGptResponse, + StripePayment, + CreateChat, + UpdateConversation, + GetAgentResponse, +} from "@wasp/actions/types"; +import type { StripePaymentResult, OpenAIResponse } from "./types"; +import Stripe from "stripe"; const stripe = new Stripe(process.env.STRIPE_KEY!, { - apiVersion: '2022-11-15', + apiVersion: "2022-11-15", }); // WASP_WEB_CLIENT_URL will be set up by Wasp when deploying to production: https://wasp-lang.dev/docs/deploying -const DOMAIN = process.env.WASP_WEB_CLIENT_URL || 'http://localhost:3000'; +const DOMAIN = process.env.WASP_WEB_CLIENT_URL || "http://localhost:3000"; // Python ADS_SERVER_URL -const ADS_SERVER_URL = process.env.ADS_SERVER_URL || 'http://127.0.0.1:9000'; +const ADS_SERVER_URL = process.env.ADS_SERVER_URL || "http://127.0.0.1:9000"; -export const stripePayment: StripePayment = async (_args, context) => { +export const stripePayment: StripePayment = async ( + _args, + context +) => { if (!context.user) { throw new HttpError(401); } - + let customer: Stripe.Customer; const stripeCustomers = await stripe.customers.list({ email: context.user.email!, }); if (!stripeCustomers.data.length) { - console.log('creating customer'); + console.log("creating customer"); customer = await stripe.customers.create({ email: context.user.email!, }); } else { - console.log('using existing customer'); + console.log("using existing customer"); customer = stripeCustomers.data[0]; } - const session: Stripe.Checkout.Session = await stripe.checkout.sessions.create({ - line_items: [ - { - price: process.env.SUBSCRIPTION_PRICE_ID!, - quantity: 1, + const session: Stripe.Checkout.Session = + await stripe.checkout.sessions.create({ + line_items: [ + { + price: process.env.SUBSCRIPTION_PRICE_ID!, + quantity: 1, + }, + ], + mode: "subscription", + success_url: `${DOMAIN}/checkout?success=true`, + cancel_url: `${DOMAIN}/checkout?canceled=true`, + automatic_tax: { enabled: true }, + customer_update: { + address: "auto", }, - ], - mode: 'subscription', - success_url: `${DOMAIN}/checkout?success=true`, - cancel_url: `${DOMAIN}/checkout?canceled=true`, - automatic_tax: { enabled: true }, - customer_update: { - address: 'auto', - }, - customer: customer.id, - }); + customer: customer.id, + }); await context.entities.User.update({ where: { @@ -64,7 +74,7 @@ export const stripePayment: StripePayment = async (_a }); if (!session) { - throw new HttpError(402, 'Could not create a Stripe session'); + throw new HttpError(402, "Could not create a Stripe session"); } else { return { sessionUrl: session.url, @@ -93,11 +103,11 @@ export const generateGptResponse: GenerateGptResponse = async ( // engine:"airt-canada-gpt35-turbo-16k", messages: [ { - role: 'system', + role: "system", content: instructions, }, { - role: 'user', + role: "user", content: command, }, ], @@ -119,20 +129,23 @@ export const generateGptResponse: GenerateGptResponse = async ( // }); // } - console.log('fetching', payload); + console.log("fetching", payload); // https://api.openai.com/v1/chat/completions - const response = await fetch('https://airt-openai-canada.openai.azure.com/openai/deployments/airt-canada-gpt35-turbo-16k/chat/completions?api-version=2023-07-01-preview', { - headers: { - 'Content-Type': 'application/json', - // Authorization: `Bearer ${process.env.AZURE_OPENAI_API_KEY!}`, - 'api-key': `${process.env.AZURE_OPENAI_API_KEY!}`, - }, - method: 'POST', - body: JSON.stringify(payload), - }); + const response = await fetch( + "https://airt-openai-canada.openai.azure.com/openai/deployments/airt-canada-gpt35-turbo-16k/chat/completions?api-version=2023-07-01-preview", + { + headers: { + "Content-Type": "application/json", + // Authorization: `Bearer ${process.env.AZURE_OPENAI_API_KEY!}`, + "api-key": `${process.env.AZURE_OPENAI_API_KEY!}`, + }, + method: "POST", + body: JSON.stringify(payload), + } + ); const json = (await response.json()) as OpenAIResponse; - console.log('response json', json); + console.log("response json", json); // return context.entities.RelatedObject.create({ // data: { // content: json?.choices[0].message.content, @@ -141,7 +154,7 @@ export const generateGptResponse: GenerateGptResponse = async ( // }); return { content: json?.choices[0].message.content, - } + }; } catch (error: any) { if (!context.user.hasPaid && error?.statusCode != 402) { await context.entities.User.update({ @@ -156,12 +169,13 @@ export const generateGptResponse: GenerateGptResponse = async ( console.error(error); } - throw new HttpError(500, 'Something went wrong'); + throw new HttpError(500, "Something went wrong"); }; - - -export const createChat: CreateChat = async (_args, context) => { +export const createChat: CreateChat = async ( + _args, + context +) => { if (!context.user) { throw new HttpError(401); } @@ -175,35 +189,38 @@ export const createChat: CreateChat = async (_args, context) data: { conversation: [ { - role: 'assistant', - content: `Hi! I am Captn and I am here to help you with digital marketing. I can create and optimise marketing campaigns for you. But before I propose any activities, please let me know a little bit about your business and what your marketing goals are.`, + role: "assistant", + content: `Hi! I am Captn and I am here to help you with digital marketing. I can create and optimise marketing campaigns for you. But before I propose any activities, please let me know a little bit about your business and what your marketing goals are.`, }, - ], + ], chat: { connect: { id: chat.id } }, user: { connect: { id: context.user.id } }, }, }); -} +}; type UpdateConversationPayload = { conversation_id: number; conversations: any; }; -export const updateConversation: UpdateConversation = async (args, context) => { +export const updateConversation: UpdateConversation< + UpdateConversationPayload, + Conversation +> = async (args, context) => { if (!context.user) { throw new HttpError(401); } return context.entities.Conversation.update({ where: { id: args.conversation_id }, data: { - conversation: args.conversations + conversation: args.conversations, }, - }) -} + }); +}; type AgentPayload = { - message: string; + message: any; conv_id: number; }; @@ -215,29 +232,33 @@ export const getAgentResponse: GetAgentResponse = async ( throw new HttpError(401); } - const payload = { message: message, conv_id: conv_id, user_id: context.user.id }; - console.log("===========") - console.log("Payload to Python server") - console.log(payload) - console.log("===========") + const payload = { + message: message, + conv_id: conv_id, + user_id: context.user.id, + }; + console.log("==========="); + console.log("Payload to Python server"); + console.log(payload); + console.log("==========="); try { - const response = await fetch(`${ADS_SERVER_URL}/chat`, { - method: 'POST', + const response = await fetch(`${ADS_SERVER_URL}/openai/chat`, { + method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); - const json = await response.json() as { detail?: string }; // Parse JSON once + const json = (await response.json()) as { detail?: string }; // Parse JSON once if (!response.ok) { - const errorMsg = json.detail || `HTTP error with status code ${response.status}`; - console.error('Server Error:', errorMsg); + const errorMsg = + json.detail || `HTTP error with status code ${response.status}`; + console.error("Server Error:", errorMsg); throw new Error(errorMsg); } return { content: json }; - } catch (error: any) { - throw new HttpError(500, 'Something went wrong. Please try again later'); + throw new HttpError(500, "Something went wrong. Please try again later"); } };