File size: 954 Bytes
7d9b16b
 
b985953
7d9b16b
 
3be11bc
7d9b16b
 
622f41b
b985953
7d9b16b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
622f41b
7d9b16b
 
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
from transformers import pipeline
import torch

qa_pipeline = pipeline(
    "text2text-generation",
    model="google/flan-t5-base",
    device=device
)

def generate_answer(context, question):
    # Handle empty context
    if context == "No relevant context found.":
        prompt = f"""
        You are a helpful AI assistant. Answer the question based on your general knowledge.
        
        Question: {question}
        
        Answer as a helpful paragraph:
        """
    else:
        prompt = f"""
        You are a helpful AI assistant. Use the context to answer the question.
        
        Context:
        {context}
        
        Question: {question}
        
        Answer as a comprehensive paragraph with key details:
        """
    
    result = qa_pipeline(
        prompt,
        max_length=400,
        do_sample=True,
        temperature=0.7,
        top_p=0.9
    )
    
    return result[0]['generated_text'].strip()