Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import openai
|
| 6 |
+
import logging
|
| 7 |
+
from pinecone import Pinecone, ServerlessSpec
|
| 8 |
+
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext
|
| 9 |
+
from llama_index.vector_stores.pinecone import PineconeVectorStore
|
| 10 |
+
|
| 11 |
+
# 1. Configure Logging
|
| 12 |
+
logging.basicConfig(level=logging.INFO)
|
| 13 |
+
|
| 14 |
+
# 2. Set API Keys (Use environment variables for security)
|
| 15 |
+
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
|
| 16 |
+
os.environ["PINECONE_API_KEY"] = "your-pinecone-api-key"
|
| 17 |
+
|
| 18 |
+
# 3. Initialize Pinecone
|
| 19 |
+
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
|
| 20 |
+
index_name = "quickstart"
|
| 21 |
+
|
| 22 |
+
# Delete & Create Index if needed
|
| 23 |
+
if index_name in [idx["name"] for idx in pc.list_indexes()]:
|
| 24 |
+
pc.delete_index(index_name)
|
| 25 |
+
|
| 26 |
+
pc.create_index(
|
| 27 |
+
name=index_name,
|
| 28 |
+
dimension=1536,
|
| 29 |
+
metric="euclidean",
|
| 30 |
+
spec=ServerlessSpec(cloud="aws", region="us-east-1"),
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
pinecone_index = pc.Index(index_name)
|
| 34 |
+
|
| 35 |
+
# 4. Load Documents
|
| 36 |
+
documents = SimpleDirectoryReader("./data/paul_graham").load_data()
|
| 37 |
+
|
| 38 |
+
# 5. Create Vector Index
|
| 39 |
+
vector_store = PineconeVectorStore(pinecone_index=pinecone_index)
|
| 40 |
+
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
| 41 |
+
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
|
| 42 |
+
|
| 43 |
+
# 6. Create Query Engine
|
| 44 |
+
query_engine = index.as_query_engine()
|
| 45 |
+
|
| 46 |
+
# 7. Gradio Interface
|
| 47 |
+
def query_document(user_query):
|
| 48 |
+
response = query_engine.query(user_query)
|
| 49 |
+
return str(response)
|
| 50 |
+
|
| 51 |
+
# 8. Gradio App
|
| 52 |
+
interface = gr.Interface(
|
| 53 |
+
fn=query_document,
|
| 54 |
+
inputs=gr.Textbox(label="Enter your query", placeholder="Ask something about the essay..."),
|
| 55 |
+
outputs=gr.Textbox(label="Response"),
|
| 56 |
+
title="Ask Paul Graham (Powered by LlamaIndex + Pinecone)"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
interface.launch()
|