Spaces:
Sleeping
Sleeping
Implement asynchronous response generation and enhance file upload processing
Browse files- Added `acreate_single_response` method to `ChatOpenAI` for non-streamed asynchronous responses.
- Updated file upload handling in `main.py` to generate document descriptions and suggested questions using the new method.
- Modified frontend components to display document descriptions and suggested questions, allowing users to select questions for chat input.
- Enhanced `Chat` component to handle selected questions and update input accordingly.
- aimakerspace/openai_utils/chatmodel.py +20 -0
- api/main.py +45 -1
- app/frontend/src/App.js +39 -4
- app/frontend/src/components/Chat.js +13 -2
- app/frontend/src/components/FileUpload.js +5 -1
aimakerspace/openai_utils/chatmodel.py
CHANGED
|
@@ -43,3 +43,23 @@ class ChatOpenAI:
|
|
| 43 |
content = chunk.choices[0].delta.content
|
| 44 |
if content is not None:
|
| 45 |
yield content
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
content = chunk.choices[0].delta.content
|
| 44 |
if content is not None:
|
| 45 |
yield content
|
| 46 |
+
|
| 47 |
+
async def acreate_single_response(self, prompt_text, **kwargs):
|
| 48 |
+
"""
|
| 49 |
+
Create a single non-streamed response asynchronously.
|
| 50 |
+
|
| 51 |
+
:param prompt_text: Text prompt as a string
|
| 52 |
+
:param kwargs: Additional parameters to pass to the completion API
|
| 53 |
+
:return: The text response
|
| 54 |
+
"""
|
| 55 |
+
messages = [{"role": "user", "content": prompt_text}]
|
| 56 |
+
|
| 57 |
+
client = AsyncOpenAI()
|
| 58 |
+
response = await client.chat.completions.create(
|
| 59 |
+
model=self.model_name,
|
| 60 |
+
messages=messages,
|
| 61 |
+
stream=False,
|
| 62 |
+
**kwargs
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
return response.choices[0].message.content
|
api/main.py
CHANGED
|
@@ -98,7 +98,51 @@ async def upload_file(file: UploadFile = File(...), session_id: str = Form(...))
|
|
| 98 |
# Store the retrieval pipeline in the user session
|
| 99 |
user_sessions[session_id] = retrieval_pipeline
|
| 100 |
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
finally:
|
| 104 |
# Clean up the temporary file
|
|
|
|
| 98 |
# Store the retrieval pipeline in the user session
|
| 99 |
user_sessions[session_id] = retrieval_pipeline
|
| 100 |
|
| 101 |
+
# Generate document description and suggested questions
|
| 102 |
+
doc_content = "\n".join(texts[:5]) # Use first few chunks for summary
|
| 103 |
+
|
| 104 |
+
description_prompt = f"""
|
| 105 |
+
Please provide a brief description of this document in 2-3 sentences:
|
| 106 |
+
{doc_content}
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
questions_prompt = f"""
|
| 110 |
+
Based on this document content, please suggest 3 specific questions that would be informative to ask:
|
| 111 |
+
{doc_content}
|
| 112 |
+
|
| 113 |
+
Format your response as a JSON array with 3 question strings.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
# Get document description
|
| 117 |
+
description_response = await chat_openai.acreate_single_response(description_prompt)
|
| 118 |
+
document_description = description_response.strip()
|
| 119 |
+
|
| 120 |
+
# Get suggested questions
|
| 121 |
+
questions_response = await chat_openai.acreate_single_response(questions_prompt)
|
| 122 |
+
|
| 123 |
+
# Try to parse the questions as JSON, or extract them as best as possible
|
| 124 |
+
try:
|
| 125 |
+
import json
|
| 126 |
+
suggested_questions = json.loads(questions_response)
|
| 127 |
+
except:
|
| 128 |
+
# Extract questions with a fallback method
|
| 129 |
+
import re
|
| 130 |
+
questions = re.findall(r'["\']([^"\']+)["\']', questions_response)
|
| 131 |
+
if not questions or len(questions) < 3:
|
| 132 |
+
questions = [q.strip() for q in questions_response.split("\n") if "?" in q]
|
| 133 |
+
if not questions or len(questions) < 3:
|
| 134 |
+
questions = ["What is the main topic of this document?",
|
| 135 |
+
"What are the key points discussed in the document?",
|
| 136 |
+
"How can I apply the information in this document?"]
|
| 137 |
+
suggested_questions = questions[:3]
|
| 138 |
+
|
| 139 |
+
return {
|
| 140 |
+
"status": "success",
|
| 141 |
+
"message": f"Processed {file.filename}",
|
| 142 |
+
"session_id": session_id,
|
| 143 |
+
"document_description": document_description,
|
| 144 |
+
"suggested_questions": suggested_questions
|
| 145 |
+
}
|
| 146 |
|
| 147 |
finally:
|
| 148 |
# Clean up the temporary file
|
app/frontend/src/App.js
CHANGED
|
@@ -7,6 +7,9 @@ function App() {
|
|
| 7 |
const [sessionId, setSessionId] = useState('');
|
| 8 |
const [isFileUploaded, setIsFileUploaded] = useState(false);
|
| 9 |
const [fileName, setFileName] = useState('');
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
useEffect(() => {
|
| 12 |
// Generate a unique session ID if one doesn't exist
|
|
@@ -15,9 +18,15 @@ function App() {
|
|
| 15 |
}
|
| 16 |
}, [sessionId]);
|
| 17 |
|
| 18 |
-
const handleFileUploadSuccess = (fileName) => {
|
| 19 |
setIsFileUploaded(true);
|
| 20 |
setFileName(fileName);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
};
|
| 22 |
|
| 23 |
return (
|
|
@@ -35,10 +44,36 @@ function App() {
|
|
| 35 |
/>
|
| 36 |
) : (
|
| 37 |
<div className="rounded-lg border border-border bg-card p-6 shadow-sm">
|
| 38 |
-
<div className="mb-
|
| 39 |
-
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
</div>
|
| 41 |
-
<Chat
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
</div>
|
| 43 |
)}
|
| 44 |
</main>
|
|
|
|
| 7 |
const [sessionId, setSessionId] = useState('');
|
| 8 |
const [isFileUploaded, setIsFileUploaded] = useState(false);
|
| 9 |
const [fileName, setFileName] = useState('');
|
| 10 |
+
const [docDescription, setDocDescription] = useState('');
|
| 11 |
+
const [suggestedQuestions, setSuggestedQuestions] = useState([]);
|
| 12 |
+
const [selectedQuestion, setSelectedQuestion] = useState('');
|
| 13 |
|
| 14 |
useEffect(() => {
|
| 15 |
// Generate a unique session ID if one doesn't exist
|
|
|
|
| 18 |
}
|
| 19 |
}, [sessionId]);
|
| 20 |
|
| 21 |
+
const handleFileUploadSuccess = (fileName, description, questions) => {
|
| 22 |
setIsFileUploaded(true);
|
| 23 |
setFileName(fileName);
|
| 24 |
+
setDocDescription(description);
|
| 25 |
+
setSuggestedQuestions(questions);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
const handleQuestionSelect = (question) => {
|
| 29 |
+
setSelectedQuestion(question);
|
| 30 |
};
|
| 31 |
|
| 32 |
return (
|
|
|
|
| 44 |
/>
|
| 45 |
) : (
|
| 46 |
<div className="rounded-lg border border-border bg-card p-6 shadow-sm">
|
| 47 |
+
<div className="mb-6">
|
| 48 |
+
<div className="rounded-md bg-muted p-3 mb-3">
|
| 49 |
+
<h3 className="font-medium mb-1">Using file: <span className="font-bold">{fileName}</span></h3>
|
| 50 |
+
<p className="text-sm text-muted-foreground">{docDescription}</p>
|
| 51 |
+
</div>
|
| 52 |
+
|
| 53 |
+
{suggestedQuestions && suggestedQuestions.length > 0 && (
|
| 54 |
+
<div className="space-y-2">
|
| 55 |
+
<h4 className="text-sm font-medium">Suggested questions:</h4>
|
| 56 |
+
<div className="flex flex-wrap gap-2">
|
| 57 |
+
{suggestedQuestions.map((question, idx) => (
|
| 58 |
+
<button
|
| 59 |
+
key={idx}
|
| 60 |
+
className="text-xs bg-secondary text-secondary-foreground px-3 py-1 rounded-full hover:bg-secondary/80"
|
| 61 |
+
onClick={() => handleQuestionSelect(question)}
|
| 62 |
+
>
|
| 63 |
+
{question}
|
| 64 |
+
</button>
|
| 65 |
+
))}
|
| 66 |
+
</div>
|
| 67 |
+
</div>
|
| 68 |
+
)}
|
| 69 |
</div>
|
| 70 |
+
<Chat
|
| 71 |
+
sessionId={sessionId}
|
| 72 |
+
docDescription={docDescription}
|
| 73 |
+
suggestedQuestions={suggestedQuestions}
|
| 74 |
+
selectedQuestion={selectedQuestion}
|
| 75 |
+
onQuestionSelected={() => setSelectedQuestion('')}
|
| 76 |
+
/>
|
| 77 |
</div>
|
| 78 |
)}
|
| 79 |
</main>
|
app/frontend/src/components/Chat.js
CHANGED
|
@@ -3,11 +3,12 @@ import axios from 'axios';
|
|
| 3 |
import { Button } from './ui/button';
|
| 4 |
import { Input } from './ui/input';
|
| 5 |
|
| 6 |
-
const Chat = ({ sessionId }) => {
|
| 7 |
const [messages, setMessages] = useState([]);
|
| 8 |
const [input, setInput] = useState('');
|
| 9 |
const [isLoading, setIsLoading] = useState(false);
|
| 10 |
const messagesEndRef = useRef(null);
|
|
|
|
| 11 |
|
| 12 |
const scrollToBottom = () => {
|
| 13 |
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
|
@@ -17,6 +18,14 @@ const Chat = ({ sessionId }) => {
|
|
| 17 |
scrollToBottom();
|
| 18 |
}, [messages]);
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
const handleInputChange = (e) => {
|
| 21 |
setInput(e.target.value);
|
| 22 |
};
|
|
@@ -77,7 +86,7 @@ const Chat = ({ sessionId }) => {
|
|
| 77 |
</div>
|
| 78 |
<h3 className="mb-1 text-lg font-semibold">Welcome to the RAG Chat!</h3>
|
| 79 |
<p className="text-sm text-muted-foreground">
|
| 80 |
-
Ask questions about the document you uploaded.
|
| 81 |
</p>
|
| 82 |
</div>
|
| 83 |
) : (
|
|
@@ -119,6 +128,8 @@ const Chat = ({ sessionId }) => {
|
|
| 119 |
<form onSubmit={handleSubmit} className="border-t border-border p-4">
|
| 120 |
<div className="flex space-x-2">
|
| 121 |
<Input
|
|
|
|
|
|
|
| 122 |
type="text"
|
| 123 |
value={input}
|
| 124 |
onChange={handleInputChange}
|
|
|
|
| 3 |
import { Button } from './ui/button';
|
| 4 |
import { Input } from './ui/input';
|
| 5 |
|
| 6 |
+
const Chat = ({ sessionId, docDescription, suggestedQuestions, selectedQuestion, onQuestionSelected }) => {
|
| 7 |
const [messages, setMessages] = useState([]);
|
| 8 |
const [input, setInput] = useState('');
|
| 9 |
const [isLoading, setIsLoading] = useState(false);
|
| 10 |
const messagesEndRef = useRef(null);
|
| 11 |
+
const inputRef = useRef(null);
|
| 12 |
|
| 13 |
const scrollToBottom = () => {
|
| 14 |
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
|
|
|
| 18 |
scrollToBottom();
|
| 19 |
}, [messages]);
|
| 20 |
|
| 21 |
+
// Handle when a suggested question is selected
|
| 22 |
+
useEffect(() => {
|
| 23 |
+
if (selectedQuestion) {
|
| 24 |
+
setInput(selectedQuestion);
|
| 25 |
+
onQuestionSelected(); // Clear the selected question after setting it
|
| 26 |
+
}
|
| 27 |
+
}, [selectedQuestion, onQuestionSelected]);
|
| 28 |
+
|
| 29 |
const handleInputChange = (e) => {
|
| 30 |
setInput(e.target.value);
|
| 31 |
};
|
|
|
|
| 86 |
</div>
|
| 87 |
<h3 className="mb-1 text-lg font-semibold">Welcome to the RAG Chat!</h3>
|
| 88 |
<p className="text-sm text-muted-foreground">
|
| 89 |
+
Ask questions about the document you uploaded or click one of the suggested questions above.
|
| 90 |
</p>
|
| 91 |
</div>
|
| 92 |
) : (
|
|
|
|
| 128 |
<form onSubmit={handleSubmit} className="border-t border-border p-4">
|
| 129 |
<div className="flex space-x-2">
|
| 130 |
<Input
|
| 131 |
+
id="chat-input"
|
| 132 |
+
ref={inputRef}
|
| 133 |
type="text"
|
| 134 |
value={input}
|
| 135 |
onChange={handleInputChange}
|
app/frontend/src/components/FileUpload.js
CHANGED
|
@@ -44,7 +44,11 @@ const FileUpload = ({ sessionId, onUploadSuccess }) => {
|
|
| 44 |
|
| 45 |
if (response.data.status === 'success') {
|
| 46 |
setIsUploading(false);
|
| 47 |
-
onUploadSuccess(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
} else {
|
| 49 |
setIsUploading(false);
|
| 50 |
setErrorMessage(response.data.message || 'Upload failed');
|
|
|
|
| 44 |
|
| 45 |
if (response.data.status === 'success') {
|
| 46 |
setIsUploading(false);
|
| 47 |
+
onUploadSuccess(
|
| 48 |
+
file.name,
|
| 49 |
+
response.data.document_description || 'No description available',
|
| 50 |
+
response.data.suggested_questions || []
|
| 51 |
+
);
|
| 52 |
} else {
|
| 53 |
setIsUploading(false);
|
| 54 |
setErrorMessage(response.data.message || 'Upload failed');
|