Spaces:
Sleeping
Sleeping
Update agents/research_agent.py
Browse files- agents/research_agent.py +82 -84
agents/research_agent.py
CHANGED
|
@@ -1,85 +1,83 @@
|
|
| 1 |
-
from
|
| 2 |
-
from
|
| 3 |
-
from
|
| 4 |
-
from
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
class ResearchAgent:
|
| 8 |
-
def __init__(self):
|
| 9 |
-
"""
|
| 10 |
-
Initialize the research agent with local Ollama LLM.
|
| 11 |
-
"""
|
| 12 |
-
print("Initializing ResearchAgent with
|
| 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 |
-
"draft_answer": draft_answer,
|
| 84 |
-
"context_used": context
|
| 85 |
}
|
|
|
|
| 1 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
| 2 |
+
from typing import Dict, List
|
| 3 |
+
from langchain_core.documents.base import Document
|
| 4 |
+
from config.settings import settings
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
class ResearchAgent:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
"""
|
| 10 |
+
Initialize the research agent with local Ollama LLM.
|
| 11 |
+
"""
|
| 12 |
+
print("Initializing ResearchAgent with Hugging Face Transformers...")
|
| 13 |
+
model_name = getattr(settings, "HF_MODEL_RESEARCH", "google/flan-t5-large")
|
| 14 |
+
|
| 15 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 16 |
+
self.model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
|
| 17 |
+
|
| 18 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 19 |
+
self.model.to(self.device)
|
| 20 |
+
|
| 21 |
+
print(f"Model '{model_name}' initialized successfully on {self.device}.")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def sanitize_response(self, response_text: str) -> str:
|
| 25 |
+
"""
|
| 26 |
+
Sanitize the LLM's response by stripping unnecessary whitespace.
|
| 27 |
+
"""
|
| 28 |
+
return response_text.strip()
|
| 29 |
+
|
| 30 |
+
def generate_prompt(self, question: str, context: str) -> str:
|
| 31 |
+
"""
|
| 32 |
+
Generate a structured prompt for the LLM to generate a precise and factual answer.
|
| 33 |
+
"""
|
| 34 |
+
prompt = f"""
|
| 35 |
+
You are an AI assistant designed to provide precise and factual answers based on the given context.
|
| 36 |
+
|
| 37 |
+
**Instructions:**
|
| 38 |
+
- Answer the following question using only the provided context.
|
| 39 |
+
- Be clear, concise, and factual.
|
| 40 |
+
- Return as much information as you can get from the context.
|
| 41 |
+
|
| 42 |
+
**Question:** {question}
|
| 43 |
+
**Context:**
|
| 44 |
+
{context}
|
| 45 |
+
|
| 46 |
+
**Provide your answer below:**
|
| 47 |
+
"""
|
| 48 |
+
return prompt
|
| 49 |
+
|
| 50 |
+
def generate(self, question: str, documents: List[Document]) -> Dict:
|
| 51 |
+
"""
|
| 52 |
+
Generate an initial answer using the provided documents.
|
| 53 |
+
"""
|
| 54 |
+
print(f"ResearchAgent.generate called with question='{question}' and {len(documents)} documents.")
|
| 55 |
+
|
| 56 |
+
# Combine the top document contents into one string
|
| 57 |
+
context = "\n\n".join([doc.page_content for doc in documents])
|
| 58 |
+
print(f"Combined context length: {len(context)} characters.")
|
| 59 |
+
|
| 60 |
+
# Create a prompt for the LLM
|
| 61 |
+
prompt = self.generate_prompt(question, context)
|
| 62 |
+
print("Prompt created for the LLM.")
|
| 63 |
+
|
| 64 |
+
# Call the LLM to generate the answer
|
| 65 |
+
try:
|
| 66 |
+
print("Running inference with Transformers...")
|
| 67 |
+
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(self.device)
|
| 68 |
+
outputs = self.model.generate(**inputs, max_new_tokens=300, temperature=0.3)
|
| 69 |
+
llm_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 70 |
+
print("Model response received.")
|
| 71 |
+
except Exception as e:
|
| 72 |
+
print(f"Error during model inference: {e}")
|
| 73 |
+
raise RuntimeError("Failed to generate answer due to a model error.") from e
|
| 74 |
+
|
| 75 |
+
# Sanitize the response
|
| 76 |
+
draft_answer = self.sanitize_response(llm_response) if llm_response else "I cannot answer this question based on the provided documents."
|
| 77 |
+
|
| 78 |
+
print(f"Generated answer: {draft_answer}")
|
| 79 |
+
|
| 80 |
+
return {
|
| 81 |
+
"draft_answer": draft_answer,
|
| 82 |
+
"context_used": context
|
|
|
|
|
|
|
| 83 |
}
|