Spaces:
Sleeping
Sleeping
Update chatbot.py
Browse files- chatbot.py +359 -207
chatbot.py
CHANGED
|
@@ -1,230 +1,382 @@
|
|
| 1 |
-
import
|
| 2 |
-
from sqlalchemy.exc import SQLAlchemyError
|
| 3 |
-
from utils import InnovativeIdea, init_db, get_db, SessionLocal, get_llm_response
|
| 4 |
-
from data_models import IdeaForm
|
| 5 |
-
from chatbot import InnovativeIdeaChatbot
|
| 6 |
-
from config import MODELS, DEFAULT_SYSTEM_PROMPT, STAGES
|
| 7 |
import logging
|
| 8 |
-
import os
|
| 9 |
-
from typing import Dict, Any
|
| 10 |
import re
|
| 11 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
def
|
| 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 |
try:
|
| 51 |
-
|
| 52 |
-
if
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
except Exception as e:
|
| 72 |
-
logging.error(f"
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
return
|
| 78 |
-
|
| 79 |
-
def
|
| 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 |
-
outputs=[chatbot] + list(form_fields.values()))
|
| 155 |
-
|
| 156 |
-
# Update form field visibility based on selected stage
|
| 157 |
-
stages.change(
|
| 158 |
-
lambda s: [gr.update(visible=(stage["name"] == s)) for stage in STAGES],
|
| 159 |
-
inputs=[stages],
|
| 160 |
-
outputs=list(form_fields.values())
|
| 161 |
)
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
| 170 |
else:
|
| 171 |
-
|
|
|
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
| 184 |
)
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
start_over,
|
| 189 |
-
outputs=[chatbot, msg] + [form_fields[stage["name"]] for stage in STAGES] + [stages]
|
| 190 |
-
)
|
| 191 |
|
| 192 |
-
|
| 193 |
-
demo.load(lambda: ([[None, innovative_chatbot.get_initial_greeting()]], ""),
|
| 194 |
-
outputs=[chatbot, msg])
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
def main():
|
| 207 |
-
try:
|
| 208 |
-
demo = create_gradio_interface()
|
| 209 |
-
return demo
|
| 210 |
-
except ImportError as e:
|
| 211 |
-
logging.error(f"Import error: {str(e)}", exc_info=True)
|
| 212 |
-
print(f"An import error occurred: {str(e)}")
|
| 213 |
-
print("Please check your import statements and ensure there are no circular dependencies.")
|
| 214 |
-
return None
|
| 215 |
-
except Exception as e:
|
| 216 |
-
logging.error(f"Failed to initialize application: {str(e)}", exc_info=True)
|
| 217 |
-
print(f"An unexpected error occurred: {str(e)}")
|
| 218 |
-
print("Please check the log file for more details.")
|
| 219 |
-
return None
|
| 220 |
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Tuple, Dict, Any, Optional
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import logging
|
|
|
|
|
|
|
| 3 |
import re
|
| 4 |
+
from data_models import IdeaForm, IDEA_STAGES
|
| 5 |
+
from config import DEFAULT_SYSTEM_PROMPT, STAGES
|
| 6 |
+
from utils import (
|
| 7 |
+
get_llm_response, extract_form_data, save_idea_to_database,
|
| 8 |
+
load_idea_from_database, update_idea_in_database,
|
| 9 |
+
get_db, clear_database, init_db, create_tables,
|
| 10 |
+
perform_web_search, optimize_search_query,
|
| 11 |
+
SessionLocal, InnovativeIdea
|
| 12 |
+
)
|
| 13 |
|
| 14 |
+
class InnovativeIdeaChatbot:
|
| 15 |
+
def __init__(self):
|
| 16 |
+
create_tables()
|
| 17 |
+
init_db()
|
| 18 |
+
self.idea_form = IdeaForm()
|
| 19 |
+
self.chat_history = []
|
| 20 |
+
self.idea_id = None
|
| 21 |
+
self.current_stage = None
|
| 22 |
+
self.api_key = None
|
| 23 |
+
self.add_system_message(self.get_initial_greeting())
|
| 24 |
|
| 25 |
+
def get_initial_greeting(self) -> str:
|
| 26 |
+
greeting = """
|
| 27 |
+
Welcome to the Innovative Idea Generator! I'm Myamoto, your AI assistant designed to help you refine and develop your innovative ideas.
|
| 28 |
+
Here's how we'll work together:
|
| 29 |
+
1. We'll go through 10 stages to explore different aspects of your idea.
|
| 30 |
+
2. At each stage, I'll ask you questions and provide feedback to help you think deeper about your concept.
|
| 31 |
+
3. You can ask me questions at any time or request more information on a topic.
|
| 32 |
+
4. If you want to perform a web search for additional information, just start your message with '@' followed by your search query.
|
| 33 |
+
5. When you're ready to move to the next stage, simply type 'next'.
|
| 34 |
+
Let's start by exploring your innovative idea! What's the name of your idea, or would you like help coming up with one?
|
| 35 |
+
"""
|
| 36 |
+
self.greeted = True
|
| 37 |
+
return greeting
|
| 38 |
|
| 39 |
+
def add_system_message(self, message: str):
|
| 40 |
+
self.chat_history.append(("System", message))
|
| 41 |
+
|
| 42 |
+
def set_api_key(self, api_key: str):
|
| 43 |
+
self.api_key = api_key
|
| 44 |
+
|
| 45 |
+
def activate_stage(self, stage_name: str) -> Optional[str]:
|
| 46 |
+
self.current_stage = stage_name
|
| 47 |
+
for stage in STAGES:
|
| 48 |
+
if stage["name"] == stage_name:
|
| 49 |
+
return f"Let's work on the '{stage_name}' stage. {stage['question']}"
|
| 50 |
+
return None
|
| 51 |
+
|
| 52 |
+
def process_stage_input(self, stage_name: str, message: str, model: str, system_prompt: str, thinking_budget: int) -> Tuple[List[Tuple[str, str]], Dict[str, Any]]:
|
| 53 |
+
if self.current_stage != stage_name:
|
| 54 |
+
activation_message = self.activate_stage(stage_name)
|
| 55 |
+
if activation_message is None:
|
| 56 |
+
error_message = f"Error: Unable to activate stage '{stage_name}'. Please check if the stage name is correct."
|
| 57 |
+
self.chat_history.append(("System", error_message))
|
| 58 |
+
return self.chat_history, self.idea_form.dict()
|
| 59 |
+
self.chat_history.append(("System", activation_message))
|
| 60 |
+
|
| 61 |
+
# Check for web search request
|
| 62 |
+
if message.startswith('@'):
|
| 63 |
+
search_query = message[1:].strip()
|
| 64 |
+
optimized_query = optimize_search_query(search_query, model)
|
| 65 |
+
search_results = perform_web_search(optimized_query)
|
| 66 |
+
self.chat_history.append(("Human", message))
|
| 67 |
+
self.chat_history.append(("AI", f"Here are the search results for '{optimized_query}':\n\n{search_results}"))
|
| 68 |
+
return self.chat_history, self.idea_form.dict()
|
| 69 |
+
|
| 70 |
+
# Generate the prompt for the current stage
|
| 71 |
+
stage_prompt = self.generate_prompt_for_stage(stage_name)
|
| 72 |
+
|
| 73 |
+
# Use the DEFAULT_SYSTEM_PROMPT from config.py
|
| 74 |
+
formatted_system_prompt = DEFAULT_SYSTEM_PROMPT.format(
|
| 75 |
+
current_stage=stage_name,
|
| 76 |
+
stage_prompt=stage_prompt
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# Combine the formatted system prompt and user's input
|
| 80 |
+
combined_prompt = f"{formatted_system_prompt}\n\nUser input: {message}"
|
| 81 |
+
|
| 82 |
+
# Get LLM response
|
| 83 |
+
llm_response = get_llm_response(combined_prompt, model, thinking_budget, self.api_key)
|
| 84 |
+
|
| 85 |
+
# Parse the LLM response to extract only the user-facing content
|
| 86 |
+
parsed_response = self.parse_llm_response(llm_response)
|
| 87 |
+
|
| 88 |
+
# Add the interaction to chat history
|
| 89 |
+
self.chat_history.append(("Human", message))
|
| 90 |
+
self.chat_history.append(("AI", parsed_response))
|
| 91 |
+
|
| 92 |
+
# Extract form data from the LLM response
|
| 93 |
+
form_data = extract_form_data(llm_response)
|
| 94 |
+
|
| 95 |
+
# Update the idea form
|
| 96 |
+
if stage_name in form_data:
|
| 97 |
+
setattr(self.idea_form, stage_name.lower().replace(" ", "_"), form_data[stage_name])
|
| 98 |
+
|
| 99 |
+
return self.chat_history, self.idea_form.dict()
|
| 100 |
+
|
| 101 |
+
def parse_llm_response(self, response: str) -> str:
|
| 102 |
+
# Remove content within <form_data> tags
|
| 103 |
+
response = re.sub(r'<form_data>.*?</form_data>', '', response, flags=re.DOTALL)
|
| 104 |
+
|
| 105 |
+
# Remove content within <reflection> tags
|
| 106 |
+
response = re.sub(r'<reflection>.*?</reflection>', '', response, flags=re.DOTALL)
|
| 107 |
+
|
| 108 |
+
# Remove content within <analysis> tags
|
| 109 |
+
response = re.sub(r'<analysis>.*?</analysis>', '', response, flags=re.DOTALL)
|
| 110 |
+
|
| 111 |
+
# Remove content within <summary> tags
|
| 112 |
+
response = re.sub(r'<summary>.*?</summary>', '', response, flags=re.DOTALL)
|
| 113 |
+
|
| 114 |
+
# Remove content within <step> tags
|
| 115 |
+
response = re.sub(r'<step>.*?</step>', '', response, flags=re.DOTALL)
|
| 116 |
+
|
| 117 |
+
# Remove any remaining HTML-like tags
|
| 118 |
+
response = re.sub(r'<[^>]+>', '', response)
|
| 119 |
+
|
| 120 |
+
# Remove extra whitespace and newlines
|
| 121 |
+
response = re.sub(r'\s+', ' ', response).strip()
|
| 122 |
+
|
| 123 |
+
return response
|
| 124 |
+
|
| 125 |
+
def fill_out_form(self, current_stage: str, model: str, thinking_budget: int) -> Dict[str, str]:
|
| 126 |
+
form_data = {}
|
| 127 |
+
for stage in STAGES:
|
| 128 |
+
stage_name = stage["name"]
|
| 129 |
+
if stage_name == current_stage:
|
| 130 |
+
# Generate new data for the current stage
|
| 131 |
+
form_data[stage["field"]] = self.generate_form_data(stage_name, model, thinking_budget)
|
| 132 |
+
else:
|
| 133 |
+
# Use existing data for other stages
|
| 134 |
+
form_data[stage["field"]] = getattr(self.idea_form, stage["field"], "")
|
| 135 |
+
|
| 136 |
+
# Update the idea form
|
| 137 |
+
for stage in STAGES:
|
| 138 |
+
setattr(self.idea_form, stage["field"], form_data[stage["field"]])
|
| 139 |
+
|
| 140 |
+
# Save to database
|
| 141 |
try:
|
| 142 |
+
new_session = SessionLocal()
|
| 143 |
+
if self.idea_id:
|
| 144 |
+
update_idea_in_database(self.idea_id, self.idea_form, new_session)
|
| 145 |
+
else:
|
| 146 |
+
self.idea_id = save_idea_to_database(self.idea_form, new_session)
|
| 147 |
+
new_session.commit()
|
| 148 |
+
except Exception as e:
|
| 149 |
+
logging.error(f"Error saving idea to database: {str(e)}")
|
| 150 |
+
new_session.rollback()
|
| 151 |
+
finally:
|
| 152 |
+
new_session.close()
|
| 153 |
+
|
| 154 |
+
return form_data
|
| 155 |
|
| 156 |
+
def generate_prompt_for_stage(self, stage: str) -> str:
|
| 157 |
+
for s in IDEA_STAGES:
|
| 158 |
+
if s.name == stage:
|
| 159 |
+
return f"We are currently working on the '{stage}' stage. {s.question}"
|
| 160 |
+
return f"We are currently working on the '{stage}' stage. Please provide relevant information."
|
| 161 |
|
| 162 |
+
def reset(self):
|
| 163 |
+
self.chat_history = []
|
| 164 |
+
self.idea_form = IdeaForm()
|
| 165 |
+
self.idea_id = None
|
| 166 |
+
self.current_stage = None
|
| 167 |
+
self.add_system_message(self.get_initial_greeting())
|
| 168 |
+
try:
|
| 169 |
+
new_session = SessionLocal()
|
| 170 |
+
clear_database(new_session)
|
| 171 |
+
new_session.commit()
|
| 172 |
+
except Exception as e:
|
| 173 |
+
logging.error(f"Error clearing database: {str(e)}")
|
| 174 |
+
new_session.rollback()
|
| 175 |
+
finally:
|
| 176 |
+
new_session.close()
|
| 177 |
+
return self.chat_history, self.idea_form.dict()
|
| 178 |
|
| 179 |
+
def start_over(self):
|
| 180 |
+
self.chat_history = []
|
| 181 |
+
self.idea_form = IdeaForm()
|
| 182 |
+
self.current_stage = None
|
| 183 |
+
self.add_system_message(self.get_initial_greeting())
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
new_session = SessionLocal()
|
| 187 |
+
# Clear the existing database
|
| 188 |
+
clear_database(new_session)
|
| 189 |
+
|
| 190 |
+
# Create a new empty idea
|
| 191 |
+
new_idea = InnovativeIdea()
|
| 192 |
+
new_session.add(new_idea)
|
| 193 |
+
new_session.commit()
|
| 194 |
+
new_session.refresh(new_idea)
|
| 195 |
+
|
| 196 |
+
# Update the idea_id
|
| 197 |
+
self.idea_id = new_idea.id
|
| 198 |
+
|
| 199 |
+
new_session.close()
|
| 200 |
except Exception as e:
|
| 201 |
+
logging.error(f"Error in start_over: {str(e)}")
|
| 202 |
+
if 'new_session' in locals():
|
| 203 |
+
new_session.rollback()
|
| 204 |
+
new_session.close()
|
| 205 |
+
|
| 206 |
+
return self.chat_history, self.idea_form.dict(), STAGES[0]["name"]
|
| 207 |
+
|
| 208 |
+
def update_idea_form(self, stage_name: str, form_data: str):
|
| 209 |
+
setattr(self.idea_form, stage_name.lower().replace(" ", "_"), form_data)
|
| 210 |
+
try:
|
| 211 |
+
new_session = SessionLocal()
|
| 212 |
+
if self.idea_id:
|
| 213 |
+
update_idea_in_database(self.idea_id, self.idea_form, new_session)
|
| 214 |
+
else:
|
| 215 |
+
self.idea_id = save_idea_to_database(self.idea_form, new_session)
|
| 216 |
+
new_session.commit()
|
| 217 |
+
except Exception as e:
|
| 218 |
+
logging.error(f"Error updating idea form: {str(e)}")
|
| 219 |
+
new_session.rollback()
|
| 220 |
+
finally:
|
| 221 |
+
new_session.close()
|
| 222 |
+
|
| 223 |
+
def generate_form_data(self, stage: str, model: str, thinking_budget: int) -> str:
|
| 224 |
+
# Prepare the conversation history for the LLM
|
| 225 |
+
conversation = "\n".join([f"{role}: {message}" for role, message in self.chat_history])
|
| 226 |
+
|
| 227 |
+
stage_prompt = self.generate_prompt_for_stage(stage)
|
| 228 |
+
|
| 229 |
+
formatted_system_prompt = DEFAULT_SYSTEM_PROMPT.format(
|
| 230 |
+
current_stage=stage,
|
| 231 |
+
stage_prompt=stage_prompt
|
| 232 |
)
|
| 233 |
|
| 234 |
+
prompt = f"""
|
| 235 |
+
{formatted_system_prompt}
|
| 236 |
+
|
| 237 |
+
Based on the following conversation, extract the relevant information for the '{stage}' stage of the innovative idea:
|
| 238 |
+
|
| 239 |
+
{conversation}
|
| 240 |
+
|
| 241 |
+
Please provide a concise summary for the '{stage}' stage, focusing only on the information relevant to this stage.
|
| 242 |
+
Your response should be structured as follows:
|
| 243 |
+
|
| 244 |
+
1. A brief analysis of the conversation related to this stage.
|
| 245 |
+
2. A concise summary of the key points relevant to this stage.
|
| 246 |
+
3. A suggested form entry for this stage, enclosed in <form_data></form_data> tags.
|
| 247 |
+
The form entry should be in the format: "{stage}: Content"
|
| 248 |
+
|
| 249 |
+
Remember to keep the form entry concise and directly related to the '{stage}' stage. Do not include information from other stages in the form entry.
|
| 250 |
+
"""
|
| 251 |
+
|
| 252 |
+
# Get LLM response
|
| 253 |
+
llm_response = get_llm_response(prompt, model, thinking_budget, self.api_key)
|
| 254 |
+
|
| 255 |
+
# Extract form data from the LLM response
|
| 256 |
+
form_data = extract_form_data(llm_response)
|
| 257 |
+
|
| 258 |
+
return form_data.get(stage, "")
|
| 259 |
+
|
| 260 |
+
def process_stage_input_stream(self, stage_name: str, message: str, model: str, system_prompt: str, thinking_budget: int):
|
| 261 |
+
if self.current_stage != stage_name:
|
| 262 |
+
activation_message = self.activate_stage(stage_name)
|
| 263 |
+
if activation_message is None:
|
| 264 |
+
error_message = f"Error: Unable to activate stage '{stage_name}'. Please check if the stage name is correct."
|
| 265 |
+
self.chat_history.append(("System", error_message))
|
| 266 |
+
yield self.chat_history, self.idea_form.dict()
|
| 267 |
+
return
|
| 268 |
+
|
| 269 |
+
self.chat_history.append(("System", activation_message))
|
| 270 |
+
|
| 271 |
+
# Check for web search request
|
| 272 |
+
if message.startswith('@'):
|
| 273 |
+
search_query = message[1:].strip()
|
| 274 |
+
optimized_query = optimize_search_query(search_query, model)
|
| 275 |
+
search_results = perform_web_search(optimized_query)
|
| 276 |
+
self.chat_history.append(("Human", message))
|
| 277 |
+
self.chat_history.append(("AI", f"Here are the search results for '{optimized_query}':\n\n{search_results}"))
|
| 278 |
+
yield self.chat_history, self.idea_form.dict()
|
| 279 |
+
return
|
| 280 |
+
|
| 281 |
+
# Generate the prompt for the current stage
|
| 282 |
+
stage_prompt = self.generate_prompt_for_stage(stage_name)
|
| 283 |
+
|
| 284 |
+
formatted_system_prompt = DEFAULT_SYSTEM_PROMPT.format(
|
| 285 |
+
current_stage=stage_name,
|
| 286 |
+
stage_prompt=stage_prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
)
|
| 288 |
|
| 289 |
+
combined_prompt = f"{formatted_system_prompt}\n\nUser input: {message}"
|
| 290 |
+
|
| 291 |
+
# Get LLM response
|
| 292 |
+
llm_response = get_llm_response(combined_prompt, model, thinking_budget, self.api_key)
|
| 293 |
+
parsed_response = self.parse_llm_response(llm_response)
|
| 294 |
+
|
| 295 |
+
self.chat_history.append(("Human", message))
|
| 296 |
+
self.chat_history.append(("AI", parsed_response))
|
| 297 |
+
|
| 298 |
+
form_data = extract_form_data(llm_response)
|
| 299 |
+
|
| 300 |
+
if stage_name in form_data:
|
| 301 |
+
setattr(self.idea_form, stage_name.lower().replace(" ", "_"), form_data[stage_name])
|
| 302 |
+
|
| 303 |
+
yield self.chat_history, self.idea_form.dict()
|
| 304 |
|
| 305 |
+
def fill_out_form_stream(self, current_stage: str, model: str, thinking_budget: int):
|
| 306 |
+
form_data = {}
|
| 307 |
+
for stage in IDEA_STAGES:
|
| 308 |
+
stage_name = stage.name
|
| 309 |
+
if stage_name == current_stage:
|
| 310 |
+
form_data[stage_name] = self.generate_form_data(stage_name, model, thinking_budget)
|
| 311 |
else:
|
| 312 |
+
form_data[stage_name] = getattr(self.idea_form, stage.field, "")
|
| 313 |
+
yield form_data
|
| 314 |
|
| 315 |
+
# Update the idea form
|
| 316 |
+
for stage in IDEA_STAGES:
|
| 317 |
+
setattr(self.idea_form, stage.field, form_data[stage.name])
|
| 318 |
+
|
| 319 |
+
# Save to database
|
| 320 |
+
try:
|
| 321 |
+
new_session = SessionLocal()
|
| 322 |
+
if self.idea_id:
|
| 323 |
+
update_idea_in_database(self.idea_id, self.idea_form, new_session)
|
| 324 |
+
else:
|
| 325 |
+
self.idea_id = save_idea_to_database(self.idea_form, new_session)
|
| 326 |
+
new_session.commit()
|
| 327 |
+
except Exception as e:
|
| 328 |
+
logging.error(f"Error saving idea to database: {str(e)}")
|
| 329 |
+
new_session.rollback()
|
| 330 |
+
finally:
|
| 331 |
+
new_session.close()
|
| 332 |
|
| 333 |
+
def generate_form_data_stream(self, stage: str, model: str, thinking_budget: int):
|
| 334 |
+
conversation = "\n".join([f"{role}: {message}" for role, message in self.chat_history])
|
| 335 |
+
|
| 336 |
+
stage_prompt = self.generate_prompt_for_stage(stage)
|
| 337 |
+
|
| 338 |
+
formatted_system_prompt = DEFAULT_SYSTEM_PROMPT.format(
|
| 339 |
+
current_stage=stage,
|
| 340 |
+
stage_prompt=stage_prompt
|
| 341 |
)
|
| 342 |
|
| 343 |
+
prompt = f"""
|
| 344 |
+
{formatted_system_prompt}
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
+
Based on the following conversation, extract the relevant information for the '{stage}' stage of the innovative idea:
|
|
|
|
|
|
|
| 347 |
|
| 348 |
+
{conversation}
|
| 349 |
+
|
| 350 |
+
Please provide a concise summary for the '{stage}' stage, focusing only on the information relevant to this stage.
|
| 351 |
+
Your response should be structured as follows:
|
| 352 |
+
|
| 353 |
+
1. A brief analysis of the conversation related to this stage.
|
| 354 |
+
2. A concise summary of the key points relevant to this stage.
|
| 355 |
+
3. A suggested form entry for this stage, enclosed in <form_data></form_data> tags.
|
| 356 |
+
The form entry should be in the format: "{stage}: Content"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
|
| 358 |
+
Remember to keep the form entry concise and directly related to the '{stage}' stage. Do not include information from other stages in the form entry.
|
| 359 |
+
"""
|
| 360 |
+
|
| 361 |
+
llm_response = get_llm_response(prompt, model, thinking_budget, self.api_key)
|
| 362 |
+
form_data = extract_form_data(llm_response)
|
| 363 |
+
return form_data.get(stage, "")
|
| 364 |
+
|
| 365 |
+
def update_form_field(self, stage_name: str, value: str):
|
| 366 |
+
setattr(self.idea_form, stage_name.lower().replace(" ", "_"), value)
|
| 367 |
+
try:
|
| 368 |
+
# Create a new session for this operation
|
| 369 |
+
new_session = SessionLocal()
|
| 370 |
+
if self.idea_id:
|
| 371 |
+
update_idea_in_database(self.idea_id, self.idea_form, new_session)
|
| 372 |
+
else:
|
| 373 |
+
self.idea_id = save_idea_to_database(self.idea_form, new_session)
|
| 374 |
+
new_session.commit()
|
| 375 |
+
except Exception as e:
|
| 376 |
+
logging.error(f"Error updating form field: {str(e)}")
|
| 377 |
+
# If an error occurs, rollback the new session
|
| 378 |
+
new_session.rollback()
|
| 379 |
+
finally:
|
| 380 |
+
# Always close the new session
|
| 381 |
+
new_session.close()
|
| 382 |
+
return value
|