-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
186 lines (166 loc) · 5.02 KB
/
db.js
File metadata and controls
186 lines (166 loc) · 5.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import knex from 'knex';
import OpenAI from 'openai';
const db = knex({
client: 'pg',
connection: process.env.PG_CONNECTION_STRING,
searchPath: ['knex', 'public'],
});
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
export async function indexUser({ fid, name, attributes, intent }) {
try {
// Generate embeddings for both attributes and intent
const [attributesEmbedding, intentEmbedding] = await Promise.all([
openai.embeddings.create({
input: attributes,
model: process.env.MODEL_EMBEDDING
}),
openai.embeddings.create({
input: intent,
model: process.env.MODEL_EMBEDDING
})
]);
// Upsert user data with both vector embeddings
await db.raw(
`INSERT INTO users (fid, name, attributes, intent, attributes_vector, intent_vector, created_at)
VALUES (?, ?, ?, ?, ?, ?, NOW())
ON CONFLICT (fid)
DO UPDATE SET
name = EXCLUDED.name,
attributes = EXCLUDED.attributes,
intent = EXCLUDED.intent,
attributes_vector = EXCLUDED.attributes_vector,
intent_vector = EXCLUDED.intent_vector,
updated_at = NOW()`,
[
fid,
name,
attributes,
intent,
JSON.stringify(attributesEmbedding.data[0].embedding),
JSON.stringify(intentEmbedding.data[0].embedding)
]
);
} catch (error) {
console.error('Error indexing user:', error);
throw error;
}
}
export async function findUsers({ fid, attributes, intent }, limit = 50) {
try {
// First get ineligible users (those who declined or are in pending matches)
const ineligibleUsers = await db.raw(
`SELECT DISTINCT fid
FROM (
SELECT CASE
WHEN m.user1_fid = ? THEN m.user2_fid
ELSE m.user1_fid
END AS fid
FROM matches m
WHERE (m.user1_fid = ? OR m.user2_fid = ?)
AND (m.status = 'declined' OR
m.user1_status = 'declined' OR
m.user2_status = 'declined')
UNION
SELECT user1_fid AS fid FROM matches WHERE status IN ('pending', 'accepted')
UNION
SELECT user2_fid AS fid FROM matches WHERE status IN ('pending', 'accepted')
) AS ineligible`,
[fid, fid, fid]
);
// Generate embeddings for both search criteria
const [searchAttributesEmbedding, searchIntentEmbedding] = await Promise.all([
openai.embeddings.create({
input: attributes,
model: process.env.MODEL_EMBEDDING
}),
openai.embeddings.create({
input: intent,
model: process.env.MODEL_EMBEDDING
})
]);
const ineligibleFids = ineligibleUsers.rows.map(u => u.fid);
// Get users ordered by similarity, excluding ineligible users
const similarUsers = await db.raw(
`SELECT
fid,
name,
attributes,
intent,
(1 - (attributes_vector <=> ?)) * 0.5 +
(1 - (intent_vector <=> ?)) * 0.5 as similarity
FROM users
WHERE fid != ?
AND fid != ALL(?)
ORDER BY similarity DESC
LIMIT ?`,
[
JSON.stringify(searchAttributesEmbedding.data[0].embedding),
JSON.stringify(searchIntentEmbedding.data[0].embedding),
fid,
ineligibleFids,
limit
]
);
return similarUsers.rows;
} catch (error) {
console.error('Error finding users:', error);
throw error;
}
}
export async function createMatch(user1Fid, user2Fid) {
try {
const result = await db('matches').insert({
user1_fid: user1Fid,
user2_fid: user2Fid,
status: 'pending',
user1_status: 'pending',
user2_status: 'pending'
}).returning('*');
return result[0];
} catch (error) {
console.error('Error creating match:', error);
throw error;
}
}
export async function updateMatchStatus(user1Fid, user2Fid, userFid, status) {
try {
const match = await db('matches')
.where({
user1_fid: user1Fid,
user2_fid: user2Fid
})
.first();
if (!match) {
throw new Error('Match not found');
}
const updates = {};
if (userFid === match.user1_fid) {
updates.user1_status = status;
} else if (userFid === match.user2_fid) {
updates.user2_status = status;
} else {
throw new Error('User not part of this match');
}
// Update overall match status if both users have accepted
if (
(updates.user1_status === 'accepted' && match.user2_status === 'accepted') ||
(match.user1_status === 'accepted' && updates.user2_status === 'accepted')
) {
updates.status = 'accepted';
}
// Update the match
const result = await db('matches')
.where({ id: match.id })
.update({
...updates,
updated_at: db.fn.now()
})
.returning('*');
return result[0];
} catch (error) {
console.error('Error updating match status:', error);
throw error;
}
}