File size: 9,304 Bytes
8c64d11
 
 
 
 
 
 
 
 
 
464851e
6f120f4
 
 
 
 
8c64d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464851e
5c73b25
 
 
 
 
464851e
8c64d11
 
464851e
 
 
 
 
 
 
 
5ddd201
5c73b25
 
464851e
 
5ddd201
5c73b25
5ddd201
464851e
 
 
 
 
 
 
 
5ddd201
5c73b25
464851e
5ddd201
8c64d11
464851e
8c64d11
5c73b25
 
8c64d11
464851e
5ddd201
5c73b25
5ddd201
8c64d11
 
 
 
 
5ddd201
8c64d11
 
5ddd201
5c73b25
8c64d11
5ddd201
8c64d11
 
 
 
5c73b25
 
5ddd201
8c64d11
 
 
 
5ddd201
5c73b25
5ddd201
8c64d11
 
5ddd201
5c73b25
 
 
 
8c64d11
 
 
 
 
6f120f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c64d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import chainlit as cl
from langchain_anthropic import ChatAnthropic
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_qdrant import QdrantVectorStore
from qdrant_client import QdrantClient
from qdrant_client.http.models import Distance, VectorParams
from langchain.prompts import ChatPromptTemplate
from langchain.text_splitter import RecursiveCharacterTextSplitter
from pathlib import Path
import os
from huggingface_hub import HfApi, hf_hub_download
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import asyncio
from contextlib import asynccontextmanager

# Global variable to store the vectorstore instance
_vectorstore = None

# Configurable model selection
MODELS = {
    "gpt-3.5-turbo": ChatOpenAI(model_name="gpt-3.5-turbo"),
    "gpt-4": ChatOpenAI(model_name="gpt-4"),
    "claude-3-sonnet": ChatAnthropic(model="claude-3-sonnet")
}

# Custom prompt for vegan ethics
VEGAN_ETHICS_TEMPLATE = """
You are an ethical philosopher specializing in animal rights and veganism. 
Use the following pieces of context to answer the user's question.
Always guide your response toward applying the "Name the Trait" argument:

1. Ask what trait in non-human animals, if present in humans, would justify treating humans the same way
2. Examine if this trait is morally relevant or arbitrary
3. Challenge the user to maintain logical consistency in their ethical framework
4. Use scientific evidence from the context to support your points

Context: {context}
Question: {question}
Answer:
"""

def get_vectorstore(persist_dir: str = "vector_store"):
    """Create or return cached vectorstore instance"""
    global _vectorstore
    if _vectorstore is not None:
        return _vectorstore
        
    # Initialize vector store with persistence
    persist_dir = Path(persist_dir)
    client = QdrantClient(
        path=str(persist_dir),
        force_disable_check_same_thread=True  # Important for concurrent access
    )
    
    # Check if collection exists
    collections = client.get_collections().collections
    collection_names = [c.name for c in collections]
    
    if "vegan_ethics" not in collection_names:
        print(f"Creating new vector store in {persist_dir}")
        client.create_collection(
            collection_name="vegan_ethics",
            vectors_config=VectorParams(
                size=1536,
                distance=Distance.COSINE,
            ),
        )
    
    _vectorstore = QdrantVectorStore(
        client=client,
        embedding=OpenAIEmbeddings(),
        collection_name="vegan_ethics"
    )
    return _vectorstore

async def process_and_load_documents(vectorstore, repo_id="Frikster42/name-that-trait", data_folder="data"):
    # Create a single TaskList for the entire process
    tasks = cl.TaskList()
    tasks.status = "Initializing..."
    await tasks.send()

    msg = cl.Message(content="Loading documents from Hugging Face repository... please be patient...")
    await msg.send()

    data_dir = Path("data")
    data_dir.mkdir(exist_ok=True)

    # Get list of files in the repository
    api = HfApi()
    dataset_files = api.list_repo_files(repo_id, repo_type="dataset")
    dataset_pdf_files = [f for f in dataset_files if f.endswith('.pdf')]
    
    # Download phase
    tasks.status = "Downloading files..."
    await tasks.send()
    
    for i, pdf_file in enumerate(dataset_pdf_files):
        task = cl.Task(title=f"Downloading {pdf_file}")
        await tasks.add_task(task)
        
        hf_hub_download(
            repo_id=repo_id,
            filename=pdf_file,
            local_dir=str(data_dir),
            local_dir_use_symlinks=False,
            repo_type="dataset"
        )
        
        task.status = cl.TaskStatus.DONE
        await tasks.send()

    # Loading phase
    documents = []
    pdf_files = [f for f in os.listdir(data_folder) if f.endswith('.pdf')]
    
    tasks.status = "Loading files..."
    await tasks.send()
    
    for i, filename in enumerate(pdf_files):
        task = cl.Task(title=f"Loading {filename}")
        await tasks.add_task(task)
        
        filepath = os.path.join(data_folder, filename)
        if filename.endswith('.pdf'):
            from langchain.document_loaders import PyPDFLoader
            loader = PyPDFLoader(filepath)
        else:
            from langchain.document_loaders import TextLoader
            loader = TextLoader(filepath)
        documents.extend(loader.load())
        task.status = cl.TaskStatus.DONE
        await tasks.send()
    
    # Split and process documents
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
    chunks = text_splitter.split_documents(documents)
    
    if chunks:
        tasks.status = "Processing chunks..."
        await tasks.send()
        
        batch_size = 100
        num_batches = (len(chunks) + batch_size - 1) // batch_size
        
        for i in range(0, len(chunks), batch_size):
            task = cl.Task(title=f"Processing batch {(i//batch_size)+1}/{num_batches}")
            await tasks.add_task(task)
            
            batch = chunks[i:i + batch_size]
            vectorstore.add_documents(batch)
            task.status = cl.TaskStatus.DONE
            await tasks.send()
    
    tasks.status = "Completed"
    await tasks.send()
    
    msg = cl.Message(content="✅ Documents loaded successfully!")
    await msg.send()
    return vectorstore

# Create FastAPI app
app = FastAPI(title="Vegan Ethics RAG API")

class QueryRequest(BaseModel):
    question: str
    model_name: Optional[str] = "gpt-3.5-turbo"

@app.post("/api/query")
async def query_endpoint(request: QueryRequest):
    try:
        # Get or create vectorstore instance
        vectorstore = get_vectorstore()
        
        # Create prompt template
        prompt = ChatPromptTemplate.from_messages([
            ("system", VEGAN_ETHICS_TEMPLATE),
            ("user", "{question}")
        ])
        
        # Validate model selection
        if request.model_name not in MODELS:
            raise HTTPException(status_code=400, detail=f"Invalid model name. Choose from: {list(MODELS.keys())}")
        
        # Get relevant documents
        docs = vectorstore.similarity_search(request.question, k=3)
        context = "\n".join(doc.page_content for doc in docs)
        
        # Generate response
        chain = prompt | MODELS[request.model_name]
        response = await chain.ainvoke({
            "context": context,
            "question": request.question
        })
        
        return {
            "response": response.content,
            "model_used": request.model_name
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@cl.on_chat_start
async def start():
    # Get or create vectorstore instance
    vectorstore = get_vectorstore()
    
    # Load documents if needed
    collection_info = vectorstore.client.get_collection("vegan_ethics")
    if collection_info.points_count == 0:
        await cl.Message(content="Vector store is empty, loading documents...").send()
        vectorstore = await process_and_load_documents(vectorstore)
    
    # Create prompt template
    prompt = ChatPromptTemplate.from_messages([
        ("system", VEGAN_ETHICS_TEMPLATE),
        ("user", "{question}")
    ])
    
    # Store components in session
    cl.user_session.set("vectorstore", vectorstore)
    cl.user_session.set("prompt", prompt)
    cl.user_session.set("model_name", "gpt-3.5-turbo")
    
    # UI for model selection
    actions = [
        cl.Action(
            name="model_select", 
            label="Current Model: gpt-3.5-turbo", 
            description="Change the AI model",
            payload={"current_model": "gpt-3.5-turbo"}
        )
    ]
    
    await cl.Message(
        content="Welcome to the Vegan Ethics Assistant. Ask any question about veganism, ethics, or animal consumption.", 
        actions=actions
    ).send()

@cl.action_callback("model_select")
async def on_action(action):
    models_list = list(MODELS.keys())
    current_index = models_list.index(action.payload["current_model"])
    next_index = (current_index + 1) % len(models_list)
    next_model_name = models_list[next_index]
    
    cl.user_session.set("model_name", next_model_name)
    
    actions = [
        cl.Action(
            name="model_select", 
            label=f"Current Model: {next_model_name}", 
            description="Change the AI model",
            payload={"current_model": next_model_name}
        )
    ]
    
    await cl.Message(content=f"Model switched to {next_model_name}", actions=actions).send()

@cl.on_message
async def main(message):
    vectorstore = cl.user_session.get("vectorstore")
    prompt = cl.user_session.get("prompt")
    model_name = cl.user_session.get("model_name")
    
    # Get relevant documents
    docs = vectorstore.similarity_search(message.content, k=3)
    context = "\n".join(doc.page_content for doc in docs)
    
    # Generate response
    chain = prompt | MODELS[model_name]
    response = await chain.ainvoke({
        "context": context,
        "question": message.content
    })
    
    await cl.Message(content=response.content).send()