forked from usemoss/moss
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_embedding_sample.py
More file actions
279 lines (238 loc) Β· 7.66 KB
/
custom_embedding_sample.py
File metadata and controls
279 lines (238 loc) Β· 7.66 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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
"""Custom embeddings workflow sample."""
# ---------- Imports ----------
import asyncio
import os
import time
from typing import List
from dotenv import load_dotenv
from openai import OpenAI
from inferedge_moss import (
DocumentInfo,
MossClient,
MutationOptions,
QueryOptions,
)
# ---------- Configuration ----------
load_dotenv()
MOSS_PROJECT_ID = os.getenv("MOSS_PROJECT_ID")
MOSS_PROJECT_KEY = os.getenv("MOSS_PROJECT_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not all([MOSS_PROJECT_ID, MOSS_PROJECT_KEY, OPENAI_API_KEY]):
raise ValueError(
"Missing required environment variables. Please set MOSS_PROJECT_ID, "
"MOSS_PROJECT_KEY, and OPENAI_API_KEY.",
)
# Cast to str for mypy
PROJECT_ID = str(MOSS_PROJECT_ID)
PROJECT_KEY = str(MOSS_PROJECT_KEY)
API_KEY = str(OPENAI_API_KEY)
MOSS_INDEX_NAME = f"custom-embedding-index-{int(time.time() * 1000)}"
moss_client = MossClient(PROJECT_ID, PROJECT_KEY)
openai_client = OpenAI(api_key=API_KEY)
# ---------- Sample Data to create Index ----------
INITIAL_DOCUMENTS = [
{
"id": "init-doc-1",
"text": "React is a popular JavaScript library for building user interfaces",
},
{
"id": "init-doc-2",
"text": "Python is a versatile programming language used for web development",
},
{
"id": "init-doc-3",
"text": "Machine learning enables computers to learn from data",
},
{
"id": "init-doc-4",
"text": "Docker containers help package applications with their dependencies",
},
{
"id": "init-doc-5",
"text": "TypeScript adds static typing to JavaScript for safer code",
},
{
"id": "init-doc-6",
"text": "Kubernetes orchestrates containerized applications at scale",
},
{
"id": "init-doc-7",
"text": "GraphQL provides a flexible query language for APIs",
},
{
"id": "init-doc-8",
"text": "Redis is an in-memory data store used for caching",
},
{
"id": "init-doc-9",
"text": "PostgreSQL is a powerful open-source relational database",
},
{
"id": "init-doc-10",
"text": "Git is a distributed version control system for tracking code changes",
},
]
# ---------- Sample Data to add later ----------
NEW_DOCUMENTS = [
{
"id": f"step-doc-{int(time.time() * 1000)}-1",
"text": "the Pine Grove gardening club meets every Saturday morning to plant herbs",
},
{
"id": f"step-doc-{int(time.time() * 1000)}-2",
"text": "club members water the raised beds and tidy the tool shed after the meeting",
},
{
"id": f"step-doc-{int(time.time() * 1000)}-3",
"text": "organizer Leo keeps a list of herbs to bring for next week",
},
]
WORKFLOW_QUERY = "when does the Pine Grove gardening club meet?"
# ---------- Helper Functions ----------
def generate_embedding(text: str) -> List[float]:
"""Generate an OpenAI embedding for the provided text."""
response = openai_client.embeddings.create(
model="text-embedding-3-small",
input=text,
)
return response.data[0].embedding
async def delete_index(index_name: str) -> None:
"""Delete the specified index if it exists."""
print("π§Ή Cleanup: Deleting index...")
try:
await moss_client.delete_index(index_name)
print(f" β
Index \"{index_name}\" deleted successfully")
except Exception as cleanup_error:
print(f" β οΈ Failed to delete index \"{index_name}\": {cleanup_error}")
# ---------- Main Workflow ----------
async def main() -> None:
"""Exercise the custom embedding workflow steps end-to-end."""
print("=" * 80)
print("π§ͺ Running Custom Embeddings Workflow Steps")
print("=" * 80)
print(f"Index: {MOSS_INDEX_NAME}")
print(f"Initial documents: {len(INITIAL_DOCUMENTS)}")
print(f"Documents to add later: {len(NEW_DOCUMENTS)}")
print()
try:
print("ποΈ Step 0: Creating index with 10 initial documents...")
print(" Generating embeddings for initial documents...")
initial_docs_with_embeddings = []
for doc in INITIAL_DOCUMENTS:
embedding = generate_embedding(doc["text"])
initial_docs_with_embeddings.append(
DocumentInfo(
id=doc["id"],
text=doc["text"],
embedding=embedding,
)
)
print(f" β Generated {len(initial_docs_with_embeddings)} embeddings")
print(" Creating index with custom embeddings...")
await moss_client.create_index(
MOSS_INDEX_NAME,
initial_docs_with_embeddings,
)
print(
f" β
Index \"{MOSS_INDEX_NAME}\" created successfully with custom embeddings"
)
print(" β³ Waiting 3 seconds for index to initialize...")
await asyncio.sleep(3)
print()
print("π Step 1: Generating OpenAI embeddings for new documents...")
docs_with_embeddings = []
for doc in NEW_DOCUMENTS:
embedding = generate_embedding(doc["text"])
print(f" β Generated embedding for \"{doc['id']}\" (dim: {len(embedding)})")
docs_with_embeddings.append(
DocumentInfo(
id=doc["id"],
text=doc["text"],
embedding=embedding,
)
)
print(f" β
Generated {len(docs_with_embeddings)} embeddings")
print()
print("π€ Step 2: Adding documents with custom embeddings to index...")
add_result = await moss_client.add_docs(
MOSS_INDEX_NAME,
docs_with_embeddings,
MutationOptions(upsert=True),
)
print(f" β
Job: {add_result.job_id}, Doc count: {add_result.doc_count}")
print(" β³ Waiting 2 seconds for index to update...")
await asyncio.sleep(2)
print()
print("π Step 3: Querying via hotpath (cloud query without loading index)...")
query_embedding = generate_embedding(WORKFLOW_QUERY)
print(f" Generated query embedding (dim: {len(query_embedding)})")
hotpath_results = await moss_client.query(
MOSS_INDEX_NAME,
WORKFLOW_QUERY,
QueryOptions(embedding=query_embedding, top_k=5),
)
print(f" β
Hotpath query returned {len(hotpath_results.docs)} results")
print(f" Time taken: {hotpath_results.time_taken_ms}ms")
print()
print(" Top 3 results:")
for i, result in enumerate(hotpath_results.docs[:3]):
print(f" {i + 1}. {result.id}")
print(f" Score: {result.score:.4f}")
print(f" Text: {result.text[:60]}...")
new_doc_ids = [d["id"] for d in NEW_DOCUMENTS]
found_new_docs = [
res
for res in hotpath_results.docs
if any(res.id.startswith("-".join(id.split("-")[:3])) for id in new_doc_ids)
]
print(
f" π Found {len(found_new_docs)} of {len(NEW_DOCUMENTS)} newly added docs in results"
)
print()
print("πΎ Step 4: Loading index locally...")
loaded_index_name = await moss_client.load_index(MOSS_INDEX_NAME)
print(f" β
Index \"{loaded_index_name}\" loaded successfully")
print()
print("π Step 5: Querying locally (using loaded index)...")
local_results = await moss_client.query(
MOSS_INDEX_NAME,
WORKFLOW_QUERY,
QueryOptions(embedding=query_embedding, top_k=5),
)
print(f" β
Local query returned {len(local_results.docs)} results")
print(f" Time taken: {local_results.time_taken_ms}ms")
print()
print(" Top 3 results:")
for i, result_local in enumerate(local_results.docs[:3]):
print(f" {i + 1}. {result_local.id}")
print(f" Score: {result_local.score:.4f}")
print(f" Text: {result_local.text[:60]}...")
found_new_docs_local = [
res_local
for res_local in local_results.docs
if any(res_local.id.startswith("-".join(id.split("-")[:3])) for id in new_doc_ids)
]
print(
" π Found "
f"{len(found_new_docs_local)} of {len(NEW_DOCUMENTS)} newly added docs in local results"
)
print()
print("π All steps completed successfully!")
print("=" * 80)
except Exception as error:
print()
print("=" * 80)
print("β STEPS FAILED")
print("=" * 80)
print(f"Error: {error}")
import traceback
print()
print("Stack trace:")
traceback.print_exc()
print("=" * 80)
raise
finally:
print()
await delete_index(MOSS_INDEX_NAME)
if __name__ == "__main__":
asyncio.run(main())