Spaces:
Configuration error
Configuration error
1. UI changes; 2. new conversation loading logic for system chart extraction mode
Browse files- conversation_storage.py +9 -0
- hypotheses_generation.py +27 -1
- index.html +453 -255
- main.py +153 -69
- prompts.py +28 -0
conversation_storage.py
CHANGED
|
@@ -54,6 +54,15 @@ def get_conversations(extraction_id: str) -> Dict[str, Dict[str, Any]]:
|
|
| 54 |
"""
|
| 55 |
return SYSTEM_CHART_CONVERSATIONS.get(extraction_id, {})
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
def update_conversation(extraction_id: str, conversation_key: str, new_message, response):
|
| 58 |
"""
|
| 59 |
Update an existing conversation with a new message and response.
|
|
|
|
| 54 |
"""
|
| 55 |
return SYSTEM_CHART_CONVERSATIONS.get(extraction_id, {})
|
| 56 |
|
| 57 |
+
def get_all_conversations() -> Dict[str, Dict[str, Any]]:
|
| 58 |
+
"""
|
| 59 |
+
Get all conversations across every extraction ID.
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
Dict of extraction_id -> {conversation_key -> conversation_data}
|
| 63 |
+
"""
|
| 64 |
+
return SYSTEM_CHART_CONVERSATIONS
|
| 65 |
+
|
| 66 |
def update_conversation(extraction_id: str, conversation_key: str, new_message, response):
|
| 67 |
"""
|
| 68 |
Update an existing conversation with a new message and response.
|
hypotheses_generation.py
CHANGED
|
@@ -5,6 +5,32 @@ from prompts import create_hypotheses_generation_prompt
|
|
| 5 |
|
| 6 |
from typing import Tuple
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
PATTERN = re.compile(
|
| 9 |
r"PAPER:\s*(?P<paper>.*?)\s*[\r\n]+SYSTEM_CHART:\s*(?P<chart>.*?)(?=\s*={5,}|$)",
|
| 10 |
re.DOTALL
|
|
@@ -154,7 +180,7 @@ async def generate_hypotheses_from_system_charts(
|
|
| 154 |
else:
|
| 155 |
response = await llm.ainvoke(conversation_history)
|
| 156 |
|
| 157 |
-
iteration_content = response.content
|
| 158 |
all_iterations_content.append({
|
| 159 |
'iteration': iteration + 1,
|
| 160 |
'content': iteration_content
|
|
|
|
| 5 |
|
| 6 |
from typing import Tuple
|
| 7 |
|
| 8 |
+
|
| 9 |
+
def _content_to_text(content) -> str:
|
| 10 |
+
"""
|
| 11 |
+
Normalize LLM content payloads (string/list/dict) into plain text.
|
| 12 |
+
Anthropic and Gemini models may return a list of content blocks instead of
|
| 13 |
+
a plain string (same normalization as llm_content_to_text in main.py).
|
| 14 |
+
"""
|
| 15 |
+
if content is None:
|
| 16 |
+
return ""
|
| 17 |
+
if isinstance(content, str):
|
| 18 |
+
return content
|
| 19 |
+
if isinstance(content, list):
|
| 20 |
+
parts = []
|
| 21 |
+
for item in content:
|
| 22 |
+
text = _content_to_text(item)
|
| 23 |
+
if text:
|
| 24 |
+
parts.append(text)
|
| 25 |
+
return "\n".join(parts)
|
| 26 |
+
if isinstance(content, dict):
|
| 27 |
+
for key in ("text", "content", "output_text"):
|
| 28 |
+
if key in content:
|
| 29 |
+
return _content_to_text(content.get(key))
|
| 30 |
+
return str(content)
|
| 31 |
+
return str(content)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
PATTERN = re.compile(
|
| 35 |
r"PAPER:\s*(?P<paper>.*?)\s*[\r\n]+SYSTEM_CHART:\s*(?P<chart>.*?)(?=\s*={5,}|$)",
|
| 36 |
re.DOTALL
|
|
|
|
| 180 |
else:
|
| 181 |
response = await llm.ainvoke(conversation_history)
|
| 182 |
|
| 183 |
+
iteration_content = _content_to_text(response.content)
|
| 184 |
all_iterations_content.append({
|
| 185 |
'iteration': iteration + 1,
|
| 186 |
'content': iteration_content
|
index.html
CHANGED
|
@@ -197,7 +197,6 @@
|
|
| 197 |
}
|
| 198 |
|
| 199 |
.provider-badge[data-provider="openai"] { color: #047857; border-color: #a7f3d0; background: #ecfdf5; }
|
| 200 |
-
.provider-badge[data-provider="anthropic"] { color: #b45309; border-color: #fcd34d; background: #fffbeb; }
|
| 201 |
.provider-badge[data-provider="gemini"] { color: #1d4ed8; border-color: #bfdbfe; background: #eff6ff; }
|
| 202 |
.provider-badge[data-provider="error"] { color: #b91c1c; border-color: #fecaca; background: #fef2f2; }
|
| 203 |
|
|
@@ -506,6 +505,33 @@
|
|
| 506 |
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
| 507 |
animation: fadeIn 0.3s ease-in;
|
| 508 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 509 |
|
| 510 |
@keyframes fadeIn {
|
| 511 |
from { opacity: 0; transform: translateY(-10px); }
|
|
@@ -1581,7 +1607,6 @@
|
|
| 1581 |
line-height: 1.6;
|
| 1582 |
margin: 0;
|
| 1583 |
font-size: 1rem;
|
| 1584 |
-
max-width: 720px;
|
| 1585 |
}
|
| 1586 |
|
| 1587 |
html[data-mode="QA"] .section-title,
|
|
@@ -1755,18 +1780,20 @@
|
|
| 1755 |
color: #e2e8f0 !important;
|
| 1756 |
}
|
| 1757 |
|
| 1758 |
-
/* Ask Questions — vertical stack,
|
|
|
|
| 1759 |
html[data-mode="QA"] #askForm,
|
| 1760 |
-
html[data-mode="System Chart Extraction"] #askForm
|
|
|
|
| 1761 |
display: flex !important;
|
| 1762 |
flex-direction: column;
|
| 1763 |
align-items: stretch;
|
| 1764 |
gap: 16px;
|
| 1765 |
-
max-width: 520px;
|
| 1766 |
}
|
| 1767 |
|
| 1768 |
html[data-mode="QA"] #askForm .form-inputs,
|
| 1769 |
-
html[data-mode="System Chart Extraction"] #askForm .form-inputs
|
|
|
|
| 1770 |
display: flex;
|
| 1771 |
flex-direction: column;
|
| 1772 |
align-items: stretch;
|
|
@@ -1777,10 +1804,16 @@
|
|
| 1777 |
|
| 1778 |
html[data-mode="QA"] #databaseContainer,
|
| 1779 |
html[data-mode="System Chart Extraction"] #databaseContainer,
|
|
|
|
| 1780 |
html[data-mode="QA"] #visualizationContainer,
|
| 1781 |
html[data-mode="System Chart Extraction"] #visualizationContainer,
|
|
|
|
| 1782 |
html[data-mode="QA"] #questionContainer,
|
| 1783 |
-
html[data-mode="System Chart Extraction"] #questionContainer
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1784 |
width: 100%;
|
| 1785 |
max-width: 100%;
|
| 1786 |
}
|
|
@@ -2046,7 +2079,7 @@
|
|
| 2046 |
html[data-mode="QA"] .api-key-stack,
|
| 2047 |
html[data-mode="System Chart Extraction"] .api-key-stack,
|
| 2048 |
html[data-mode="Hypotheses Generation"] .api-key-stack {
|
| 2049 |
-
max-width:
|
| 2050 |
}
|
| 2051 |
|
| 2052 |
html[data-mode="QA"] .api-key-stack .input-row,
|
|
@@ -2085,11 +2118,6 @@
|
|
| 2085 |
html[data-mode="Hypotheses Generation"] .provider-badge[data-provider="openai"] {
|
| 2086 |
color: #34d399; border-color: rgba(16, 185, 129, 0.4); background: rgba(16, 185, 129, 0.1);
|
| 2087 |
}
|
| 2088 |
-
html[data-mode="QA"] .provider-badge[data-provider="anthropic"],
|
| 2089 |
-
html[data-mode="System Chart Extraction"] .provider-badge[data-provider="anthropic"],
|
| 2090 |
-
html[data-mode="Hypotheses Generation"] .provider-badge[data-provider="anthropic"] {
|
| 2091 |
-
color: #fbbf24; border-color: rgba(251, 191, 36, 0.4); background: rgba(251, 191, 36, 0.12);
|
| 2092 |
-
}
|
| 2093 |
html[data-mode="QA"] .provider-badge[data-provider="gemini"],
|
| 2094 |
html[data-mode="System Chart Extraction"] .provider-badge[data-provider="gemini"],
|
| 2095 |
html[data-mode="Hypotheses Generation"] .provider-badge[data-provider="gemini"] {
|
|
@@ -2159,6 +2187,18 @@
|
|
| 2159 |
color: var(--text) !important;
|
| 2160 |
}
|
| 2161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2162 |
html[data-mode="QA"] .user-bubble,
|
| 2163 |
html[data-mode="System Chart Extraction"] .user-bubble,
|
| 2164 |
html[data-mode="Hypotheses Generation"] .user-bubble {
|
|
@@ -2340,7 +2380,6 @@
|
|
| 2340 |
gap: 16px;
|
| 2341 |
align-items: stretch;
|
| 2342 |
margin-top: 12px;
|
| 2343 |
-
max-width: 520px;
|
| 2344 |
}
|
| 2345 |
|
| 2346 |
html[data-mode="QA"] .upload-panel-grid .stack,
|
|
@@ -2392,6 +2431,26 @@
|
|
| 2392 |
min-height: 200px;
|
| 2393 |
}
|
| 2394 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2395 |
html[data-mode="QA"] .dropzone input[type="file"],
|
| 2396 |
html[data-mode="System Chart Extraction"] .dropzone input[type="file"],
|
| 2397 |
html[data-mode="Hypotheses Generation"] .dropzone input[type="file"] {
|
|
@@ -2604,6 +2663,15 @@
|
|
| 2604 |
border: 1px solid rgba(239, 68, 68, 0.4) !important;
|
| 2605 |
}
|
| 2606 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2607 |
html[data-mode="QA"] hr,
|
| 2608 |
html[data-mode="System Chart Extraction"] hr,
|
| 2609 |
html[data-mode="Hypotheses Generation"] hr {
|
|
@@ -2716,13 +2784,26 @@
|
|
| 2716 |
background: linear-gradient(120deg, var(--primary), var(--accent-2)) !important;
|
| 2717 |
color: #fff !important;
|
| 2718 |
border: none !important;
|
| 2719 |
-
padding:
|
| 2720 |
-
border-radius:
|
|
|
|
| 2721 |
font-weight: 600;
|
| 2722 |
cursor: pointer;
|
| 2723 |
box-shadow: 0 6px 18px var(--accent-shadow);
|
| 2724 |
}
|
| 2725 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2726 |
/* Hide Upload Files section and renumber Ask Questions in Hypotheses Generation mode */
|
| 2727 |
html[data-mode="Hypotheses Generation"] #uploadSection {
|
| 2728 |
display: none !important;
|
|
@@ -2731,6 +2812,13 @@
|
|
| 2731 |
html[data-mode="Hypotheses Generation"] .step-number-default { display: none; }
|
| 2732 |
html[data-mode="Hypotheses Generation"] .step-number-hypotheses { display: inline; }
|
| 2733 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2734 |
/* Per-mode footer disclaimers (PlotExtract-style) */
|
| 2735 |
.mode-footer {
|
| 2736 |
display: none;
|
|
@@ -2787,10 +2875,10 @@
|
|
| 2787 |
<div class="stack compact api-key-stack">
|
| 2788 |
<label class="label" id="apiKeyLabel" for="apiKeyInput">API Key</label>
|
| 2789 |
<div class="input-row">
|
| 2790 |
-
<input type="password" id="apiKeyInput" name="api_key_input"
|
| 2791 |
<button class="ghost" id="toggleKey" type="button">Show</button>
|
| 2792 |
</div>
|
| 2793 |
-
<p class="hint left">We never store your key. It is used only for
|
| 2794 |
|
| 2795 |
<label class="label" for="modelSelect">Model</label>
|
| 2796 |
<select name="model" id="modelSelect" disabled>
|
|
@@ -2799,10 +2887,12 @@
|
|
| 2799 |
<span id="modelStatus" class="model-status"></span>
|
| 2800 |
</div>
|
| 2801 |
<div class="actions api-key-actions">
|
| 2802 |
-
<button type="submit" id="modelSubmitButton">
|
| 2803 |
</div>
|
| 2804 |
</form>
|
| 2805 |
|
|
|
|
|
|
|
| 2806 |
<hr id="uploadSectionDivider">
|
| 2807 |
|
| 2808 |
<div id="uploadSection">
|
|
@@ -2826,12 +2916,13 @@
|
|
| 2826 |
<button type="submit">Upload</button>
|
| 2827 |
</div>
|
| 2828 |
</form>
|
|
|
|
| 2829 |
</div>
|
| 2830 |
</section>
|
| 2831 |
|
| 2832 |
<!-- Workspace panel: ask + chat + continuations -->
|
| 2833 |
<section class="panel" id="workspacePanel">
|
| 2834 |
-
<div class="section-title"><span class="step-number-default">3)</span><span class="step-number-hypotheses">2)</span> Ask Questions</div>
|
| 2835 |
<form id="askForm">
|
| 2836 |
<div class="form-inputs">
|
| 2837 |
<div id="databaseContainer">
|
|
@@ -2854,19 +2945,38 @@
|
|
| 2854 |
|
| 2855 |
<div id="hypothesesContainer" style="display: none;">
|
| 2856 |
<div class="result-card hypotheses-options">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2857 |
<label style="display: block; margin-bottom: 8px;">
|
| 2858 |
-
|
| 2859 |
-
<
|
| 2860 |
-
<small class="hint left">
|
| 2861 |
-
</label>
|
| 2862 |
-
<label style="display: block; margin-bottom: 8px;">
|
| 2863 |
-
Mechanism 1:
|
| 2864 |
-
<input type="text" id="materialGoal1" placeholder="e.g., property #1 for xxx material" style="margin-top: 4px; width: 100%; padding: 6px;">
|
| 2865 |
-
</label>
|
| 2866 |
-
<label style="display: block; margin-bottom: 8px;">
|
| 2867 |
-
Mechanism 2:
|
| 2868 |
-
<input type="text" id="materialGoal2" placeholder="e.g., property #2 for xxx material" style="margin-top: 4px; width: 100%; padding: 6px;">
|
| 2869 |
</label>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2870 |
<label style="display: block; margin-bottom: 0;">
|
| 2871 |
Number of Iterations:
|
| 2872 |
<input type="number" id="iterationsCount" min="1" max="100" value="1" placeholder="1" style="margin-top: 4px; width: 100%; padding: 6px;">
|
|
@@ -2883,7 +2993,7 @@
|
|
| 2883 |
</div>
|
| 2884 |
</div>
|
| 2885 |
|
| 2886 |
-
<button type="submit">Ask</button>
|
| 2887 |
</form>
|
| 2888 |
|
| 2889 |
<div id="chat-area"></div>
|
|
@@ -2948,22 +3058,17 @@
|
|
| 2948 |
Load Conversation
|
| 2949 |
</button>
|
| 2950 |
</div>
|
| 2951 |
-
|
| 2952 |
-
|
| 2953 |
-
|
|
|
|
|
|
|
| 2954 |
<input type="text" id="followUpQuestion" placeholder="Ask a follow-up question about this paper...">
|
| 2955 |
-
|
| 2956 |
-
<
|
| 2957 |
-
Continue Conversation
|
| 2958 |
-
</button>
|
| 2959 |
</div>
|
| 2960 |
</form>
|
| 2961 |
</div>
|
| 2962 |
-
|
| 2963 |
-
<div id="conversation-history" style="display: none;">
|
| 2964 |
-
<h4 class="panel-subtitle">Conversation History:</h4>
|
| 2965 |
-
<div id="conversation-messages"></div>
|
| 2966 |
-
</div>
|
| 2967 |
</div>
|
| 2968 |
</section>
|
| 2969 |
|
|
@@ -2973,10 +3078,10 @@
|
|
| 2973 |
</div>
|
| 2974 |
|
| 2975 |
<div class="reference-item" id="systemChartReference">
|
| 2976 |
-
|
| 2977 |
</div>
|
| 2978 |
<div class="reference-item" id="hypothesesReference">
|
| 2979 |
-
|
| 2980 |
</div>
|
| 2981 |
</section>
|
| 2982 |
|
|
@@ -2998,8 +3103,7 @@
|
|
| 2998 |
</footer>
|
| 2999 |
<footer class="mode-footer footer" id="hypothesesFooter">
|
| 3000 |
<p>
|
| 3001 |
-
This tool generates materials design hypotheses by synergistically combining materials system charts,
|
| 3002 |
-
knowledge. Generated hypotheses are produced by LLMs and are not guaranteed to be
|
| 3003 |
scientifically valid or novel, so please take the
|
| 3004 |
results with caution. Always apply domain expertise and verify against the literature before acting
|
| 3005 |
on any hypothesis.
|
|
@@ -3051,7 +3155,7 @@
|
|
| 3051 |
const subheads = {
|
| 3052 |
'QA': 'Upload research papers, select a model, and ask questions across your documents.',
|
| 3053 |
'System Chart Extraction': 'Upload papers, select a model, and extract materials system charts linking processing, structure, and properties.',
|
| 3054 |
-
'Hypotheses Generation': 'Provide system charts and
|
| 3055 |
};
|
| 3056 |
subhead.textContent = subheads[window.selectedMode] || subhead.textContent;
|
| 3057 |
}
|
|
@@ -3140,8 +3244,10 @@
|
|
| 3140 |
|
| 3141 |
apiKeyInput.addEventListener('input', () => {
|
| 3142 |
const provider = detectProviderFromKey(apiKeyInput.value);
|
| 3143 |
-
if (provider) {
|
| 3144 |
-
setProviderBadge(
|
|
|
|
|
|
|
| 3145 |
} else {
|
| 3146 |
setProviderBadge('', null);
|
| 3147 |
}
|
|
@@ -3179,10 +3285,16 @@
|
|
| 3179 |
if (_modelsLoading) return false;
|
| 3180 |
|
| 3181 |
const provider = detectProviderFromKey(key);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3182 |
if (!provider) {
|
| 3183 |
setProviderBadge('error', 'unknown');
|
| 3184 |
setModelDropdownPlaceholder('Unsupported key format');
|
| 3185 |
-
setModelStatus('Use an OpenAI (sk-...)
|
| 3186 |
return false;
|
| 3187 |
}
|
| 3188 |
|
|
@@ -3239,6 +3351,31 @@
|
|
| 3239 |
await submitApiKey(formData);
|
| 3240 |
});
|
| 3241 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3242 |
// Function to submit API key to server
|
| 3243 |
async function submitApiKey(formData) {
|
| 3244 |
try {
|
|
@@ -3250,7 +3387,10 @@
|
|
| 3250 |
const data = await res.json();
|
| 3251 |
|
| 3252 |
if (!res.ok) {
|
| 3253 |
-
//
|
|
|
|
|
|
|
|
|
|
| 3254 |
const errorDiv = document.createElement('div');
|
| 3255 |
errorDiv.className = 'error-message';
|
| 3256 |
errorDiv.textContent = data.message || 'Error setting up model.';
|
|
@@ -3269,8 +3409,17 @@
|
|
| 3269 |
return false;
|
| 3270 |
}
|
| 3271 |
|
| 3272 |
-
//
|
| 3273 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3274 |
return true;
|
| 3275 |
} catch (error) {
|
| 3276 |
alert('Connection error: ' + error);
|
|
@@ -3312,7 +3461,11 @@
|
|
| 3312 |
throw new Error(data.message || `HTTP ${res.status} ${res.statusText}`);
|
| 3313 |
}
|
| 3314 |
|
| 3315 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3316 |
|
| 3317 |
// Update databases and goal options based on newly uploaded files
|
| 3318 |
setTimeout(loadAvailableDatabases, 500);
|
|
@@ -3322,6 +3475,8 @@
|
|
| 3322 |
startEmbeddingProgressTracking(category);
|
| 3323 |
}
|
| 3324 |
} catch (error) {
|
|
|
|
|
|
|
| 3325 |
alert('Error uploading file: ' + error);
|
| 3326 |
}
|
| 3327 |
});
|
|
@@ -3873,6 +4028,23 @@
|
|
| 3873 |
// Initial load
|
| 3874 |
setTimeout(loadAvailableDatabases, 1000); // Delay to ensure page is loaded
|
| 3875 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3876 |
|
| 3877 |
|
| 3878 |
|
|
@@ -4190,6 +4362,108 @@
|
|
| 4190 |
}
|
| 4191 |
});
|
| 4192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4193 |
// ========================
|
| 4194 |
// Hypotheses Generation Handler
|
| 4195 |
// ========================
|
|
@@ -4224,9 +4498,12 @@
|
|
| 4224 |
|
| 4225 |
// Validate material design goals
|
| 4226 |
if (!materialGoal1 || !materialGoal2) {
|
|
|
|
|
|
|
|
|
|
| 4227 |
const errorDiv = document.createElement('div');
|
| 4228 |
errorDiv.classList.add('chat-bubble', 'ai-bubble', 'error-bubble');
|
| 4229 |
-
errorDiv.innerHTML = '<strong>Error:</strong> Please provide both
|
| 4230 |
chatArea.appendChild(errorDiv);
|
| 4231 |
chatArea.scrollTop = chatArea.scrollHeight;
|
| 4232 |
return;
|
|
@@ -4316,7 +4593,7 @@
|
|
| 4316 |
// Create AI bubble for status
|
| 4317 |
const aiDiv = document.createElement('div');
|
| 4318 |
aiDiv.classList.add('chat-bubble', 'ai-bubble');
|
| 4319 |
-
aiDiv.innerHTML = `<strong>Hypotheses Generation Started</strong>
|
| 4320 |
chatArea.appendChild(aiDiv);
|
| 4321 |
|
| 4322 |
// Create progress tracking bubble
|
|
@@ -4386,24 +4663,27 @@
|
|
| 4386 |
currentExtractionId = extractionId;
|
| 4387 |
const conversationSection = document.getElementById('conversation-section');
|
| 4388 |
conversationSection.style.display = 'block';
|
| 4389 |
-
|
| 4390 |
-
// Load conversations
|
| 4391 |
-
loadConversations(
|
| 4392 |
}
|
| 4393 |
|
| 4394 |
-
//
|
| 4395 |
-
|
|
|
|
| 4396 |
try {
|
| 4397 |
-
const response = await fetch(
|
| 4398 |
const data = await response.json();
|
| 4399 |
-
|
| 4400 |
const conversationSelect = document.getElementById('conversationSelect');
|
| 4401 |
conversationSelect.innerHTML = '<option value="">Select a paper to continue conversation...</option>';
|
| 4402 |
-
|
| 4403 |
if (data.conversations && data.conversations.length > 0) {
|
| 4404 |
data.conversations.forEach(conv => {
|
| 4405 |
const option = document.createElement('option');
|
| 4406 |
-
option
|
|
|
|
|
|
|
| 4407 |
option.textContent = `${conv.title} (${conv.paper_type}, ${conv.message_count} messages)`;
|
| 4408 |
conversationSelect.appendChild(option);
|
| 4409 |
});
|
|
@@ -4422,100 +4702,93 @@
|
|
| 4422 |
|
| 4423 |
// Function to load conversation history
|
| 4424 |
async function loadConversationHistory(extractionId, conversationKey) {
|
|
|
|
|
|
|
| 4425 |
try {
|
| 4426 |
const response = await fetch(`/conversation_history/${extractionId}/${conversationKey}`);
|
| 4427 |
const data = await response.json();
|
| 4428 |
-
|
| 4429 |
-
const conversationHistory = document.getElementById('conversation-history');
|
| 4430 |
-
const conversationMessages = document.getElementById('conversation-messages');
|
| 4431 |
-
|
| 4432 |
conversationMessages.innerHTML = '';
|
| 4433 |
-
|
| 4434 |
if (data.history && data.history.length > 0) {
|
| 4435 |
data.history.forEach(message => {
|
| 4436 |
const messageDiv = document.createElement('div');
|
| 4437 |
-
|
| 4438 |
-
messageDiv.
|
| 4439 |
-
|
| 4440 |
-
|
| 4441 |
-
|
| 4442 |
-
messageDiv.style.backgroundColor = '#E8F5E8';
|
| 4443 |
-
messageDiv.style.borderLeft = '4px solid #4CAF50';
|
| 4444 |
-
messageDiv.innerHTML = `<strong>Human:</strong> ${message.content.replace(/\n/g, '<br>')}`;
|
| 4445 |
} else {
|
| 4446 |
-
|
| 4447 |
-
messageDiv.
|
| 4448 |
-
const formattedContent = message.content.replace(/\n/g, '<br>');
|
| 4449 |
-
messageDiv.innerHTML = `<strong>AI:</strong> ${formattedContent}`;
|
| 4450 |
}
|
| 4451 |
-
|
| 4452 |
conversationMessages.appendChild(messageDiv);
|
| 4453 |
});
|
| 4454 |
-
|
| 4455 |
-
conversationHistory.style.display = 'block';
|
| 4456 |
-
} else {
|
| 4457 |
-
conversationHistory.style.display = 'none';
|
| 4458 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4459 |
} catch (error) {
|
| 4460 |
console.error('Error loading conversation history:', error);
|
| 4461 |
-
|
| 4462 |
-
conversationHistory.style.display = 'none';
|
| 4463 |
}
|
| 4464 |
}
|
| 4465 |
|
| 4466 |
// Handle load conversation button click
|
| 4467 |
document.getElementById('loadConversationBtn').addEventListener('click', async () => {
|
| 4468 |
const conversationSelect = document.getElementById('conversationSelect');
|
| 4469 |
-
const
|
| 4470 |
-
|
| 4471 |
-
if (!
|
| 4472 |
alert('Please select a conversation to load');
|
| 4473 |
return;
|
| 4474 |
}
|
| 4475 |
-
|
| 4476 |
-
|
| 4477 |
-
|
|
|
|
|
|
|
| 4478 |
return;
|
| 4479 |
}
|
| 4480 |
-
|
| 4481 |
-
currentConversationKey =
|
| 4482 |
-
|
| 4483 |
-
//
|
| 4484 |
-
|
| 4485 |
-
|
| 4486 |
-
|
| 4487 |
-
// Load conversation history
|
| 4488 |
-
await loadConversationHistory(currentExtractionId, selectedConversation);
|
| 4489 |
-
|
| 4490 |
// Focus on the follow-up question input
|
| 4491 |
document.getElementById('followUpQuestion').focus();
|
| 4492 |
});
|
| 4493 |
|
| 4494 |
-
// Handle conversation form submission
|
|
|
|
| 4495 |
document.getElementById('conversationForm').addEventListener('submit', async (e) => {
|
| 4496 |
e.preventDefault();
|
| 4497 |
-
|
| 4498 |
-
const
|
| 4499 |
-
|
|
|
|
| 4500 |
if (!followUpQuestion) {
|
| 4501 |
alert('Please enter a follow-up question');
|
| 4502 |
return;
|
| 4503 |
}
|
| 4504 |
-
|
| 4505 |
if (!currentExtractionId || !currentConversationKey) {
|
| 4506 |
alert('Please select a conversation first');
|
| 4507 |
return;
|
| 4508 |
}
|
| 4509 |
-
|
| 4510 |
-
const
|
| 4511 |
-
|
| 4512 |
-
//
|
| 4513 |
const userDiv = document.createElement('div');
|
| 4514 |
userDiv.classList.add('chat-bubble', 'user-bubble');
|
| 4515 |
-
userDiv.innerText =
|
| 4516 |
-
|
| 4517 |
-
|
| 4518 |
-
//
|
| 4519 |
const loadingDiv = document.createElement('div');
|
| 4520 |
loadingDiv.classList.add('chat-bubble', 'ai-bubble', 'loading-bubble');
|
| 4521 |
loadingDiv.innerHTML = `
|
|
@@ -4528,76 +4801,43 @@
|
|
| 4528 |
</div>
|
| 4529 |
</div>
|
| 4530 |
`;
|
| 4531 |
-
|
| 4532 |
-
|
| 4533 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4534 |
try {
|
| 4535 |
-
// Prepare form data
|
| 4536 |
const formData = new FormData();
|
| 4537 |
formData.append('question', followUpQuestion);
|
| 4538 |
-
|
| 4539 |
-
// Send request to continue conversation
|
| 4540 |
const response = await fetch(`/continue_conversation/${currentExtractionId}/${currentConversationKey}`, {
|
| 4541 |
method: 'POST',
|
| 4542 |
body: formData
|
| 4543 |
});
|
| 4544 |
-
|
| 4545 |
-
// Remove loading bubble
|
| 4546 |
-
setTimeout(() => {
|
| 4547 |
-
chatArea.removeChild(loadingDiv);
|
| 4548 |
-
|
| 4549 |
-
(async () => {
|
| 4550 |
-
try {
|
| 4551 |
-
if (!response.ok) {
|
| 4552 |
-
const errorData = await response.json();
|
| 4553 |
-
const errorDiv = document.createElement('div');
|
| 4554 |
-
errorDiv.classList.add('chat-bubble', 'ai-bubble', 'error-bubble');
|
| 4555 |
-
errorDiv.innerHTML = `<strong>Error:</strong> ${errorData.error || 'Unknown error'}`;
|
| 4556 |
-
chatArea.appendChild(errorDiv);
|
| 4557 |
-
chatArea.scrollTop = chatArea.scrollHeight;
|
| 4558 |
-
return;
|
| 4559 |
-
}
|
| 4560 |
|
| 4561 |
-
|
| 4562 |
-
|
| 4563 |
-
|
| 4564 |
-
|
| 4565 |
-
|
| 4566 |
-
|
| 4567 |
-
|
| 4568 |
-
|
| 4569 |
-
|
| 4570 |
-
|
| 4571 |
-
|
| 4572 |
-
|
| 4573 |
-
// Clear the follow-up question input
|
| 4574 |
-
document.getElementById('followUpQuestion').value = '';
|
| 4575 |
-
|
| 4576 |
-
// Refresh conversation history
|
| 4577 |
-
await loadConversationHistory(currentExtractionId, currentConversationKey);
|
| 4578 |
-
|
| 4579 |
-
} catch (error) {
|
| 4580 |
-
console.error("Error processing conversation response:", error);
|
| 4581 |
-
const errorDiv = document.createElement('div');
|
| 4582 |
-
errorDiv.classList.add('chat-bubble', 'ai-bubble', 'error-bubble');
|
| 4583 |
-
errorDiv.innerHTML = `<strong>Error:</strong> Failed to process response`;
|
| 4584 |
-
chatArea.appendChild(errorDiv);
|
| 4585 |
-
chatArea.scrollTop = chatArea.scrollHeight;
|
| 4586 |
-
}
|
| 4587 |
-
})();
|
| 4588 |
-
}, 100);
|
| 4589 |
-
|
| 4590 |
} catch (error) {
|
| 4591 |
-
|
| 4592 |
-
setTimeout(() => {
|
| 4593 |
-
chatArea.removeChild(loadingDiv);
|
| 4594 |
-
|
| 4595 |
-
const errorDiv = document.createElement('div');
|
| 4596 |
-
errorDiv.classList.add('chat-bubble', 'ai-bubble', 'error-bubble');
|
| 4597 |
-
errorDiv.innerHTML = `<strong>Error:</strong> ${error.message || error}`;
|
| 4598 |
-
chatArea.appendChild(errorDiv);
|
| 4599 |
-
chatArea.scrollTop = chatArea.scrollHeight;
|
| 4600 |
-
}, 100);
|
| 4601 |
}
|
| 4602 |
});
|
| 4603 |
|
|
@@ -4690,8 +4930,7 @@
|
|
| 4690 |
const chatMessages = document.getElementById('hypothesis-chat-messages');
|
| 4691 |
chatMessages.innerHTML = `
|
| 4692 |
<div style="background: #f8f9fa; padding: 10px; border-radius: 4px; margin-bottom: 10px; border-left: 4px solid #4285F4;">
|
| 4693 |
-
<strong>System:</strong> I have loaded the context for your hypothesis analysis, including your <strong>provided paper content</strong> and <strong>${data.charts_found} referenced system charts</strong>. The conversation is ready!
|
| 4694 |
-
<small style="color: #666; margin-top: 5px; display: block;">Ask specific questions about alloy compositions, mechanisms, structures, or properties. Responses will include detailed scientific information from your provided content and the referenced charts.</small>
|
| 4695 |
</div>
|
| 4696 |
`;
|
| 4697 |
|
|
@@ -4729,7 +4968,7 @@
|
|
| 4729 |
// Add user message
|
| 4730 |
const userMessageDiv = document.createElement('div');
|
| 4731 |
userMessageDiv.style.cssText = 'background: #e8f5e8; padding: 10px; border-radius: 4px; margin-bottom: 10px; border-left: 4px solid #4caf50;';
|
| 4732 |
-
userMessageDiv.innerHTML = `<strong>You:</strong> ${message}`;
|
| 4733 |
chatMessages.appendChild(userMessageDiv);
|
| 4734 |
|
| 4735 |
// Clear input
|
|
@@ -4764,11 +5003,9 @@
|
|
| 4764 |
return;
|
| 4765 |
}
|
| 4766 |
|
| 4767 |
-
//
|
| 4768 |
const aiResponse = data.response;
|
| 4769 |
-
|
| 4770 |
-
const formattedResponse = aiResponse.replace(/\n/g, '<br>');
|
| 4771 |
-
loadingDiv.innerHTML = `<strong>AI:</strong> ${formattedResponse}`;
|
| 4772 |
chatMessages.scrollTop = chatMessages.scrollHeight;
|
| 4773 |
|
| 4774 |
console.log(`✅ Conversation response received: ${data.conversation_length} total exchanges, ${data.papers_count} papers, ${data.charts_count} charts in context`);
|
|
@@ -4877,77 +5114,38 @@
|
|
| 4877 |
return basicMarkdownToHtml(text);
|
| 4878 |
}
|
| 4879 |
|
| 4880 |
-
//
|
| 4881 |
-
marked
|
| 4882 |
-
|
| 4883 |
-
gfm: true,
|
| 4884 |
-
tables: true,
|
| 4885 |
-
sanitize: false,
|
| 4886 |
-
headerIds: false
|
| 4887 |
-
});
|
| 4888 |
-
|
| 4889 |
-
// Custom renderer for tables with better styling
|
| 4890 |
-
const renderer = new marked.Renderer();
|
| 4891 |
-
|
| 4892 |
-
// Custom table rendering
|
| 4893 |
-
renderer.table = function(header, body) {
|
| 4894 |
-
return `<div class="qa-table-wrap"><table class="qa-table"><thead>${header}</thead><tbody>${body}</tbody></table></div>`;
|
| 4895 |
-
};
|
| 4896 |
-
|
| 4897 |
-
// Custom table header rendering
|
| 4898 |
-
renderer.tablecell = function(content, flags) {
|
| 4899 |
-
const type = flags.header ? 'th' : 'td';
|
| 4900 |
-
return `<${type}>${content}</${type}>`;
|
| 4901 |
-
};
|
| 4902 |
-
|
| 4903 |
-
// Custom header rendering
|
| 4904 |
-
renderer.heading = function(text, level) {
|
| 4905 |
-
return `<h${level} class="qa-h qa-h${level}">${text}</h${level}>`;
|
| 4906 |
-
};
|
| 4907 |
-
|
| 4908 |
-
// Custom paragraph rendering
|
| 4909 |
-
renderer.paragraph = function(text) {
|
| 4910 |
-
return `<p class="qa-p">${text}</p>`;
|
| 4911 |
-
};
|
| 4912 |
-
|
| 4913 |
-
// Custom horizontal rule
|
| 4914 |
-
renderer.hr = function() {
|
| 4915 |
-
return '<hr class="qa-hr">';
|
| 4916 |
-
};
|
| 4917 |
-
|
| 4918 |
-
// Custom blockquote
|
| 4919 |
-
renderer.blockquote = function(quote) {
|
| 4920 |
-
return `<blockquote class="qa-blockquote">${quote}</blockquote>`;
|
| 4921 |
-
};
|
| 4922 |
-
|
| 4923 |
-
// Custom code
|
| 4924 |
-
renderer.code = function(code, language) {
|
| 4925 |
-
return `<pre class="qa-pre"><code>${code}</code></pre>`;
|
| 4926 |
-
};
|
| 4927 |
-
|
| 4928 |
-
// Custom inline code
|
| 4929 |
-
renderer.codespan = function(code) {
|
| 4930 |
-
return `<code class="qa-code-inline">${code}</code>`;
|
| 4931 |
-
};
|
| 4932 |
-
|
| 4933 |
-
// Custom list rendering
|
| 4934 |
-
renderer.list = function(body, ordered) {
|
| 4935 |
-
const type = ordered ? 'ol' : 'ul';
|
| 4936 |
-
return `<${type} class="qa-list">${body}</${type}>`;
|
| 4937 |
-
};
|
| 4938 |
-
|
| 4939 |
-
renderer.listitem = function(text) {
|
| 4940 |
-
return `<li class="qa-li">${text}</li>`;
|
| 4941 |
-
};
|
| 4942 |
-
|
| 4943 |
-
// Parse markdown with custom renderer
|
| 4944 |
try {
|
| 4945 |
-
const html = marked(text, {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4946 |
// If markdown markers still survive parsing, use robust fallback renderer.
|
| 4947 |
-
if (/\*\*|
|
| 4948 |
return basicMarkdownToHtml(text);
|
| 4949 |
}
|
| 4950 |
-
return
|
| 4951 |
} catch (error) {
|
| 4952 |
console.error('Error parsing markdown:', error);
|
| 4953 |
return basicMarkdownToHtml(text);
|
|
|
|
| 197 |
}
|
| 198 |
|
| 199 |
.provider-badge[data-provider="openai"] { color: #047857; border-color: #a7f3d0; background: #ecfdf5; }
|
|
|
|
| 200 |
.provider-badge[data-provider="gemini"] { color: #1d4ed8; border-color: #bfdbfe; background: #eff6ff; }
|
| 201 |
.provider-badge[data-provider="error"] { color: #b91c1c; border-color: #fecaca; background: #fef2f2; }
|
| 202 |
|
|
|
|
| 505 |
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
| 506 |
animation: fadeIn 0.3s ease-in;
|
| 507 |
}
|
| 508 |
+
|
| 509 |
+
.confirm-message {
|
| 510 |
+
background-color: #e6f4ea;
|
| 511 |
+
border-left: 4px solid #0F9D58;
|
| 512 |
+
color: #146c43;
|
| 513 |
+
padding: 12px 15px;
|
| 514 |
+
margin: 15px 0;
|
| 515 |
+
font-size: 0.9rem;
|
| 516 |
+
border-radius: 4px;
|
| 517 |
+
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
| 518 |
+
animation: fadeIn 0.3s ease-in;
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
.confirm-message[hidden] { display: none; }
|
| 522 |
+
|
| 523 |
+
.confirm-message .confirm-title {
|
| 524 |
+
font-weight: 600;
|
| 525 |
+
display: flex;
|
| 526 |
+
align-items: center;
|
| 527 |
+
gap: 6px;
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
.confirm-message .confirm-detail {
|
| 531 |
+
margin-top: 4px;
|
| 532 |
+
font-size: 0.82rem;
|
| 533 |
+
opacity: 0.9;
|
| 534 |
+
}
|
| 535 |
|
| 536 |
@keyframes fadeIn {
|
| 537 |
from { opacity: 0; transform: translateY(-10px); }
|
|
|
|
| 1607 |
line-height: 1.6;
|
| 1608 |
margin: 0;
|
| 1609 |
font-size: 1rem;
|
|
|
|
| 1610 |
}
|
| 1611 |
|
| 1612 |
html[data-mode="QA"] .section-title,
|
|
|
|
| 1780 |
color: #e2e8f0 !important;
|
| 1781 |
}
|
| 1782 |
|
| 1783 |
+
/* Ask Questions — vertical stack, full-width fields so long text doesn't
|
| 1784 |
+
wrap while horizontal space sits unused */
|
| 1785 |
html[data-mode="QA"] #askForm,
|
| 1786 |
+
html[data-mode="System Chart Extraction"] #askForm,
|
| 1787 |
+
html[data-mode="Hypotheses Generation"] #askForm {
|
| 1788 |
display: flex !important;
|
| 1789 |
flex-direction: column;
|
| 1790 |
align-items: stretch;
|
| 1791 |
gap: 16px;
|
|
|
|
| 1792 |
}
|
| 1793 |
|
| 1794 |
html[data-mode="QA"] #askForm .form-inputs,
|
| 1795 |
+
html[data-mode="System Chart Extraction"] #askForm .form-inputs,
|
| 1796 |
+
html[data-mode="Hypotheses Generation"] #askForm .form-inputs {
|
| 1797 |
display: flex;
|
| 1798 |
flex-direction: column;
|
| 1799 |
align-items: stretch;
|
|
|
|
| 1804 |
|
| 1805 |
html[data-mode="QA"] #databaseContainer,
|
| 1806 |
html[data-mode="System Chart Extraction"] #databaseContainer,
|
| 1807 |
+
html[data-mode="Hypotheses Generation"] #databaseContainer,
|
| 1808 |
html[data-mode="QA"] #visualizationContainer,
|
| 1809 |
html[data-mode="System Chart Extraction"] #visualizationContainer,
|
| 1810 |
+
html[data-mode="Hypotheses Generation"] #visualizationContainer,
|
| 1811 |
html[data-mode="QA"] #questionContainer,
|
| 1812 |
+
html[data-mode="System Chart Extraction"] #questionContainer,
|
| 1813 |
+
html[data-mode="Hypotheses Generation"] #questionContainer,
|
| 1814 |
+
html[data-mode="QA"] #hypothesesContainer,
|
| 1815 |
+
html[data-mode="System Chart Extraction"] #hypothesesContainer,
|
| 1816 |
+
html[data-mode="Hypotheses Generation"] #hypothesesContainer {
|
| 1817 |
width: 100%;
|
| 1818 |
max-width: 100%;
|
| 1819 |
}
|
|
|
|
| 2079 |
html[data-mode="QA"] .api-key-stack,
|
| 2080 |
html[data-mode="System Chart Extraction"] .api-key-stack,
|
| 2081 |
html[data-mode="Hypotheses Generation"] .api-key-stack {
|
| 2082 |
+
max-width: 100%;
|
| 2083 |
}
|
| 2084 |
|
| 2085 |
html[data-mode="QA"] .api-key-stack .input-row,
|
|
|
|
| 2118 |
html[data-mode="Hypotheses Generation"] .provider-badge[data-provider="openai"] {
|
| 2119 |
color: #34d399; border-color: rgba(16, 185, 129, 0.4); background: rgba(16, 185, 129, 0.1);
|
| 2120 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2121 |
html[data-mode="QA"] .provider-badge[data-provider="gemini"],
|
| 2122 |
html[data-mode="System Chart Extraction"] .provider-badge[data-provider="gemini"],
|
| 2123 |
html[data-mode="Hypotheses Generation"] .provider-badge[data-provider="gemini"] {
|
|
|
|
| 2187 |
color: var(--text) !important;
|
| 2188 |
}
|
| 2189 |
|
| 2190 |
+
/* Continue-conversation form: stack the load row and the Continuous
|
| 2191 |
+
Conversation panel vertically at full width (the base #conversationForm
|
| 2192 |
+
rule is a flex row, which shrinks children to content width) */
|
| 2193 |
+
html[data-mode="QA"] #conversationForm,
|
| 2194 |
+
html[data-mode="System Chart Extraction"] #conversationForm,
|
| 2195 |
+
html[data-mode="Hypotheses Generation"] #conversationForm {
|
| 2196 |
+
display: flex !important;
|
| 2197 |
+
flex-direction: column;
|
| 2198 |
+
align-items: stretch;
|
| 2199 |
+
gap: 14px;
|
| 2200 |
+
}
|
| 2201 |
+
|
| 2202 |
html[data-mode="QA"] .user-bubble,
|
| 2203 |
html[data-mode="System Chart Extraction"] .user-bubble,
|
| 2204 |
html[data-mode="Hypotheses Generation"] .user-bubble {
|
|
|
|
| 2380 |
gap: 16px;
|
| 2381 |
align-items: stretch;
|
| 2382 |
margin-top: 12px;
|
|
|
|
| 2383 |
}
|
| 2384 |
|
| 2385 |
html[data-mode="QA"] .upload-panel-grid .stack,
|
|
|
|
| 2431 |
min-height: 200px;
|
| 2432 |
}
|
| 2433 |
|
| 2434 |
+
/* Files picked but not yet uploaded — mirror the green confirm tone */
|
| 2435 |
+
html[data-mode="QA"] .dropzone.has-files,
|
| 2436 |
+
html[data-mode="System Chart Extraction"] .dropzone.has-files,
|
| 2437 |
+
html[data-mode="Hypotheses Generation"] .dropzone.has-files {
|
| 2438 |
+
border: 1px solid rgba(34, 197, 94, 0.55);
|
| 2439 |
+
background: rgba(34, 197, 94, 0.08);
|
| 2440 |
+
}
|
| 2441 |
+
|
| 2442 |
+
html[data-mode="QA"] .dropzone.has-files .dropzone-content p,
|
| 2443 |
+
html[data-mode="System Chart Extraction"] .dropzone.has-files .dropzone-content p,
|
| 2444 |
+
html[data-mode="Hypotheses Generation"] .dropzone.has-files .dropzone-content p {
|
| 2445 |
+
color: #86efac;
|
| 2446 |
+
}
|
| 2447 |
+
|
| 2448 |
+
html[data-mode="QA"] .dropzone.has-files .dropzone-content .small,
|
| 2449 |
+
html[data-mode="System Chart Extraction"] .dropzone.has-files .dropzone-content .small,
|
| 2450 |
+
html[data-mode="Hypotheses Generation"] .dropzone.has-files .dropzone-content .small {
|
| 2451 |
+
overflow-wrap: anywhere;
|
| 2452 |
+
}
|
| 2453 |
+
|
| 2454 |
html[data-mode="QA"] .dropzone input[type="file"],
|
| 2455 |
html[data-mode="System Chart Extraction"] .dropzone input[type="file"],
|
| 2456 |
html[data-mode="Hypotheses Generation"] .dropzone input[type="file"] {
|
|
|
|
| 2663 |
border: 1px solid rgba(239, 68, 68, 0.4) !important;
|
| 2664 |
}
|
| 2665 |
|
| 2666 |
+
html[data-mode="QA"] .confirm-message,
|
| 2667 |
+
html[data-mode="System Chart Extraction"] .confirm-message,
|
| 2668 |
+
html[data-mode="Hypotheses Generation"] .confirm-message {
|
| 2669 |
+
background: rgba(34, 197, 94, 0.12) !important;
|
| 2670 |
+
color: #86efac !important;
|
| 2671 |
+
border: 1px solid rgba(34, 197, 94, 0.4) !important;
|
| 2672 |
+
border-left: 4px solid rgba(34, 197, 94, 0.7) !important;
|
| 2673 |
+
}
|
| 2674 |
+
|
| 2675 |
html[data-mode="QA"] hr,
|
| 2676 |
html[data-mode="System Chart Extraction"] hr,
|
| 2677 |
html[data-mode="Hypotheses Generation"] hr {
|
|
|
|
| 2784 |
background: linear-gradient(120deg, var(--primary), var(--accent-2)) !important;
|
| 2785 |
color: #fff !important;
|
| 2786 |
border: none !important;
|
| 2787 |
+
padding: 12px 26px;
|
| 2788 |
+
border-radius: 12px;
|
| 2789 |
+
font-size: 0.9rem;
|
| 2790 |
font-weight: 600;
|
| 2791 |
cursor: pointer;
|
| 2792 |
box-shadow: 0 6px 18px var(--accent-shadow);
|
| 2793 |
}
|
| 2794 |
|
| 2795 |
+
/* "Start Hypothesis Conversation" and hypothesis-chat "Send" — match the
|
| 2796 |
+
standard button text size (0.9rem, like Load Conversation) */
|
| 2797 |
+
html[data-mode="QA"] #start-hypothesis-conversation-btn,
|
| 2798 |
+
html[data-mode="System Chart Extraction"] #start-hypothesis-conversation-btn,
|
| 2799 |
+
html[data-mode="Hypotheses Generation"] #start-hypothesis-conversation-btn,
|
| 2800 |
+
html[data-mode="QA"] #send-hypothesis-message-btn,
|
| 2801 |
+
html[data-mode="System Chart Extraction"] #send-hypothesis-message-btn,
|
| 2802 |
+
html[data-mode="Hypotheses Generation"] #send-hypothesis-message-btn {
|
| 2803 |
+
padding: 12px 26px !important;
|
| 2804 |
+
font-size: 0.9rem !important;
|
| 2805 |
+
}
|
| 2806 |
+
|
| 2807 |
/* Hide Upload Files section and renumber Ask Questions in Hypotheses Generation mode */
|
| 2808 |
html[data-mode="Hypotheses Generation"] #uploadSection {
|
| 2809 |
display: none !important;
|
|
|
|
| 2812 |
html[data-mode="Hypotheses Generation"] .step-number-default { display: none; }
|
| 2813 |
html[data-mode="Hypotheses Generation"] .step-number-hypotheses { display: inline; }
|
| 2814 |
|
| 2815 |
+
/* Per-mode title for the question/extraction/hypotheses section */
|
| 2816 |
+
.ask-title-chart, .ask-title-hypotheses { display: none; }
|
| 2817 |
+
html[data-mode="System Chart Extraction"] .ask-title-qa { display: none; }
|
| 2818 |
+
html[data-mode="System Chart Extraction"] .ask-title-chart { display: inline; }
|
| 2819 |
+
html[data-mode="Hypotheses Generation"] .ask-title-qa { display: none; }
|
| 2820 |
+
html[data-mode="Hypotheses Generation"] .ask-title-hypotheses { display: inline; }
|
| 2821 |
+
|
| 2822 |
/* Per-mode footer disclaimers (PlotExtract-style) */
|
| 2823 |
.mode-footer {
|
| 2824 |
display: none;
|
|
|
|
| 2875 |
<div class="stack compact api-key-stack">
|
| 2876 |
<label class="label" id="apiKeyLabel" for="apiKeyInput">API Key</label>
|
| 2877 |
<div class="input-row">
|
| 2878 |
+
<input type="password" id="apiKeyInput" name="api_key_input" autocomplete="off">
|
| 2879 |
<button class="ghost" id="toggleKey" type="button">Show</button>
|
| 2880 |
</div>
|
| 2881 |
+
<p class="hint left">We never store your key. It is used only for OpenAI or Google Gemini API requests.</p>
|
| 2882 |
|
| 2883 |
<label class="label" for="modelSelect">Model</label>
|
| 2884 |
<select name="model" id="modelSelect" disabled>
|
|
|
|
| 2887 |
<span id="modelStatus" class="model-status"></span>
|
| 2888 |
</div>
|
| 2889 |
<div class="actions api-key-actions">
|
| 2890 |
+
<button type="submit" id="modelSubmitButton">Confirm</button>
|
| 2891 |
</div>
|
| 2892 |
</form>
|
| 2893 |
|
| 2894 |
+
<div id="apiKeyConfirm" class="confirm-message" role="status" aria-live="polite" hidden></div>
|
| 2895 |
+
|
| 2896 |
<hr id="uploadSectionDivider">
|
| 2897 |
|
| 2898 |
<div id="uploadSection">
|
|
|
|
| 2916 |
<button type="submit">Upload</button>
|
| 2917 |
</div>
|
| 2918 |
</form>
|
| 2919 |
+
<div id="uploadConfirm" class="confirm-message" role="status" aria-live="polite" hidden></div>
|
| 2920 |
</div>
|
| 2921 |
</section>
|
| 2922 |
|
| 2923 |
<!-- Workspace panel: ask + chat + continuations -->
|
| 2924 |
<section class="panel" id="workspacePanel">
|
| 2925 |
+
<div class="section-title"><span class="step-number-default">3)</span><span class="step-number-hypotheses">2)</span> <span class="ask-title-qa">Ask Questions</span><span class="ask-title-chart">Extract System Charts</span><span class="ask-title-hypotheses">Hypotheses Generation</span></div>
|
| 2926 |
<form id="askForm">
|
| 2927 |
<div class="form-inputs">
|
| 2928 |
<div id="databaseContainer">
|
|
|
|
| 2945 |
|
| 2946 |
<div id="hypothesesContainer" style="display: none;">
|
| 2947 |
<div class="result-card hypotheses-options">
|
| 2948 |
+
<div class="stack" style="margin-bottom: 12px;">
|
| 2949 |
+
<span class="label" style="display: block; margin-bottom: 6px;">System Charts Files</span>
|
| 2950 |
+
<div class="dropzone tall" id="systemChartsDropzone">
|
| 2951 |
+
<input type="file" id="systemChartsFile" accept=".txt" multiple>
|
| 2952 |
+
<div class="dropzone-content">
|
| 2953 |
+
<p>Drag & drop or click to upload files.</p>
|
| 2954 |
+
<span class="small">Upload the <strong>system_charts.txt</strong> file(s) downloaded from the System Chart Extraction tool — not all_details.txt. You can select multiple system_charts.txt files. Together they must contain <strong>at least two system charts</strong> (e.g., extracted from two different papers) — a single chart is not enough for hypothesis generation.</span>
|
| 2955 |
+
</div>
|
| 2956 |
+
</div>
|
| 2957 |
+
</div>
|
| 2958 |
+
|
| 2959 |
<label style="display: block; margin-bottom: 8px;">
|
| 2960 |
+
Describe your materials design goals:
|
| 2961 |
+
<textarea id="designGoalsDescription" rows="4" placeholder="Describe what you want to design in plain language: your overall goal, the trade-offs you care about, ideal properties, constraints, and the target application..." style="margin-top: 4px; width: 100%; padding: 6px; resize: vertical;"></textarea>
|
| 2962 |
+
<small class="hint left">The model will read it and suggest the two key design properties.</small>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2963 |
</label>
|
| 2964 |
+
<div style="margin-bottom: 8px;">
|
| 2965 |
+
<button type="button" id="analyzeGoalsBtn" style="padding: 8px 14px; cursor: pointer; border-radius: 6px; border: 1px solid var(--primary, #4285F4); background: var(--primary, #4285F4); color: #fff; font-size: 0.9em;">Analyze design goals</button>
|
| 2966 |
+
<span id="analyzeGoalsStatus" class="hint left" style="margin-left: 10px;"></span>
|
| 2967 |
+
</div>
|
| 2968 |
+
|
| 2969 |
+
<div id="mechanismFields" style="display: none;">
|
| 2970 |
+
<small class="hint left" style="display: block; margin-bottom: 8px;">Review the two suggested design properties below and edit them freely before generating hypotheses.</small>
|
| 2971 |
+
<label style="display: block; margin-bottom: 8px;">
|
| 2972 |
+
Property / Mechanism 1:
|
| 2973 |
+
<input type="text" id="materialGoal1" placeholder="e.g., property #1 for xxx material" style="margin-top: 4px; width: 100%; padding: 6px;">
|
| 2974 |
+
</label>
|
| 2975 |
+
<label style="display: block; margin-bottom: 8px;">
|
| 2976 |
+
Property / Mechanism 2:
|
| 2977 |
+
<input type="text" id="materialGoal2" placeholder="e.g., property #2 for xxx material" style="margin-top: 4px; width: 100%; padding: 6px;">
|
| 2978 |
+
</label>
|
| 2979 |
+
</div>
|
| 2980 |
<label style="display: block; margin-bottom: 0;">
|
| 2981 |
Number of Iterations:
|
| 2982 |
<input type="number" id="iterationsCount" min="1" max="100" value="1" placeholder="1" style="margin-top: 4px; width: 100%; padding: 6px;">
|
|
|
|
| 2993 |
</div>
|
| 2994 |
</div>
|
| 2995 |
|
| 2996 |
+
<button type="submit"><span class="ask-title-qa">Ask</span><span class="ask-title-chart">Confirm</span><span class="ask-title-hypotheses">Confirm</span></button>
|
| 2997 |
</form>
|
| 2998 |
|
| 2999 |
<div id="chat-area"></div>
|
|
|
|
| 3058 |
Load Conversation
|
| 3059 |
</button>
|
| 3060 |
</div>
|
| 3061 |
+
|
| 3062 |
+
<div id="conversation-history" style="display: none;">
|
| 3063 |
+
<h4 class="panel-subtitle">Continuous Conversation</h4>
|
| 3064 |
+
<div id="conversation-messages"></div>
|
| 3065 |
+
<div class="input-row" id="followUpContainer">
|
| 3066 |
<input type="text" id="followUpQuestion" placeholder="Ask a follow-up question about this paper...">
|
| 3067 |
+
<button type="submit">Send</button>
|
| 3068 |
+
</div>
|
|
|
|
|
|
|
| 3069 |
</div>
|
| 3070 |
</form>
|
| 3071 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3072 |
</div>
|
| 3073 |
</section>
|
| 3074 |
|
|
|
|
| 3078 |
</div>
|
| 3079 |
|
| 3080 |
<div class="reference-item" id="systemChartReference">
|
| 3081 |
+
Liu, Q., Polak, M. P., Shuvo, M. A. A., Deodhar, H. S., Han, J., Morgan, D., & Oh, H. (2025, October). Automated extraction of materials system charts using a large language model framework. <em>Scripta Materialia</em>. Elsevier BV. http://doi.org/10.1016/j.scriptamat.2025.116815
|
| 3082 |
</div>
|
| 3083 |
<div class="reference-item" id="hypothesesReference">
|
| 3084 |
+
Liu, Q., Polak, M. P., Kim, S. Y., Shuvo, M. A. A., Deodhar, H. S., Han, J., … Oh, H. (2025, September). Beyond designer's knowledge: Generating materials design hypotheses via a large language model. <em>Acta Materialia</em>. Elsevier BV. http://doi.org/10.1016/j.actamat.2025.121307
|
| 3085 |
</div>
|
| 3086 |
</section>
|
| 3087 |
|
|
|
|
| 3103 |
</footer>
|
| 3104 |
<footer class="mode-footer footer" id="hypothesesFooter">
|
| 3105 |
<p>
|
| 3106 |
+
This tool generates materials design hypotheses by synergistically combining materials system charts, guided by design goals. Generated hypotheses are produced by LLMs and are not guaranteed to be
|
|
|
|
| 3107 |
scientifically valid or novel, so please take the
|
| 3108 |
results with caution. Always apply domain expertise and verify against the literature before acting
|
| 3109 |
on any hypothesis.
|
|
|
|
| 3155 |
const subheads = {
|
| 3156 |
'QA': 'Upload research papers, select a model, and ask questions across your documents.',
|
| 3157 |
'System Chart Extraction': 'Upload papers, select a model, and extract materials system charts linking processing, structure, and properties.',
|
| 3158 |
+
'Hypotheses Generation': 'Provide system charts and design goals, select a model, and generate materials design hypotheses.'
|
| 3159 |
};
|
| 3160 |
subhead.textContent = subheads[window.selectedMode] || subhead.textContent;
|
| 3161 |
}
|
|
|
|
| 3244 |
|
| 3245 |
apiKeyInput.addEventListener('input', () => {
|
| 3246 |
const provider = detectProviderFromKey(apiKeyInput.value);
|
| 3247 |
+
if (provider === 'anthropic') {
|
| 3248 |
+
setProviderBadge('error', 'not supported');
|
| 3249 |
+
} else if (provider) {
|
| 3250 |
+
setProviderBadge(provider, provider === 'openai' ? 'OpenAI' : 'Gemini');
|
| 3251 |
} else {
|
| 3252 |
setProviderBadge('', null);
|
| 3253 |
}
|
|
|
|
| 3285 |
if (_modelsLoading) return false;
|
| 3286 |
|
| 3287 |
const provider = detectProviderFromKey(key);
|
| 3288 |
+
if (provider === 'anthropic') {
|
| 3289 |
+
setProviderBadge('error', 'not supported');
|
| 3290 |
+
setModelDropdownPlaceholder('Anthropic keys are not supported');
|
| 3291 |
+
setModelStatus('Anthropic (sk-ant-...) keys are not supported — Anthropic does not provide an embedding model, which this tool requires. Use an OpenAI (sk-...) or Gemini (AIza...) key.', 'error');
|
| 3292 |
+
return false;
|
| 3293 |
+
}
|
| 3294 |
if (!provider) {
|
| 3295 |
setProviderBadge('error', 'unknown');
|
| 3296 |
setModelDropdownPlaceholder('Unsupported key format');
|
| 3297 |
+
setModelStatus('Use an OpenAI (sk-...) or Gemini (AIza...) key.', 'error');
|
| 3298 |
return false;
|
| 3299 |
}
|
| 3300 |
|
|
|
|
| 3351 |
await submitApiKey(formData);
|
| 3352 |
});
|
| 3353 |
|
| 3354 |
+
// Escape user-provided text before inserting into innerHTML
|
| 3355 |
+
function escapeHtml(str) {
|
| 3356 |
+
return String(str == null ? '' : str)
|
| 3357 |
+
.replace(/&/g, '&')
|
| 3358 |
+
.replace(/</g, '<')
|
| 3359 |
+
.replace(/>/g, '>')
|
| 3360 |
+
.replace(/"/g, '"')
|
| 3361 |
+
.replace(/'/g, ''');
|
| 3362 |
+
}
|
| 3363 |
+
|
| 3364 |
+
// Show a persistent inline confirmation banner (survives so the user can
|
| 3365 |
+
// see the current state instead of a transient alert).
|
| 3366 |
+
function showConfirm(elId, title, detail) {
|
| 3367 |
+
const el = document.getElementById(elId);
|
| 3368 |
+
if (!el) return;
|
| 3369 |
+
el.innerHTML =
|
| 3370 |
+
`<div class="confirm-title"><span aria-hidden="true">\u2713</span><span>${escapeHtml(title)}</span></div>` +
|
| 3371 |
+
(detail ? `<div class="confirm-detail">${escapeHtml(detail)}</div>` : '');
|
| 3372 |
+
el.hidden = false;
|
| 3373 |
+
// Restart the fade-in animation on repeat submissions
|
| 3374 |
+
el.style.animation = 'none';
|
| 3375 |
+
void el.offsetWidth;
|
| 3376 |
+
el.style.animation = '';
|
| 3377 |
+
}
|
| 3378 |
+
|
| 3379 |
// Function to submit API key to server
|
| 3380 |
async function submitApiKey(formData) {
|
| 3381 |
try {
|
|
|
|
| 3387 |
const data = await res.json();
|
| 3388 |
|
| 3389 |
if (!res.ok) {
|
| 3390 |
+
// Hide any stale confirmation and show error message
|
| 3391 |
+
const confirmEl = document.getElementById('apiKeyConfirm');
|
| 3392 |
+
if (confirmEl) confirmEl.hidden = true;
|
| 3393 |
+
|
| 3394 |
const errorDiv = document.createElement('div');
|
| 3395 |
errorDiv.className = 'error-message';
|
| 3396 |
errorDiv.textContent = data.message || 'Error setting up model.';
|
|
|
|
| 3409 |
return false;
|
| 3410 |
}
|
| 3411 |
|
| 3412 |
+
// Persistent success confirmation showing the active model & provider
|
| 3413 |
+
const modelSelect = document.getElementById('modelSelect');
|
| 3414 |
+
const selectedLabel = modelSelect && modelSelect.selectedOptions.length
|
| 3415 |
+
? modelSelect.selectedOptions[0].textContent
|
| 3416 |
+
: (formData.get('model') || '');
|
| 3417 |
+
const badge = document.getElementById('providerBadge');
|
| 3418 |
+
const providerLabel = badge && badge.textContent ? badge.textContent.trim() : '';
|
| 3419 |
+
const detail = selectedLabel
|
| 3420 |
+
? `Active model: ${selectedLabel}${providerLabel ? ` \u00b7 ${providerLabel}` : ''}`
|
| 3421 |
+
: '';
|
| 3422 |
+
showConfirm('apiKeyConfirm', data.message || 'API key set and model ready.', detail);
|
| 3423 |
return true;
|
| 3424 |
} catch (error) {
|
| 3425 |
alert('Connection error: ' + error);
|
|
|
|
| 3461 |
throw new Error(data.message || `HTTP ${res.status} ${res.statusText}`);
|
| 3462 |
}
|
| 3463 |
|
| 3464 |
+
// Persistent success confirmation showing what was uploaded and where
|
| 3465 |
+
const uploadedCount = Array.isArray(data.uploaded) ? data.uploaded.length : files.length;
|
| 3466 |
+
const noun = uploadedCount === 1 ? 'file' : 'files';
|
| 3467 |
+
const detail = `${uploadedCount} ${noun} added to database "${category}". Embedding may continue below.`;
|
| 3468 |
+
showConfirm('uploadConfirm', data.message || 'Upload received.', detail);
|
| 3469 |
|
| 3470 |
// Update databases and goal options based on newly uploaded files
|
| 3471 |
setTimeout(loadAvailableDatabases, 500);
|
|
|
|
| 3475 |
startEmbeddingProgressTracking(category);
|
| 3476 |
}
|
| 3477 |
} catch (error) {
|
| 3478 |
+
const confirmEl = document.getElementById('uploadConfirm');
|
| 3479 |
+
if (confirmEl) confirmEl.hidden = true;
|
| 3480 |
alert('Error uploading file: ' + error);
|
| 3481 |
}
|
| 3482 |
});
|
|
|
|
| 4028 |
// Initial load
|
| 4029 |
setTimeout(loadAvailableDatabases, 1000); // Delay to ensure page is loaded
|
| 4030 |
|
| 4031 |
+
// Show the continue-conversation section on page load when any prior
|
| 4032 |
+
// extraction (from any database or tab) already produced conversations.
|
| 4033 |
+
async function initConversationSection() {
|
| 4034 |
+
if (window.selectedMode !== 'QA' && window.selectedMode !== 'System Chart Extraction') return;
|
| 4035 |
+
try {
|
| 4036 |
+
const res = await fetch('/all_conversations');
|
| 4037 |
+
const data = await res.json();
|
| 4038 |
+
if (data.conversations && data.conversations.length > 0) {
|
| 4039 |
+
document.getElementById('conversation-section').style.display = 'block';
|
| 4040 |
+
await loadConversations();
|
| 4041 |
+
}
|
| 4042 |
+
} catch (e) {
|
| 4043 |
+
console.error('Could not check for existing conversations:', e);
|
| 4044 |
+
}
|
| 4045 |
+
}
|
| 4046 |
+
setTimeout(initConversationSection, 1200);
|
| 4047 |
+
|
| 4048 |
|
| 4049 |
|
| 4050 |
|
|
|
|
| 4362 |
}
|
| 4363 |
});
|
| 4364 |
|
| 4365 |
+
// ========================
|
| 4366 |
+
// Dropzone file-selection feedback (shows picked files before Upload is clicked)
|
| 4367 |
+
// ========================
|
| 4368 |
+
function setupDropzoneFileFeedback(inputId, dropzoneId) {
|
| 4369 |
+
const input = document.getElementById(inputId);
|
| 4370 |
+
const dropzone = document.getElementById(dropzoneId);
|
| 4371 |
+
if (!input || !dropzone) return;
|
| 4372 |
+
|
| 4373 |
+
const contentP = dropzone.querySelector('.dropzone-content p');
|
| 4374 |
+
const contentSmall = dropzone.querySelector('.dropzone-content .small');
|
| 4375 |
+
const defaultP = contentP ? contentP.textContent : '';
|
| 4376 |
+
const defaultSmallHtml = contentSmall ? contentSmall.innerHTML : '';
|
| 4377 |
+
const MAX_NAMES_SHOWN = 8;
|
| 4378 |
+
|
| 4379 |
+
input.addEventListener('change', () => {
|
| 4380 |
+
const files = input.files;
|
| 4381 |
+
if (!files || files.length === 0) {
|
| 4382 |
+
dropzone.classList.remove('has-files');
|
| 4383 |
+
if (contentP) contentP.textContent = defaultP;
|
| 4384 |
+
if (contentSmall) contentSmall.innerHTML = defaultSmallHtml;
|
| 4385 |
+
return;
|
| 4386 |
+
}
|
| 4387 |
+
const names = Array.from(files).map(f => f.name);
|
| 4388 |
+
const shown = names.slice(0, MAX_NAMES_SHOWN);
|
| 4389 |
+
const extra = names.length - shown.length;
|
| 4390 |
+
dropzone.classList.add('has-files');
|
| 4391 |
+
if (contentP) {
|
| 4392 |
+
contentP.textContent = `✓ ${files.length} file${files.length > 1 ? 's' : ''} selected — ready to upload`;
|
| 4393 |
+
}
|
| 4394 |
+
if (contentSmall) {
|
| 4395 |
+
contentSmall.textContent = shown.join(', ') + (extra > 0 ? ` and ${extra} more` : '');
|
| 4396 |
+
}
|
| 4397 |
+
});
|
| 4398 |
+
}
|
| 4399 |
+
|
| 4400 |
+
setupDropzoneFileFeedback('filesInput', 'uploadDropzone');
|
| 4401 |
+
setupDropzoneFileFeedback('systemChartsFile', 'systemChartsDropzone');
|
| 4402 |
+
|
| 4403 |
+
// ========================
|
| 4404 |
+
// Analyze Design Goals -> pre-fill the two mechanism fields
|
| 4405 |
+
// ========================
|
| 4406 |
+
|
| 4407 |
+
(function setupDesignGoalsAnalyzer() {
|
| 4408 |
+
const analyzeBtn = document.getElementById('analyzeGoalsBtn');
|
| 4409 |
+
if (!analyzeBtn) return;
|
| 4410 |
+
|
| 4411 |
+
analyzeBtn.addEventListener('click', async () => {
|
| 4412 |
+
const descriptionEl = document.getElementById('designGoalsDescription');
|
| 4413 |
+
const statusEl = document.getElementById('analyzeGoalsStatus');
|
| 4414 |
+
const mechanismFields = document.getElementById('mechanismFields');
|
| 4415 |
+
const goal1El = document.getElementById('materialGoal1');
|
| 4416 |
+
const goal2El = document.getElementById('materialGoal2');
|
| 4417 |
+
|
| 4418 |
+
const description = (descriptionEl.value || '').trim();
|
| 4419 |
+
if (!description) {
|
| 4420 |
+
statusEl.style.color = 'var(--danger, #d93025)';
|
| 4421 |
+
statusEl.textContent = 'Please describe your design goals first.';
|
| 4422 |
+
return;
|
| 4423 |
+
}
|
| 4424 |
+
|
| 4425 |
+
const originalLabel = analyzeBtn.textContent;
|
| 4426 |
+
analyzeBtn.disabled = true;
|
| 4427 |
+
analyzeBtn.style.opacity = '0.7';
|
| 4428 |
+
analyzeBtn.textContent = 'Analyzing…';
|
| 4429 |
+
statusEl.style.color = 'var(--muted, #666)';
|
| 4430 |
+
statusEl.textContent = 'Analyzing your goals with the model…';
|
| 4431 |
+
|
| 4432 |
+
try {
|
| 4433 |
+
const formData = new FormData();
|
| 4434 |
+
formData.append('description', description);
|
| 4435 |
+
|
| 4436 |
+
const res = await fetch('/analyze_design_goals', {
|
| 4437 |
+
method: 'POST',
|
| 4438 |
+
body: formData
|
| 4439 |
+
});
|
| 4440 |
+
const data = await res.json();
|
| 4441 |
+
|
| 4442 |
+
if (!res.ok || !data.success) {
|
| 4443 |
+
statusEl.style.color = 'var(--danger, #d93025)';
|
| 4444 |
+
statusEl.textContent = data.error || 'Analysis failed. Please fill in the properties manually below.';
|
| 4445 |
+
// Still reveal the fields so the user can enter them by hand.
|
| 4446 |
+
mechanismFields.style.display = 'block';
|
| 4447 |
+
return;
|
| 4448 |
+
}
|
| 4449 |
+
|
| 4450 |
+
goal1El.value = data.goal_1 || '';
|
| 4451 |
+
goal2El.value = data.goal_2 || '';
|
| 4452 |
+
mechanismFields.style.display = 'block';
|
| 4453 |
+
statusEl.style.color = 'var(--success, #188038)';
|
| 4454 |
+
statusEl.textContent = 'Suggested two properties — review and edit them below.';
|
| 4455 |
+
} catch (err) {
|
| 4456 |
+
statusEl.style.color = 'var(--danger, #d93025)';
|
| 4457 |
+
statusEl.textContent = 'Error contacting the server: ' + err;
|
| 4458 |
+
mechanismFields.style.display = 'block';
|
| 4459 |
+
} finally {
|
| 4460 |
+
analyzeBtn.disabled = false;
|
| 4461 |
+
analyzeBtn.style.opacity = '1';
|
| 4462 |
+
analyzeBtn.textContent = originalLabel;
|
| 4463 |
+
}
|
| 4464 |
+
});
|
| 4465 |
+
})();
|
| 4466 |
+
|
| 4467 |
// ========================
|
| 4468 |
// Hypotheses Generation Handler
|
| 4469 |
// ========================
|
|
|
|
| 4498 |
|
| 4499 |
// Validate material design goals
|
| 4500 |
if (!materialGoal1 || !materialGoal2) {
|
| 4501 |
+
// Make sure the (possibly hidden) fields are visible so the user can fix this.
|
| 4502 |
+
const mechanismFields = document.getElementById('mechanismFields');
|
| 4503 |
+
if (mechanismFields) mechanismFields.style.display = 'block';
|
| 4504 |
const errorDiv = document.createElement('div');
|
| 4505 |
errorDiv.classList.add('chat-bubble', 'ai-bubble', 'error-bubble');
|
| 4506 |
+
errorDiv.innerHTML = '<strong>Error:</strong> Please provide both design properties. Describe your goals and click "Analyze design goals", or fill in the two fields manually.';
|
| 4507 |
chatArea.appendChild(errorDiv);
|
| 4508 |
chatArea.scrollTop = chatArea.scrollHeight;
|
| 4509 |
return;
|
|
|
|
| 4593 |
// Create AI bubble for status
|
| 4594 |
const aiDiv = document.createElement('div');
|
| 4595 |
aiDiv.classList.add('chat-bubble', 'ai-bubble');
|
| 4596 |
+
aiDiv.innerHTML = `<strong>Hypotheses Generation Started</strong>`;
|
| 4597 |
chatArea.appendChild(aiDiv);
|
| 4598 |
|
| 4599 |
// Create progress tracking bubble
|
|
|
|
| 4663 |
currentExtractionId = extractionId;
|
| 4664 |
const conversationSection = document.getElementById('conversation-section');
|
| 4665 |
conversationSection.style.display = 'block';
|
| 4666 |
+
|
| 4667 |
+
// Load conversations across all extractions (not just this one)
|
| 4668 |
+
loadConversations();
|
| 4669 |
}
|
| 4670 |
|
| 4671 |
+
// Load conversations across ALL extractions/databases so the dropdown is
|
| 4672 |
+
// not limited to papers from the most recent extraction run.
|
| 4673 |
+
async function loadConversations() {
|
| 4674 |
try {
|
| 4675 |
+
const response = await fetch('/all_conversations');
|
| 4676 |
const data = await response.json();
|
| 4677 |
+
|
| 4678 |
const conversationSelect = document.getElementById('conversationSelect');
|
| 4679 |
conversationSelect.innerHTML = '<option value="">Select a paper to continue conversation...</option>';
|
| 4680 |
+
|
| 4681 |
if (data.conversations && data.conversations.length > 0) {
|
| 4682 |
data.conversations.forEach(conv => {
|
| 4683 |
const option = document.createElement('option');
|
| 4684 |
+
// Each option carries its own extraction id so papers from
|
| 4685 |
+
// different extraction runs (and databases) can be mixed freely.
|
| 4686 |
+
option.value = `${conv.extraction_id}||${conv.key}`;
|
| 4687 |
option.textContent = `${conv.title} (${conv.paper_type}, ${conv.message_count} messages)`;
|
| 4688 |
conversationSelect.appendChild(option);
|
| 4689 |
});
|
|
|
|
| 4702 |
|
| 4703 |
// Function to load conversation history
|
| 4704 |
async function loadConversationHistory(extractionId, conversationKey) {
|
| 4705 |
+
const conversationHistory = document.getElementById('conversation-history');
|
| 4706 |
+
const conversationMessages = document.getElementById('conversation-messages');
|
| 4707 |
try {
|
| 4708 |
const response = await fetch(`/conversation_history/${extractionId}/${conversationKey}`);
|
| 4709 |
const data = await response.json();
|
| 4710 |
+
|
|
|
|
|
|
|
|
|
|
| 4711 |
conversationMessages.innerHTML = '';
|
| 4712 |
+
|
| 4713 |
if (data.history && data.history.length > 0) {
|
| 4714 |
data.history.forEach(message => {
|
| 4715 |
const messageDiv = document.createElement('div');
|
| 4716 |
+
const isHuman = message.type === 'human';
|
| 4717 |
+
messageDiv.classList.add('chat-bubble', isHuman ? 'user-bubble' : 'ai-bubble');
|
| 4718 |
+
if (isHuman) {
|
| 4719 |
+
const content = escapeHtml(message.content).replace(/\n/g, '<br>');
|
| 4720 |
+
messageDiv.innerHTML = `<strong>You:</strong> ${content}`;
|
|
|
|
|
|
|
|
|
|
| 4721 |
} else {
|
| 4722 |
+
// Render AI messages as markdown (tables, lists, headings, code)
|
| 4723 |
+
messageDiv.innerHTML = `<strong>AI:</strong><div class="qa-response">${formatMarkdownResponse(message.content)}</div>`;
|
|
|
|
|
|
|
| 4724 |
}
|
|
|
|
| 4725 |
conversationMessages.appendChild(messageDiv);
|
| 4726 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4727 |
}
|
| 4728 |
+
|
| 4729 |
+
// Keep the conversation container (and its input) visible even when the
|
| 4730 |
+
// thread is empty — the user is about to start chatting.
|
| 4731 |
+
conversationHistory.style.display = 'block';
|
| 4732 |
+
conversationMessages.scrollTop = conversationMessages.scrollHeight;
|
| 4733 |
} catch (error) {
|
| 4734 |
console.error('Error loading conversation history:', error);
|
| 4735 |
+
conversationHistory.style.display = 'block';
|
|
|
|
| 4736 |
}
|
| 4737 |
}
|
| 4738 |
|
| 4739 |
// Handle load conversation button click
|
| 4740 |
document.getElementById('loadConversationBtn').addEventListener('click', async () => {
|
| 4741 |
const conversationSelect = document.getElementById('conversationSelect');
|
| 4742 |
+
const selectedValue = conversationSelect.value;
|
| 4743 |
+
|
| 4744 |
+
if (!selectedValue) {
|
| 4745 |
alert('Please select a conversation to load');
|
| 4746 |
return;
|
| 4747 |
}
|
| 4748 |
+
|
| 4749 |
+
// Option values are "<extraction_id>||<conversation_key>"
|
| 4750 |
+
const sep = selectedValue.indexOf('||');
|
| 4751 |
+
if (sep === -1) {
|
| 4752 |
+
alert('Invalid conversation selection');
|
| 4753 |
return;
|
| 4754 |
}
|
| 4755 |
+
currentExtractionId = selectedValue.slice(0, sep);
|
| 4756 |
+
currentConversationKey = selectedValue.slice(sep + 2);
|
| 4757 |
+
|
| 4758 |
+
// Load conversation history into the Continuous Conversation panel
|
| 4759 |
+
await loadConversationHistory(currentExtractionId, currentConversationKey);
|
| 4760 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4761 |
// Focus on the follow-up question input
|
| 4762 |
document.getElementById('followUpQuestion').focus();
|
| 4763 |
});
|
| 4764 |
|
| 4765 |
+
// Handle conversation form submission — the whole exchange lives inside the
|
| 4766 |
+
// Continuous Conversation panel (#conversation-messages), not the main chat area.
|
| 4767 |
document.getElementById('conversationForm').addEventListener('submit', async (e) => {
|
| 4768 |
e.preventDefault();
|
| 4769 |
+
|
| 4770 |
+
const questionInput = document.getElementById('followUpQuestion');
|
| 4771 |
+
const followUpQuestion = questionInput.value.trim();
|
| 4772 |
+
|
| 4773 |
if (!followUpQuestion) {
|
| 4774 |
alert('Please enter a follow-up question');
|
| 4775 |
return;
|
| 4776 |
}
|
| 4777 |
+
|
| 4778 |
if (!currentExtractionId || !currentConversationKey) {
|
| 4779 |
alert('Please select a conversation first');
|
| 4780 |
return;
|
| 4781 |
}
|
| 4782 |
+
|
| 4783 |
+
const conversationMessages = document.getElementById('conversation-messages');
|
| 4784 |
+
|
| 4785 |
+
// Optimistically show the user's message in the thread
|
| 4786 |
const userDiv = document.createElement('div');
|
| 4787 |
userDiv.classList.add('chat-bubble', 'user-bubble');
|
| 4788 |
+
userDiv.innerText = followUpQuestion;
|
| 4789 |
+
conversationMessages.appendChild(userDiv);
|
| 4790 |
+
|
| 4791 |
+
// Loading bubble
|
| 4792 |
const loadingDiv = document.createElement('div');
|
| 4793 |
loadingDiv.classList.add('chat-bubble', 'ai-bubble', 'loading-bubble');
|
| 4794 |
loadingDiv.innerHTML = `
|
|
|
|
| 4801 |
</div>
|
| 4802 |
</div>
|
| 4803 |
`;
|
| 4804 |
+
conversationMessages.appendChild(loadingDiv);
|
| 4805 |
+
conversationMessages.scrollTop = conversationMessages.scrollHeight;
|
| 4806 |
+
|
| 4807 |
+
questionInput.value = '';
|
| 4808 |
+
|
| 4809 |
+
const showError = (text) => {
|
| 4810 |
+
if (loadingDiv.parentNode) loadingDiv.remove();
|
| 4811 |
+
const errorDiv = document.createElement('div');
|
| 4812 |
+
errorDiv.classList.add('chat-bubble', 'ai-bubble', 'error-bubble');
|
| 4813 |
+
errorDiv.innerHTML = `<strong>Error:</strong> ${escapeHtml(text)}`;
|
| 4814 |
+
conversationMessages.appendChild(errorDiv);
|
| 4815 |
+
conversationMessages.scrollTop = conversationMessages.scrollHeight;
|
| 4816 |
+
};
|
| 4817 |
+
|
| 4818 |
try {
|
|
|
|
| 4819 |
const formData = new FormData();
|
| 4820 |
formData.append('question', followUpQuestion);
|
| 4821 |
+
|
|
|
|
| 4822 |
const response = await fetch(`/continue_conversation/${currentExtractionId}/${currentConversationKey}`, {
|
| 4823 |
method: 'POST',
|
| 4824 |
body: formData
|
| 4825 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4826 |
|
| 4827 |
+
if (!response.ok) {
|
| 4828 |
+
const errorData = await response.json().catch(() => ({}));
|
| 4829 |
+
showError(errorData.error || errorData.answer || 'Unknown error');
|
| 4830 |
+
return;
|
| 4831 |
+
}
|
| 4832 |
+
|
| 4833 |
+
await response.json();
|
| 4834 |
+
|
| 4835 |
+
// Re-render the whole thread from the server — it now includes the new
|
| 4836 |
+
// question and answer, replacing the optimistic bubbles above.
|
| 4837 |
+
await loadConversationHistory(currentExtractionId, currentConversationKey);
|
| 4838 |
+
questionInput.focus();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4839 |
} catch (error) {
|
| 4840 |
+
showError(error.message || String(error));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4841 |
}
|
| 4842 |
});
|
| 4843 |
|
|
|
|
| 4930 |
const chatMessages = document.getElementById('hypothesis-chat-messages');
|
| 4931 |
chatMessages.innerHTML = `
|
| 4932 |
<div style="background: #f8f9fa; padding: 10px; border-radius: 4px; margin-bottom: 10px; border-left: 4px solid #4285F4;">
|
| 4933 |
+
<strong>System:</strong> I have loaded the context for your hypothesis analysis, including your <strong>provided paper content</strong> and <strong>${data.charts_found} referenced system charts</strong>. The conversation is ready!
|
|
|
|
| 4934 |
</div>
|
| 4935 |
`;
|
| 4936 |
|
|
|
|
| 4968 |
// Add user message
|
| 4969 |
const userMessageDiv = document.createElement('div');
|
| 4970 |
userMessageDiv.style.cssText = 'background: #e8f5e8; padding: 10px; border-radius: 4px; margin-bottom: 10px; border-left: 4px solid #4caf50;';
|
| 4971 |
+
userMessageDiv.innerHTML = `<strong>You:</strong> ${escapeHtml(message)}`;
|
| 4972 |
chatMessages.appendChild(userMessageDiv);
|
| 4973 |
|
| 4974 |
// Clear input
|
|
|
|
| 5003 |
return;
|
| 5004 |
}
|
| 5005 |
|
| 5006 |
+
// Render the AI response as markdown (tables, lists, headings, code)
|
| 5007 |
const aiResponse = data.response;
|
| 5008 |
+
loadingDiv.innerHTML = `<strong>AI:</strong><div class="qa-response">${formatMarkdownResponse(aiResponse)}</div>`;
|
|
|
|
|
|
|
| 5009 |
chatMessages.scrollTop = chatMessages.scrollHeight;
|
| 5010 |
|
| 5011 |
console.log(`✅ Conversation response received: ${data.conversation_length} total exchanges, ${data.papers_count} papers, ${data.charts_count} charts in context`);
|
|
|
|
| 5114 |
return basicMarkdownToHtml(text);
|
| 5115 |
}
|
| 5116 |
|
| 5117 |
+
// Parse with the modern marked API (the legacy custom-Renderer API is no
|
| 5118 |
+
// longer supported by current marked builds and silently broke tables),
|
| 5119 |
+
// then apply the qa-* styling classes to the resulting DOM.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5120 |
try {
|
| 5121 |
+
const html = marked.parse(text, { breaks: true, gfm: true });
|
| 5122 |
+
const tpl = document.createElement('template');
|
| 5123 |
+
tpl.innerHTML = html;
|
| 5124 |
+
tpl.content.querySelectorAll('table').forEach(t => {
|
| 5125 |
+
t.classList.add('qa-table');
|
| 5126 |
+
if (!t.parentElement || !t.parentElement.classList.contains('qa-table-wrap')) {
|
| 5127 |
+
const wrap = document.createElement('div');
|
| 5128 |
+
wrap.className = 'qa-table-wrap';
|
| 5129 |
+
t.replaceWith(wrap);
|
| 5130 |
+
wrap.appendChild(t);
|
| 5131 |
+
}
|
| 5132 |
+
});
|
| 5133 |
+
tpl.content.querySelectorAll('h1,h2,h3,h4,h5,h6').forEach(h => h.classList.add('qa-h', 'qa-h' + h.tagName[1]));
|
| 5134 |
+
tpl.content.querySelectorAll('p').forEach(el => el.classList.add('qa-p'));
|
| 5135 |
+
tpl.content.querySelectorAll('hr').forEach(el => el.classList.add('qa-hr'));
|
| 5136 |
+
tpl.content.querySelectorAll('blockquote').forEach(el => el.classList.add('qa-blockquote'));
|
| 5137 |
+
tpl.content.querySelectorAll('pre').forEach(el => el.classList.add('qa-pre'));
|
| 5138 |
+
tpl.content.querySelectorAll('code').forEach(c => {
|
| 5139 |
+
if (!c.closest('pre')) c.classList.add('qa-code-inline');
|
| 5140 |
+
});
|
| 5141 |
+
tpl.content.querySelectorAll('ul,ol').forEach(el => el.classList.add('qa-list'));
|
| 5142 |
+
tpl.content.querySelectorAll('li').forEach(el => el.classList.add('qa-li'));
|
| 5143 |
+
const rendered = tpl.innerHTML;
|
| 5144 |
// If markdown markers still survive parsing, use robust fallback renderer.
|
| 5145 |
+
if (/\*\*|(^|\s)-\s+\S/m.test(rendered.replace(/<[^>]+>/g, ''))) {
|
| 5146 |
return basicMarkdownToHtml(text);
|
| 5147 |
}
|
| 5148 |
+
return rendered;
|
| 5149 |
} catch (error) {
|
| 5150 |
console.error('Error parsing markdown:', error);
|
| 5151 |
return basicMarkdownToHtml(text);
|
main.py
CHANGED
|
@@ -46,17 +46,6 @@ except ImportError:
|
|
| 46 |
|
| 47 |
import requests as _requests
|
| 48 |
|
| 49 |
-
# 1c) Imports for Anthropic (Claude)
|
| 50 |
-
try:
|
| 51 |
-
from langchain_anthropic import ChatAnthropic
|
| 52 |
-
except ImportError:
|
| 53 |
-
ChatAnthropic = None
|
| 54 |
-
|
| 55 |
-
try:
|
| 56 |
-
import anthropic as anthropic_sdk
|
| 57 |
-
except ImportError:
|
| 58 |
-
anthropic_sdk = None
|
| 59 |
-
|
| 60 |
try:
|
| 61 |
from openai import OpenAI as OpenAIClient
|
| 62 |
except ImportError:
|
|
@@ -72,8 +61,8 @@ from vectorstore import get_vectorstore, compute_file_hash, CHROMA_DB_BASE
|
|
| 72 |
from system_chart_extraction import system_chart_extraction
|
| 73 |
from system_chart_service import SystemChartService
|
| 74 |
from hypotheses_service import HypothesesService
|
| 75 |
-
from prompts import create_hypotheses_generation_prompt
|
| 76 |
-
from conversation_storage import save_conversation, get_conversations, update_conversation
|
| 77 |
from plotextract.app import app as plotextract_app
|
| 78 |
|
| 79 |
# Metadata management functions
|
|
@@ -677,7 +666,7 @@ DEFAULT_MODEL_QA = DEFAULT_MODEL
|
|
| 677 |
DEFAULT_MODEL_SYSTEM_CHART_EXTRACTION = DEFAULT_MODEL
|
| 678 |
# Shared output-length cap for QA, system chart extraction, and hypotheses.
|
| 679 |
# LangChain's max_tokens maps to provider-specific names:
|
| 680 |
-
#
|
| 681 |
DEFAULT_MAX_OUTPUT_TOKENS = 8192
|
| 682 |
|
| 683 |
# -------------- Global placeholders (ensure they're declared) -------------- #
|
|
@@ -699,7 +688,10 @@ def get_model_provider(model: str) -> Optional[str]:
|
|
| 699 |
def detect_provider_from_key(api_key: str) -> Optional[str]:
|
| 700 |
"""Infer provider from an API key prefix.
|
| 701 |
|
| 702 |
-
|
|
|
|
|
|
|
|
|
|
| 703 |
"""
|
| 704 |
key = (api_key or "").strip()
|
| 705 |
if not key:
|
|
@@ -713,8 +705,15 @@ def detect_provider_from_key(api_key: str) -> Optional[str]:
|
|
| 713 |
return None
|
| 714 |
|
| 715 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 716 |
def provider_display_name(provider: str) -> str:
|
| 717 |
-
return {"openai": "OpenAI", "
|
| 718 |
|
| 719 |
|
| 720 |
def list_openai_chat_models(api_key: str) -> List[Dict[str, str]]:
|
|
@@ -735,23 +734,6 @@ def list_openai_chat_models(api_key: str) -> List[Dict[str, str]]:
|
|
| 735 |
return out
|
| 736 |
|
| 737 |
|
| 738 |
-
def list_anthropic_models(api_key: str) -> List[Dict[str, str]]:
|
| 739 |
-
if anthropic_sdk is None:
|
| 740 |
-
raise RuntimeError("anthropic SDK is not installed.")
|
| 741 |
-
client = anthropic_sdk.Anthropic(api_key=api_key)
|
| 742 |
-
page = client.models.list(limit=1000)
|
| 743 |
-
out: List[Dict[str, str]] = []
|
| 744 |
-
seen = set()
|
| 745 |
-
for item in getattr(page, "data", []) or []:
|
| 746 |
-
model_id = getattr(item, "id", None) or (item.get("id") if isinstance(item, dict) else None)
|
| 747 |
-
if not model_id or model_id in seen:
|
| 748 |
-
continue
|
| 749 |
-
seen.add(model_id)
|
| 750 |
-
display = getattr(item, "display_name", None) or model_id
|
| 751 |
-
out.append({"id": model_id, "display_name": str(display)})
|
| 752 |
-
return out
|
| 753 |
-
|
| 754 |
-
|
| 755 |
def _fetch_gemini_model_list(api_key: str) -> List[Dict[str, Any]]:
|
| 756 |
url = "https://generativelanguage.googleapis.com/v1beta/models"
|
| 757 |
response = _requests.get(url, params={"key": api_key}, timeout=15)
|
|
@@ -820,8 +802,6 @@ def pick_gemini_embedding_model(api_key: str) -> str:
|
|
| 820 |
def fetch_models_for_provider(provider: str, api_key: str) -> List[Dict[str, str]]:
|
| 821 |
if provider == "openai":
|
| 822 |
return list_openai_chat_models(api_key)
|
| 823 |
-
if provider == "anthropic":
|
| 824 |
-
return list_anthropic_models(api_key)
|
| 825 |
if provider == "gemini":
|
| 826 |
return list_gemini_models(api_key)
|
| 827 |
return []
|
|
@@ -844,10 +824,6 @@ def choose_default_model(models: List[Dict[str, str]], provider: str) -> str:
|
|
| 844 |
def priority(m):
|
| 845 |
mid = (m.get("id") or "").lower()
|
| 846 |
return (1 if "latest" in mid else 0, _date_key(mid), mid)
|
| 847 |
-
if provider == "anthropic":
|
| 848 |
-
sonnets = [m for m in models if "sonnet" in (m.get("id") or "").lower()]
|
| 849 |
-
if sonnets:
|
| 850 |
-
return max(sonnets, key=priority)["id"]
|
| 851 |
if provider == "openai":
|
| 852 |
gpt5 = [m for m in models if "gpt-5" in (m.get("id") or "").lower()]
|
| 853 |
if gpt5:
|
|
@@ -920,9 +896,14 @@ async def set_api_key(
|
|
| 920 |
)
|
| 921 |
api_key = api_key_input.strip()
|
| 922 |
model_provider = detect_provider_from_key(api_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 923 |
if not model_provider:
|
| 924 |
return JSONResponse(
|
| 925 |
-
content={"message": "Unsupported API key format. Use an OpenAI (sk-...)
|
| 926 |
status_code=400
|
| 927 |
)
|
| 928 |
if not model:
|
|
@@ -992,27 +973,6 @@ async def set_api_key(
|
|
| 992 |
**gemini_chart_kwargs
|
| 993 |
)
|
| 994 |
provider_label = "Gemini"
|
| 995 |
-
elif model_provider == "anthropic":
|
| 996 |
-
if ChatAnthropic is None:
|
| 997 |
-
return JSONResponse(
|
| 998 |
-
content={"message": "Anthropic models require langchain-anthropic. Please install it to continue."},
|
| 999 |
-
status_code=500
|
| 1000 |
-
)
|
| 1001 |
-
# No native Anthropic embedding model — QA retrieval requires OpenAI or Gemini.
|
| 1002 |
-
embedding_model = None
|
| 1003 |
-
anthropic_common_kwargs: Dict[str, Any] = {
|
| 1004 |
-
"anthropic_api_key": api_key,
|
| 1005 |
-
"model": DEFAULT_MODEL_QA,
|
| 1006 |
-
"max_tokens": DEFAULT_MAX_OUTPUT_TOKENS,
|
| 1007 |
-
}
|
| 1008 |
-
anthropic_chart_kwargs: Dict[str, Any] = {
|
| 1009 |
-
"anthropic_api_key": api_key,
|
| 1010 |
-
"model": DEFAULT_MODEL_SYSTEM_CHART_EXTRACTION,
|
| 1011 |
-
"max_tokens": DEFAULT_MAX_OUTPUT_TOKENS,
|
| 1012 |
-
}
|
| 1013 |
-
llm_QA = ChatAnthropic(**anthropic_common_kwargs)
|
| 1014 |
-
llm_system_chart_extraction = ChatAnthropic(**anthropic_chart_kwargs)
|
| 1015 |
-
provider_label = "Anthropic"
|
| 1016 |
else:
|
| 1017 |
return JSONResponse(
|
| 1018 |
content={"message": f"Unsupported provider: {model_provider}."},
|
|
@@ -1047,9 +1007,14 @@ async def list_models_for_key(api_key_input: Optional[str] = Form(None)):
|
|
| 1047 |
if not key:
|
| 1048 |
return JSONResponse({"message": "API key is required."}, status_code=400)
|
| 1049 |
provider = detect_provider_from_key(key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1050 |
if not provider:
|
| 1051 |
return JSONResponse(
|
| 1052 |
-
{"message": "Unsupported API key format. Use an OpenAI (sk-...)
|
| 1053 |
status_code=400,
|
| 1054 |
)
|
| 1055 |
try:
|
|
@@ -2123,7 +2088,7 @@ async def upload_files(
|
|
| 2123 |
|
| 2124 |
# Prepare response with file type information
|
| 2125 |
return JSONResponse(content={
|
| 2126 |
-
"message": "
|
| 2127 |
"uploaded": [info["filename"] for info in uploaded_files_info],
|
| 2128 |
"duplicates": duplicates,
|
| 2129 |
"file_types": {
|
|
@@ -2292,6 +2257,34 @@ async def get_available_databases():
|
|
| 2292 |
|
| 2293 |
# -------------------- Conversation Management Endpoints -------------------- #
|
| 2294 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2295 |
@app.get("/conversations/{extraction_id}")
|
| 2296 |
async def get_extraction_conversations(extraction_id: str):
|
| 2297 |
"""
|
|
@@ -2377,14 +2370,15 @@ Please provide a detailed, scientific answer. Follow these guidelines:
|
|
| 2377 |
|
| 2378 |
# Get response from the model
|
| 2379 |
response = await llm_system_chart_extraction.ainvoke(current_history)
|
| 2380 |
-
|
| 2381 |
-
|
|
|
|
| 2382 |
# Update the conversation
|
| 2383 |
update_conversation(extraction_id, conversation_key, new_message, ai_response)
|
| 2384 |
-
|
| 2385 |
return JSONResponse(content={
|
| 2386 |
"question": question,
|
| 2387 |
-
"answer":
|
| 2388 |
"paper_title": conversation["paper_title"],
|
| 2389 |
"paper_type": conversation["paper_type"],
|
| 2390 |
"conversation_updated": True
|
|
@@ -2668,6 +2662,96 @@ async def generate_hypotheses(
|
|
| 2668 |
status_code=500
|
| 2669 |
)
|
| 2670 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2671 |
# -------------------- Hypothesis Continuous Conversation Endpoint -------------------- #
|
| 2672 |
@app.post("/start_hypothesis_conversation")
|
| 2673 |
async def start_hypothesis_conversation(
|
|
@@ -2838,8 +2922,8 @@ AI: """
|
|
| 2838 |
# Get response from LLM
|
| 2839 |
from langchain_core.messages import HumanMessage
|
| 2840 |
response = await llm_QA.ainvoke([HumanMessage(content=prompt)])
|
| 2841 |
-
ai_response = response.content
|
| 2842 |
-
|
| 2843 |
print(f"✅ Received LLM response (length: {len(ai_response)} characters)")
|
| 2844 |
|
| 2845 |
# Store in conversation history
|
|
|
|
| 46 |
|
| 47 |
import requests as _requests
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
try:
|
| 50 |
from openai import OpenAI as OpenAIClient
|
| 51 |
except ImportError:
|
|
|
|
| 61 |
from system_chart_extraction import system_chart_extraction
|
| 62 |
from system_chart_service import SystemChartService
|
| 63 |
from hypotheses_service import HypothesesService
|
| 64 |
+
from prompts import create_hypotheses_generation_prompt, create_design_goals_analysis_prompt
|
| 65 |
+
from conversation_storage import save_conversation, get_conversations, get_all_conversations, update_conversation
|
| 66 |
from plotextract.app import app as plotextract_app
|
| 67 |
|
| 68 |
# Metadata management functions
|
|
|
|
| 666 |
DEFAULT_MODEL_SYSTEM_CHART_EXTRACTION = DEFAULT_MODEL
|
| 667 |
# Shared output-length cap for QA, system chart extraction, and hypotheses.
|
| 668 |
# LangChain's max_tokens maps to provider-specific names:
|
| 669 |
+
# OpenAI max_output_tokens / max_completion_tokens, Gemini maxOutputTokens.
|
| 670 |
DEFAULT_MAX_OUTPUT_TOKENS = 8192
|
| 671 |
|
| 672 |
# -------------- Global placeholders (ensure they're declared) -------------- #
|
|
|
|
| 688 |
def detect_provider_from_key(api_key: str) -> Optional[str]:
|
| 689 |
"""Infer provider from an API key prefix.
|
| 690 |
|
| 691 |
+
AIza... → Gemini, sk-... → OpenAI.
|
| 692 |
+
Anthropic (sk-ant-...) keys are detected but unsupported — they must be
|
| 693 |
+
checked *before* the generic sk- prefix so they are not misread as OpenAI;
|
| 694 |
+
callers reject the "anthropic" value with a clear message.
|
| 695 |
"""
|
| 696 |
key = (api_key or "").strip()
|
| 697 |
if not key:
|
|
|
|
| 705 |
return None
|
| 706 |
|
| 707 |
|
| 708 |
+
UNSUPPORTED_ANTHROPIC_KEY_MESSAGE = (
|
| 709 |
+
"Anthropic (sk-ant-...) keys are not supported: Anthropic does not provide an "
|
| 710 |
+
"embedding model, which this tool requires. Please use an OpenAI (sk-...) or "
|
| 711 |
+
"Gemini (AIza...) key."
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
|
| 715 |
def provider_display_name(provider: str) -> str:
|
| 716 |
+
return {"openai": "OpenAI", "gemini": "Gemini"}.get(provider, provider or "Unknown")
|
| 717 |
|
| 718 |
|
| 719 |
def list_openai_chat_models(api_key: str) -> List[Dict[str, str]]:
|
|
|
|
| 734 |
return out
|
| 735 |
|
| 736 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 737 |
def _fetch_gemini_model_list(api_key: str) -> List[Dict[str, Any]]:
|
| 738 |
url = "https://generativelanguage.googleapis.com/v1beta/models"
|
| 739 |
response = _requests.get(url, params={"key": api_key}, timeout=15)
|
|
|
|
| 802 |
def fetch_models_for_provider(provider: str, api_key: str) -> List[Dict[str, str]]:
|
| 803 |
if provider == "openai":
|
| 804 |
return list_openai_chat_models(api_key)
|
|
|
|
|
|
|
| 805 |
if provider == "gemini":
|
| 806 |
return list_gemini_models(api_key)
|
| 807 |
return []
|
|
|
|
| 824 |
def priority(m):
|
| 825 |
mid = (m.get("id") or "").lower()
|
| 826 |
return (1 if "latest" in mid else 0, _date_key(mid), mid)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 827 |
if provider == "openai":
|
| 828 |
gpt5 = [m for m in models if "gpt-5" in (m.get("id") or "").lower()]
|
| 829 |
if gpt5:
|
|
|
|
| 896 |
)
|
| 897 |
api_key = api_key_input.strip()
|
| 898 |
model_provider = detect_provider_from_key(api_key)
|
| 899 |
+
if model_provider == "anthropic":
|
| 900 |
+
return JSONResponse(
|
| 901 |
+
content={"message": UNSUPPORTED_ANTHROPIC_KEY_MESSAGE},
|
| 902 |
+
status_code=400
|
| 903 |
+
)
|
| 904 |
if not model_provider:
|
| 905 |
return JSONResponse(
|
| 906 |
+
content={"message": "Unsupported API key format. Use an OpenAI (sk-...) or Gemini (AIza...) key."},
|
| 907 |
status_code=400
|
| 908 |
)
|
| 909 |
if not model:
|
|
|
|
| 973 |
**gemini_chart_kwargs
|
| 974 |
)
|
| 975 |
provider_label = "Gemini"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 976 |
else:
|
| 977 |
return JSONResponse(
|
| 978 |
content={"message": f"Unsupported provider: {model_provider}."},
|
|
|
|
| 1007 |
if not key:
|
| 1008 |
return JSONResponse({"message": "API key is required."}, status_code=400)
|
| 1009 |
provider = detect_provider_from_key(key)
|
| 1010 |
+
if provider == "anthropic":
|
| 1011 |
+
return JSONResponse(
|
| 1012 |
+
{"message": UNSUPPORTED_ANTHROPIC_KEY_MESSAGE},
|
| 1013 |
+
status_code=400,
|
| 1014 |
+
)
|
| 1015 |
if not provider:
|
| 1016 |
return JSONResponse(
|
| 1017 |
+
{"message": "Unsupported API key format. Use an OpenAI (sk-...) or Gemini (AIza...) key."},
|
| 1018 |
status_code=400,
|
| 1019 |
)
|
| 1020 |
try:
|
|
|
|
| 2088 |
|
| 2089 |
# Prepare response with file type information
|
| 2090 |
return JSONResponse(content={
|
| 2091 |
+
"message": "Upload complete.",
|
| 2092 |
"uploaded": [info["filename"] for info in uploaded_files_info],
|
| 2093 |
"duplicates": duplicates,
|
| 2094 |
"file_types": {
|
|
|
|
| 2257 |
|
| 2258 |
# -------------------- Conversation Management Endpoints -------------------- #
|
| 2259 |
|
| 2260 |
+
@app.get("/all_conversations")
|
| 2261 |
+
async def get_every_conversation():
|
| 2262 |
+
"""
|
| 2263 |
+
Get conversations across ALL extractions (and therefore all databases),
|
| 2264 |
+
so the frontend dropdown is not limited to the most recent extraction run.
|
| 2265 |
+
"""
|
| 2266 |
+
all_convs = get_all_conversations()
|
| 2267 |
+
|
| 2268 |
+
conversation_list = []
|
| 2269 |
+
for ext_id, conversations in all_convs.items():
|
| 2270 |
+
for conv_key, conv_data in conversations.items():
|
| 2271 |
+
conversation_list.append({
|
| 2272 |
+
"extraction_id": ext_id,
|
| 2273 |
+
"key": conv_key,
|
| 2274 |
+
"title": conv_data["paper_title"],
|
| 2275 |
+
"paper_type": conv_data["paper_type"],
|
| 2276 |
+
"created_at": conv_data["created_at"],
|
| 2277 |
+
"last_updated": conv_data["last_updated"],
|
| 2278 |
+
"message_count": len(conv_data["conversation_history"])
|
| 2279 |
+
})
|
| 2280 |
+
|
| 2281 |
+
conversation_list.sort(key=lambda x: x["created_at"], reverse=True)
|
| 2282 |
+
|
| 2283 |
+
return JSONResponse(content={
|
| 2284 |
+
"conversations": conversation_list,
|
| 2285 |
+
"total_count": len(conversation_list)
|
| 2286 |
+
})
|
| 2287 |
+
|
| 2288 |
@app.get("/conversations/{extraction_id}")
|
| 2289 |
async def get_extraction_conversations(extraction_id: str):
|
| 2290 |
"""
|
|
|
|
| 2370 |
|
| 2371 |
# Get response from the model
|
| 2372 |
response = await llm_system_chart_extraction.ainvoke(current_history)
|
| 2373 |
+
answer_text = llm_content_to_text(response.content)
|
| 2374 |
+
ai_response = AIMessage(content=answer_text)
|
| 2375 |
+
|
| 2376 |
# Update the conversation
|
| 2377 |
update_conversation(extraction_id, conversation_key, new_message, ai_response)
|
| 2378 |
+
|
| 2379 |
return JSONResponse(content={
|
| 2380 |
"question": question,
|
| 2381 |
+
"answer": answer_text,
|
| 2382 |
"paper_title": conversation["paper_title"],
|
| 2383 |
"paper_type": conversation["paper_type"],
|
| 2384 |
"conversation_updated": True
|
|
|
|
| 2662 |
status_code=500
|
| 2663 |
)
|
| 2664 |
|
| 2665 |
+
@app.post("/analyze_design_goals")
|
| 2666 |
+
async def analyze_design_goals(description: str = Form(...)):
|
| 2667 |
+
"""
|
| 2668 |
+
Analyze a free-form materials-design description and suggest the two target
|
| 2669 |
+
properties for hypothesis generation. Runs a single LLM call and returns the
|
| 2670 |
+
two properties so the frontend can pre-fill the editable goal fields.
|
| 2671 |
+
"""
|
| 2672 |
+
global llm_QA
|
| 2673 |
+
|
| 2674 |
+
if llm_QA is None:
|
| 2675 |
+
return JSONResponse(
|
| 2676 |
+
content={"error": "No model set. Please call /set_api_key first."},
|
| 2677 |
+
status_code=400
|
| 2678 |
+
)
|
| 2679 |
+
|
| 2680 |
+
description = (description or "").strip()
|
| 2681 |
+
if not description:
|
| 2682 |
+
return JSONResponse(
|
| 2683 |
+
content={"error": "Please describe your materials design goals first."},
|
| 2684 |
+
status_code=400
|
| 2685 |
+
)
|
| 2686 |
+
|
| 2687 |
+
try:
|
| 2688 |
+
from langchain_core.messages import HumanMessage
|
| 2689 |
+
|
| 2690 |
+
prompt = create_design_goals_analysis_prompt(description)
|
| 2691 |
+
response = await llm_QA.ainvoke([HumanMessage(content=prompt)])
|
| 2692 |
+
raw = llm_content_to_text(response.content).strip()
|
| 2693 |
+
print(f"🎯 Design-goals analysis raw output: {raw[:300]}")
|
| 2694 |
+
|
| 2695 |
+
# Parse the strict "Property 1: ... / Property 2: ..." format robustly.
|
| 2696 |
+
goal_1, goal_2 = _parse_design_goals(raw)
|
| 2697 |
+
|
| 2698 |
+
if not goal_1 or not goal_2:
|
| 2699 |
+
return JSONResponse(
|
| 2700 |
+
content={
|
| 2701 |
+
"error": "Could not confidently extract two design properties. Please refine your description or fill in the fields manually.",
|
| 2702 |
+
"raw": raw
|
| 2703 |
+
},
|
| 2704 |
+
status_code=422
|
| 2705 |
+
)
|
| 2706 |
+
|
| 2707 |
+
return JSONResponse(content={
|
| 2708 |
+
"success": True,
|
| 2709 |
+
"goal_1": goal_1,
|
| 2710 |
+
"goal_2": goal_2
|
| 2711 |
+
})
|
| 2712 |
+
|
| 2713 |
+
except Exception as e:
|
| 2714 |
+
print(f"❌ Error analyzing design goals: {str(e)}")
|
| 2715 |
+
return JSONResponse(
|
| 2716 |
+
content={"error": f"Error analyzing design goals: {str(e)}"},
|
| 2717 |
+
status_code=500
|
| 2718 |
+
)
|
| 2719 |
+
|
| 2720 |
+
def _parse_design_goals(raw: str):
|
| 2721 |
+
"""Extract the two properties from the model output.
|
| 2722 |
+
|
| 2723 |
+
Handles the expected 'Property 1: ...' / 'Property 2: ...' format and a few
|
| 2724 |
+
lenient fallbacks (numbered lists, bullet points).
|
| 2725 |
+
"""
|
| 2726 |
+
goal_1 = ""
|
| 2727 |
+
goal_2 = ""
|
| 2728 |
+
|
| 2729 |
+
def _clean(value: str) -> str:
|
| 2730 |
+
return value.strip().strip('"').strip("'").strip("*").strip("-").strip().rstrip(".")
|
| 2731 |
+
|
| 2732 |
+
m1 = re.search(r"Property\s*1\s*[:\-]\s*(.+)", raw, re.IGNORECASE)
|
| 2733 |
+
m2 = re.search(r"Property\s*2\s*[:\-]\s*(.+)", raw, re.IGNORECASE)
|
| 2734 |
+
if m1:
|
| 2735 |
+
goal_1 = _clean(m1.group(1).splitlines()[0])
|
| 2736 |
+
if m2:
|
| 2737 |
+
goal_2 = _clean(m2.group(1).splitlines()[0])
|
| 2738 |
+
|
| 2739 |
+
# Fallback: take the first two non-empty lines if labels were not found.
|
| 2740 |
+
if not (goal_1 and goal_2):
|
| 2741 |
+
lines = [l.strip() for l in raw.splitlines() if l.strip()]
|
| 2742 |
+
cleaned = []
|
| 2743 |
+
for line in lines:
|
| 2744 |
+
line = re.sub(r"^\s*(?:property\s*\d+|[0-9]+[.)]|[-*•])\s*[:\-]?\s*", "", line, flags=re.IGNORECASE)
|
| 2745 |
+
line = _clean(line)
|
| 2746 |
+
if line:
|
| 2747 |
+
cleaned.append(line)
|
| 2748 |
+
if not goal_1 and len(cleaned) >= 1:
|
| 2749 |
+
goal_1 = cleaned[0]
|
| 2750 |
+
if not goal_2 and len(cleaned) >= 2:
|
| 2751 |
+
goal_2 = cleaned[1]
|
| 2752 |
+
|
| 2753 |
+
return goal_1, goal_2
|
| 2754 |
+
|
| 2755 |
# -------------------- Hypothesis Continuous Conversation Endpoint -------------------- #
|
| 2756 |
@app.post("/start_hypothesis_conversation")
|
| 2757 |
async def start_hypothesis_conversation(
|
|
|
|
| 2922 |
# Get response from LLM
|
| 2923 |
from langchain_core.messages import HumanMessage
|
| 2924 |
response = await llm_QA.ainvoke([HumanMessage(content=prompt)])
|
| 2925 |
+
ai_response = llm_content_to_text(response.content)
|
| 2926 |
+
|
| 2927 |
print(f"✅ Received LLM response (length: {len(ai_response)} characters)")
|
| 2928 |
|
| 2929 |
# Store in conversation history
|
prompts.py
CHANGED
|
@@ -210,6 +210,34 @@ PROMPTS_SYSTEM_CHART_NORMALIZATION = [
|
|
| 210 |
|
| 211 |
# ---- For hypothesis generation ----
|
| 212 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
def create_hypotheses_generation_prompt(material_goal_1, material_goal_2):
|
| 214 |
"""Create the hypotheses generation prompt with user-specified material design goals."""
|
| 215 |
return f'''Background Information: The table you're referring to has been compiled from various system charts found in multiple research papers. Whenever the same paper number appears more than once in the table, it indicates that the entries originate from the same research study. In many materials science challenges, achieving {material_goal_1} requires innovative design approaches. The challenge is to design materials that can maintain {material_goal_2} across multiple demanding criteria simultaneously. This necessitates the synergistic combination of special design principles for superior material properties with relevant deformation mechanisms to find innovative design solutions.
|
|
|
|
| 210 |
|
| 211 |
# ---- For hypothesis generation ----
|
| 212 |
|
| 213 |
+
def create_design_goals_analysis_prompt(description):
|
| 214 |
+
"""Analyze a free-form materials-design description and extract the two key target properties.
|
| 215 |
+
|
| 216 |
+
The user writes a paragraph about what they want to design (goals, trade-offs,
|
| 217 |
+
ideal properties, constraints, target application). This prompt asks the model to
|
| 218 |
+
distill that into exactly two distinct target properties/mechanisms that the
|
| 219 |
+
hypothesis generation should target simultaneously.
|
| 220 |
+
"""
|
| 221 |
+
return f'''You are assisting a materials scientist who is setting up a materials-design hypothesis generation task. The task requires exactly TWO target material properties (or performance goals) that the design must achieve simultaneously, since the tool works by finding synergistic combinations between two objectives that are often in tension (a trade-off).
|
| 222 |
+
|
| 223 |
+
Read the researcher's description of their design goal below, delimited by triple quotes:
|
| 224 |
+
|
| 225 |
+
"""{description}"""
|
| 226 |
+
|
| 227 |
+
From this description, identify the TWO most important, distinct target material properties (or performance goals) that best capture what the researcher wants to achieve simultaneously.
|
| 228 |
+
|
| 229 |
+
Rules:
|
| 230 |
+
1. Return exactly two properties.
|
| 231 |
+
2. Each property must be a concise noun phrase (typically 2-6 words), e.g. "High tensile strength", "Good ductility", "High ionic conductivity", "Low thermal expansion".
|
| 232 |
+
3. The two properties must be distinct and non-overlapping. When the description implies a trade-off (e.g. strength vs. ductility), the two properties should reflect the two competing sides.
|
| 233 |
+
4. Prefer properties explicitly mentioned by the researcher. Only infer a property if the description clearly implies it.
|
| 234 |
+
5. Do not add explanations, units, target values, material names, or any extra text.
|
| 235 |
+
|
| 236 |
+
Respond STRICTLY in the following format and output nothing else:
|
| 237 |
+
Property 1: <first property>
|
| 238 |
+
Property 2: <second property>'''
|
| 239 |
+
|
| 240 |
+
|
| 241 |
def create_hypotheses_generation_prompt(material_goal_1, material_goal_2):
|
| 242 |
"""Create the hypotheses generation prompt with user-specified material design goals."""
|
| 243 |
return f'''Background Information: The table you're referring to has been compiled from various system charts found in multiple research papers. Whenever the same paper number appears more than once in the table, it indicates that the entries originate from the same research study. In many materials science challenges, achieving {material_goal_1} requires innovative design approaches. The challenge is to design materials that can maintain {material_goal_2} across multiple demanding criteria simultaneously. This necessitates the synergistic combination of special design principles for superior material properties with relevant deformation mechanisms to find innovative design solutions.
|