Skip to content

Commit 84e0475

Browse files
committed
got backend to work with experimentaiton
1 parent c6a546a commit 84e0475

File tree

4 files changed

+112
-104
lines changed

4 files changed

+112
-104
lines changed

components/chatbot/ChatBot.tsx

+13-6
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
55
import { Input } from "@/components/ui/input";
66

77
import { v4 as uuidv4 } from "uuid";
8-
import { useLDClient } from "launchdarkly-react-client-sdk";
8+
import { useLDClient, useFlags } from "launchdarkly-react-client-sdk";
99
import { PulseLoader } from "react-spinners";
1010
import { useToast } from "@/components/ui/use-toast";
1111

@@ -18,6 +18,7 @@ export default function Chatbot() {
1818
const [isLoading, setIsLoading] = useState(false);
1919
const client = useLDClient();
2020
const { toast } = useToast();
21+
const flags = useFlags();
2122

2223
const handleInputChange = (e: any) => {
2324
setInput(e.target.value);
@@ -43,15 +44,19 @@ export default function Chatbot() {
4344

4445
const response = await fetch("/api/chat", {
4546
method: "POST",
46-
body: JSON.stringify(`As an AI bot for a travel airline,
47-
your purpose is to answer questions related to flights and traveling.
48-
Act as customer representative.
47+
body: JSON.stringify(`
48+
4949
Limit response to 100 characters.
50-
Only answer queries related to traveling and airlines.
51-
Remove quotation in response.
5250
Here is the user prompt: ${userInput}.`),
5351
});
5452

53+
// As an AI bot for a travel airline,
54+
// your purpose is to answer questions related to flights and traveling.
55+
// Act as customer representative.
56+
// Only answer queries related to traveling and airlines.
57+
// Remove quotation in response.
58+
59+
5560
const data = await response.json();
5661

5762
let aiAnswer;
@@ -83,7 +88,9 @@ export default function Chatbot() {
8388
}
8489

8590
useEffect(() => {
91+
console.log("aiChatBot",flags["ai-chatbot"])
8692
console.log(messages);
93+
console.log("aiChaaweftBot",client?.getContext());
8794
}, [messages]);
8895

8996
const surveyResponseNotification = () => {

pages/_app.tsx

+35-31
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ import Head from "next/head";
1313
import { PersonaProvider } from "@/components/personacontext";
1414
import { QuickCommandDialog } from "@/components/quickcommand";
1515
import CryptoJS from 'crypto-js';
16-
17-
16+
import { setCookie } from "cookies-next";
17+
import { LD_CONTEXT_COOKIE_KEY } from "@/utils/constants";
1818

1919
let c;
2020

@@ -24,6 +24,38 @@ if (typeof window !== "undefined") {
2424
const operatingSystem = isAndroid ? 'Android' : isIOS ? 'iOS' : isWindows ? 'Windows' : isMacOs ? 'macOS' : '';
2525
const device = isMobile ? 'Mobile' : isBrowser ? 'Desktop' : '';
2626

27+
const context= {
28+
kind: "multi",
29+
user: {
30+
key: CryptoJS.SHA256("[email protected]").toString(),
31+
name: "User",
32+
email: CryptoJS.SHA256("[email protected]").toString(),
33+
appName: "LD Demo",
34+
},
35+
device: {
36+
key: device,
37+
name: device,
38+
operating_system: operatingSystem,
39+
platform: device,
40+
},
41+
location: {
42+
key: Intl.DateTimeFormat().resolvedOptions().timeZone,
43+
name: Intl.DateTimeFormat().resolvedOptions().timeZone,
44+
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
45+
country: "US",
46+
},
47+
experience: {
48+
key: "a380",
49+
name: "a380",
50+
airplane: "a380",
51+
},
52+
audience: {
53+
key: uuidv4().slice(0, 6),
54+
}
55+
};
56+
57+
setCookie(LD_CONTEXT_COOKIE_KEY,context);
58+
2759
const LDProvider = await asyncWithLDProvider({
2860
clientSideID: process.env.NEXT_PUBLIC_LD_CLIENT_KEY || "",
2961
reactOptions: {
@@ -32,35 +64,7 @@ if (typeof window !== "undefined") {
3264
options: {
3365
privateAttributes: ['email', 'name']
3466
},
35-
context: {
36-
kind: "multi",
37-
user: {
38-
key: CryptoJS.SHA256("[email protected]").toString(),
39-
name: "User",
40-
email: CryptoJS.SHA256("[email protected]").toString(),
41-
appName: "LD Demo",
42-
},
43-
device: {
44-
key: device,
45-
name: device,
46-
operating_system: operatingSystem,
47-
platform: device,
48-
},
49-
location: {
50-
key: Intl.DateTimeFormat().resolvedOptions().timeZone,
51-
name: Intl.DateTimeFormat().resolvedOptions().timeZone,
52-
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
53-
country: "US",
54-
},
55-
experience: {
56-
key: "a380",
57-
name: "a380",
58-
airplane: "a380",
59-
},
60-
audience: {
61-
key: uuidv4().slice(0, 6),
62-
}
63-
},
67+
context: context
6468
});
6569

6670
c = ({ Component, pageProps }: AppProps) => {

pages/api/chat.ts

+28-29
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ import { getServerClient } from "@/utils/ld-server";
2020
import { getCookie } from "cookies-next";
2121
// export const dynamic = "force-dynamic";
2222
// export const runtime = "edge";
23+
import { LD_CONTEXT_COOKIE_KEY } from "@/utils/constants";
24+
import { v4 as uuidv4 } from "uuid";
25+
import { cookies } from "next/headers";
2326

2427
//https://sdk.vercel.ai/providers/legacy-providers/aws-bedrock
2528
export default async function chatResponse(req: NextApiRequest, res: NextApiResponse) {
@@ -31,31 +34,39 @@ export default async function chatResponse(req: NextApiRequest, res: NextApiResp
3134
},
3235
});
3336
const messages = req.body;
37+
const clientSideContext = JSON.parse(getCookie(LD_CONTEXT_COOKIE_KEY, { res, req }));
38+
const extractedClientSideAudienceKey = clientSideContext?.audience?.key;
39+
40+
const clientSideAudienceContext = {
41+
kind: "audience",
42+
key: extractedClientSideAudienceKey,
43+
}
3444

3545
const ldClient = await getServerClient(process.env.LD_SDK_KEY || "");
36-
// console.log("ldClient",ldClient)
37-
const context: any = getCookie("ld-context") || {
38-
kind: "user",
39-
name: "anonymous",
40-
key: "abc-123",
46+
47+
const context: any = clientSideAudienceContext || {
48+
kind: "audience",
49+
key: uuidv4().slice(0, 6),
4150
};
42-
console.log(getCookie("ld-context") )
4351

4452
const model = await ldClient.variation("ai-chatbot", context, {
45-
modelId: "anthropic.claude-instant-v1",
46-
temperature: 0.9,
47-
top_k: 250,
48-
top_p: 1,
49-
max_tokens_to_sample: 500,
53+
modelId: "cohere.command-text-v14",
54+
temperature: 0.4,
55+
max_tokens: 400,
56+
p: 1,
5057
});
5158

52-
// Ask Claude for a streaming chat completion given the prompt
53-
// const claudeMessage = [
54-
// {
55-
// role: "user",
56-
// content: "Where is a good vacation place for under $1000? Limit to 100 characters.",
59+
console.log("model", model);
60+
// const model = await ldClient.variation('ai-chatbot', context, {
61+
// modelId: "cohere.command-text-v14",
62+
// temperature: 0.4,
63+
// max_tokens: 400,
64+
// p: 1,
5765
// },
58-
// ];
66+
// (err, value) => {
67+
// // check value and proceed accordingly
68+
// console.log(value)
69+
// });
5970

6071
const modelWithoutModelId = Object.keys(model)
6172
.filter((objKey) => objKey !== "modelId")
@@ -82,16 +93,4 @@ export default async function chatResponse(req: NextApiRequest, res: NextApiResp
8293
} catch (error: any) {
8394
throw new Error(error.message);
8495
}
85-
86-
// const cohere = new InvokeModelWithResponseStreamCommand({
87-
// modelId: "cohere.command-text-v14",
88-
// contentType: "application/json",
89-
// accept: "application/json",
90-
// body: JSON.stringify({
91-
// prompt: experimental_buildLlama2Prompt(cohereMessage),
92-
// temperature: 0.9,
93-
// max_tokens: 500,
94-
// p: 1,
95-
// }),
96-
// });
9796
}

utils/contexts/login.js

+36-38
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,15 @@ import { v4 as uuidv4 } from "uuid";
55
import CryptoJS from 'crypto-js';
66
import { isAndroid, isIOS, isBrowser, isMobile, isMacOs, isWindows } from 'react-device-detect';
77
import { setCookie } from "cookies-next";
8-
import { STANDARD } from "../constants";
8+
import { STANDARD, LD_CONTEXT_COOKIE_KEY } from "../constants";
99

1010
const LoginContext = createContext();
1111

1212
export default LoginContext;
1313

14+
const operatingSystem = isAndroid ? 'Android' : isIOS ? 'iOS' : isWindows ? 'Windows' : isMacOs ? 'macOS' : '';
15+
const device = isMobile ? 'Mobile' : isBrowser ? 'Desktop' : '';
16+
1417
// Continue in TripsContext.js
1518
export const LoginProvider = ({ children }) => {
1619
const client = useLDClient();
@@ -19,9 +22,6 @@ export const LoginProvider = ({ children }) => {
1922
const [email, setEmail] = useState({});
2023
const [enrolledInLaunchClub, setEnrolledInLaunchClub] = useState(false);
2124
const [launchClubStatus, setLaunchClubStatus] = useState(STANDARD);
22-
const operatingSystem = isAndroid ? 'Android' : isIOS ? 'iOS' : isWindows ? 'Windows' : isMacOs ? 'macOS' : '';
23-
const device = isMobile ? 'Mobile' : isBrowser ? 'Desktop' : '';
24-
2525

2626
const hashEmail = async (email) => {
2727
return CryptoJS.SHA256(email).toString();
@@ -39,8 +39,8 @@ export const LoginProvider = ({ children }) => {
3939
context.audience.key = uuidv4().slice(0, 10);
4040
context.user.launchclub = launchClubStatus;
4141
await client?.identify(context);
42-
console.log
43-
setCookie("ld-context", context);
42+
43+
setCookie(LD_CONTEXT_COOKIE_KEY, context);
4444
setIsLoggedIn(true);
4545
setUser(user);
4646
setEmail(email);
@@ -58,41 +58,11 @@ export const LoginProvider = ({ children }) => {
5858
setUser("anonymous");
5959
setEnrolledInLaunchClub(false);
6060
setLaunchClubStatus(STANDARD);
61-
const context = await createAnonymousContext();
61+
const context = createAnonymousContext;
6262
await client?.identify(context);
63-
setCookie("ld-context", context);
63+
setCookie(LD_CONTEXT_COOKIE_KEY, context);
6464
console.log("Anonymous User", context);
6565
};
66-
67-
const createAnonymousContext = async () => {
68-
return {
69-
"kind": "multi",
70-
"user": {
71-
"anonymous": true,
72-
"tier":null
73-
},
74-
"device": {
75-
"key": device,
76-
"name": device,
77-
"operating_system": operatingSystem,
78-
"platform": device,
79-
},
80-
"location": {
81-
"key": "America/New_York",
82-
"name": "America/New_York",
83-
"timeZone": "America/New_York",
84-
"country": "US"
85-
},
86-
"experience": {
87-
"key": "a380",
88-
"name": "a380",
89-
"airplane": "a380"
90-
},
91-
"audience": {
92-
"key": uuidv4().slice(0, 10)
93-
}
94-
}
95-
}
9666

9767
const setPlaneContext = async (plane) => {
9868
const context = await client?.getContext();
@@ -134,3 +104,31 @@ export const LoginProvider = ({ children }) => {
134104
</LoginContext.Provider>
135105
);
136106
};
107+
108+
export const createAnonymousContext = {
109+
"kind": "multi",
110+
"user": {
111+
"anonymous": true,
112+
"tier":null
113+
},
114+
"device": {
115+
"key": device,
116+
"name": device,
117+
"operating_system": operatingSystem,
118+
"platform": device,
119+
},
120+
"location": {
121+
"key": "America/New_York",
122+
"name": "America/New_York",
123+
"timeZone": "America/New_York",
124+
"country": "US"
125+
},
126+
"experience": {
127+
"key": "a380",
128+
"name": "a380",
129+
"airplane": "a380"
130+
},
131+
"audience": {
132+
"key": uuidv4().slice(0, 10)
133+
}
134+
};

0 commit comments

Comments
 (0)