Skip to content

Commit

Permalink
proper caching and KV
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhravya committed Apr 13, 2024
1 parent fac02d3 commit 93e4fd7
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 10 deletions.
12 changes: 11 additions & 1 deletion apps/cf-ai-backend/src/routes/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,17 @@ export async function POST(request: Request, store: CloudflareVectorizeStore, _:

const ourID = `${body.url}-${body.user}`;

const uuid = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
// WHY? Because this helps us to prevent duplicate entries for the same URL and user
function seededRandom(seed: string) {
let x = [...seed].reduce((acc, cur) => acc + cur.charCodeAt(0), 0);
return () => {
x = (x * 9301 + 49297) % 233280;
return x / 233280;
};
}

const random = seededRandom(ourID);
const uuid = random().toString(36).substring(2, 15) + random().toString(36).substring(2, 15);

await env.KV.put(uuid, ourID);

Expand Down
19 changes: 16 additions & 3 deletions apps/cf-ai-backend/src/routes/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,21 @@ export async function POST(request: Request, _: CloudflareVectorizeStore, embedd
console.log('highscoreIds', highScoreIds);

if (sourcesOnly === 'true') {
const idsAsStrings = highScoreIds.map((id) => env?.KV.get(id.toString()) ?? id.toString());
return new Response(JSON.stringify({ ids: idsAsStrings }), { status: 200 });
// Try await env.KV.get(id) for each id in a Promise.all
const idsAsStrings = highScoreIds.map(String);

const storedContent = await Promise.all(
idsAsStrings.map(async (id) => {
const stored = await env!.KV.get(id);
if (stored) {
return stored;
}
return id;
}),
);

console.log(storedContent);
return new Response(JSON.stringify({ ids: storedContent }), { status: 200 });
}

const vec = await env!.VECTORIZE_INDEX.getByIds(highScoreIds);
Expand Down Expand Up @@ -103,7 +116,7 @@ export async function POST(request: Request, _: CloudflareVectorizeStore, embedd
history: [...defaultHistory, ...(body.chatHistory ?? [])],
});

const prompt = `Context:\n${preparedContext}\n\nQuestion: ${query}\nAnswer:`;
const prompt = `Context:\n${preparedContext ?? ''}\n\nQuestion: ${query}\nAnswer:`;

const output = await chat.sendMessageStream(prompt);

Expand Down
16 changes: 14 additions & 2 deletions apps/cf-ai-backend/src/routes/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,20 @@ export async function GET(request: Request, _: CloudflareVectorizeStore, embeddi
const highScoreIds = resp.matches.filter(({ score }) => score > 0.3).map(({ id }) => id);

if (sourcesOnly === 'true') {
const idsAsStrings = highScoreIds.map((id) => env?.KV.get(id.toString()) ?? id.toString());
return new Response(JSON.stringify({ ids: idsAsStrings }), { status: 200 });
const idsAsStrings = highScoreIds.map(String);

const storedContent = await Promise.all(
idsAsStrings.map(async (id) => {
const stored = await env!.KV.get(id);
if (stored) {
return stored;
}
return id;
}),
);

console.log(storedContent);
return new Response(JSON.stringify({ ids: storedContent }), { status: 200 });
}

const vec = await env!.VECTORIZE_INDEX.getByIds(highScoreIds);
Expand Down
2 changes: 1 addition & 1 deletion apps/cf-ai-backend/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ compatibility_date = "2024-02-23"

[[vectorize]]
binding = "VECTORIZE_INDEX"
index_name = "any-vector"
index_name = "supermem-vector"

[ai]
binding = "AI"
Expand Down
1 change: 0 additions & 1 deletion apps/extension/src/SideBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,6 @@ function SideBar() {
<DialogTrigger asChild>
<button
onClick={() => {
return;
sendUrlToAPI();
setIsSendingData(true);
setTimeout(() => {
Expand Down
3 changes: 1 addition & 2 deletions apps/web/src/app/api/store/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,14 @@ export async function POST(req: NextRequest) {
storeToSpace = "none";
}

// Count the number of stored content of the user
const count = await db
.select({
count: sql<number>`count(*)`.mapWith(Number),
})
.from(storedContent)
.where(eq(storedContent.user, session.user.id));

console.log(count[0].count);
console.log("count", count[0].count);

const storedContentId = await db.insert(storedContent).values({
content: data.pageContent,
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export function cleanUrl(url: string) {
}

export function getIdsFromSource(sourceIds: string[]) {
console.log(sourceIds);
return sourceIds.map((id) => {
const parts = id.split("-");
if (parts.length > 1) {
Expand Down

0 comments on commit 93e4fd7

Please sign in to comment.