Spaces:
Sleeping
Sleeping
File size: 1,310 Bytes
1b04b96 634bbff 1b04b96 |
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 |
import openai
import time
import os
# Set your OpenAI API key
openai.api_key = os.getenv("OPENAI_API_KEY")
def generate_response_from_document(query, retrieved_docs):
if not retrieved_docs: # Check if no documents were retrieved
return "I cannot answer the question due to insufficient information in the documents."
context = " ".join([doc.page_content for doc in retrieved_docs]) # Now iterates over Document objects
prompt = (
"You are a highly intelligent assistant tasked with answering a question based strictly on the provided context. "
f"Given Question: {query} \n\n"
f"Context: {context} \n"
"Answer the question directly and concisely using only the information available in the context."
)
try:
response = openai.chat.completions.create( # Use the new chat completions API
model= "gpt-3.5-turbo", #"gpt-4", #"gpt-3.5-turbo" Or use another suitable model like gpt-4
messages=[{"role": "user", "content": prompt}],
max_tokens=300,
temperature=0.7,
)
return response.choices[0].message.content.strip() # Extract content from message
except Exception as e:
return f"Error generating response: {str(e)}" |