|
1 | 1 | import cocoindex |
2 | 2 | import uvicorn |
3 | | - |
4 | | -from fastapi import FastAPI |
5 | 3 | from dotenv import load_dotenv |
| 4 | +from fastapi import FastAPI, Query |
| 5 | +from psycopg_pool import ConnectionPool |
| 6 | +import os |
| 7 | + |
| 8 | +@cocoindex.transform_flow() |
| 9 | +def text_to_embedding(text: cocoindex.DataSlice[str]) -> cocoindex.DataSlice[list[float]]: |
| 10 | + """ |
| 11 | + Embed the text using a SentenceTransformer model. |
| 12 | + This is a shared logic between indexing and querying. |
| 13 | + """ |
| 14 | + return text.transform( |
| 15 | + cocoindex.functions.SentenceTransformerEmbed( |
| 16 | + model="sentence-transformers/all-MiniLM-L6-v2")) |
| 17 | + |
| 18 | +@cocoindex.flow_def(name="MarkdownEmbeddingFastApiExample") |
| 19 | +def markdown_embedding_flow(flow_builder: cocoindex.FlowBuilder, data_scope: cocoindex.DataScope): |
| 20 | + """ |
| 21 | + Define an example flow that embeds markdown files into a vector database. |
| 22 | + """ |
| 23 | + data_scope["documents"] = flow_builder.add_source( |
| 24 | + cocoindex.sources.LocalFile(path="files")) |
| 25 | + doc_embeddings = data_scope.add_collector() |
| 26 | + |
| 27 | + with data_scope["documents"].row() as doc: |
| 28 | + doc["chunks"] = doc["content"].transform( |
| 29 | + cocoindex.functions.SplitRecursively(), |
| 30 | + language="markdown", chunk_size=2000, chunk_overlap=500) |
| 31 | + |
| 32 | + with doc["chunks"].row() as chunk: |
| 33 | + chunk["embedding"] = text_to_embedding(chunk["text"]) |
| 34 | + doc_embeddings.collect( |
| 35 | + filename=doc["filename"], |
| 36 | + location=chunk["location"], |
| 37 | + text=chunk["text"], |
| 38 | + embedding=chunk["embedding"] |
| 39 | + ) |
| 40 | + |
| 41 | + doc_embeddings.export( |
| 42 | + "doc_embeddings", |
| 43 | + cocoindex.storages.Postgres(), |
| 44 | + primary_key_fields=["filename", "location"], |
| 45 | + vector_indexes=[ |
| 46 | + cocoindex.VectorIndexDef( |
| 47 | + field_name="embedding", |
| 48 | + metric=cocoindex.VectorSimilarityMetric.COSINE_SIMILARITY)]) |
6 | 49 |
|
7 | | -from src.cocoindex_funs import code_embedding_flow, code_to_embedding |
| 50 | +def search(pool: ConnectionPool, query: str, top_k: int = 5): |
| 51 | + # Get the table name, for the export target in the text_embedding_flow above. |
| 52 | + table_name = cocoindex.utils.get_target_storage_default_name(markdown_embedding_flow, "doc_embeddings") |
| 53 | + # Evaluate the transform flow defined above with the input query, to get the embedding. |
| 54 | + query_vector = text_to_embedding.eval(query) |
| 55 | + # Run the query and get the results. |
| 56 | + with pool.connection() as conn: |
| 57 | + with conn.cursor() as cur: |
| 58 | + cur.execute(f""" |
| 59 | + SELECT filename, text, embedding <=> %s::vector AS distance |
| 60 | + FROM {table_name} ORDER BY distance LIMIT %s |
| 61 | + """, (query_vector, top_k)) |
| 62 | + return [ |
| 63 | + {"filename": row[0], "text": row[1], "score": 1.0 - row[2]} |
| 64 | + for row in cur.fetchall() |
| 65 | + ] |
8 | 66 |
|
9 | 67 | fastapi_app = FastAPI() |
10 | | - |
11 | | -query_handler = cocoindex.query.SimpleSemanticsQueryHandler( |
12 | | - name="SemanticsSearch", |
13 | | - flow=code_embedding_flow, |
14 | | - target_name="code_embeddings", |
15 | | - query_transform_flow=code_to_embedding, |
16 | | - default_similarity_metric=cocoindex.VectorSimilarityMetric.COSINE_SIMILARITY |
17 | | -) |
18 | | - |
19 | | -@fastapi_app.get("/query") |
20 | | -def query_endpoint(string: str): |
21 | | - results, _ = query_handler.search(string, 10) |
22 | | - return results |
| 68 | + |
| 69 | +@fastapi_app.on_event("startup") |
| 70 | +def startup_event(): |
| 71 | + load_dotenv() |
| 72 | + cocoindex.init() |
| 73 | + # Initialize database connection pool |
| 74 | + fastapi_app.state.pool = ConnectionPool(os.getenv("COCOINDEX_DATABASE_URL")) |
| 75 | + |
| 76 | +@fastapi_app.get("/search") |
| 77 | +def search_endpoint(q: str = Query(..., description="Search query"), limit: int = Query(5, description="Number of results")): |
| 78 | + results = search(fastapi_app.state.pool, q, limit) |
| 79 | + return {"results": results} |
23 | 80 |
|
24 | 81 | if __name__ == "__main__": |
25 | 82 | load_dotenv() |
|
0 commit comments