Wall06 commited on
Commit
d1dcf94
·
verified ·
1 Parent(s): 8012530

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +87 -34
src/streamlit_app.py CHANGED
@@ -1,40 +1,93 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
 
 
 
 
 
 
 
 
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
 
 
 
 
 
 
 
 
 
 
 
14
  """
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import os
3
+ from google import genai
4
+ from google.genai import types
5
 
6
+ # --- Configuration & Styling ---
7
+ st.set_page_config(page_title="Gemini 3: Hypothesis Engine", layout="wide")
8
+ st.title("🔬 Advanced Scientific Hypothesis Engine")
9
+ st.caption("Powered by Gemini 3 Pro Reasoning & Action Loops")
10
+
11
+ # SECURE API KEY: Add this in Hugging Face "Settings > Secrets"
12
+ API_KEY = os.environ.get("GOOGLE_API_KEY")
13
+
14
+ if not API_KEY:
15
+ st.error("Please add your GOOGLE_API_KEY to the Hugging Face Space Secrets.")
16
+ st.stop()
17
 
18
+ # --- Initialize Gen AI Client ---
19
+ client = genai.Client(api_key=API_KEY)
 
20
 
21
+ # --- Define Advanced System Instructions ---
22
+ SYSTEM_INSTRUCTIONS = """
23
+ You are a Senior Scientific Discovery Agent specializing in cross-disciplinary synthesis.
24
+ Your core objective: Find contradictions, missing links, or novel hypotheses in massive research datasets.
25
+
26
+ STRATEGIC PROTOCOL:
27
+ 1. ANALYSIS: Scan the 1M token context for conflicting claims between papers.
28
+ 2. PLANNING: Explicitly state your reasoning path before taking any action.
29
+ 3. VERIFICATION: Use the 'code_execution' tool to run Python simulations or statistical checks.
30
+ 4. GROUNDING: Use 'google_search' to verify if your discovery is already public.
31
+ 5. PERSISTENCE: If a tool fails, analyze the error and try a different Python approach.
32
+ DO NOT provide medical diagnoses. Focus on chemistry, physics, and materials science.
33
  """
34
 
35
+ # --- Stateful Session Management ---
36
+ if "chat" not in st.session_state:
37
+ # Official SDK handles Thought Signatures automatically in Chat sessions
38
+ st.session_state.chat = client.chats.create(
39
+ model="gemini-3-pro-preview",
40
+ config=types.GenerateContentConfig(
41
+ system_instruction=SYSTEM_INSTRUCTIONS,
42
+ thinking_config=types.ThinkingConfig(
43
+ include_thoughts=True,
44
+ thinking_level=types.ThinkingLevel.HIGH # Mandatory for Marathon Agents
45
+ ),
46
+ tools=[
47
+ types.Tool(google_search=types.GoogleSearchRetrieval()),
48
+ types.Tool(code_execution=types.ToolCodeExecution())
49
+ ],
50
+ temperature=1.0 # Gemini 3 reasoning is optimized for 1.0
51
+ )
52
+ )
53
+ st.session_state.messages = []
54
+
55
+ # --- UI Sidebar: Multi-Paper Ingestion ---
56
+ with st.sidebar:
57
+ st.header("Research Corpus")
58
+ uploaded_files = st.file_uploader("Upload PDFs (Max 1M Tokens)", type="pdf", accept_multiple_files=True)
59
+ if st.button("Reset Lab State"):
60
+ st.session_state.chat = None # Resetting will trigger re-initialization
61
+ st.session_state.messages = []
62
+ st.rerun()
63
+
64
+ # --- Main Interaction Loop ---
65
+ for msg in st.session_state.messages:
66
+ with st.chat_message(msg["role"]):
67
+ st.markdown(msg["content"])
68
+
69
+ if prompt := st.chat_input("Enter your research objective..."):
70
+ st.session_state.messages.append({"role": "user", "content": prompt})
71
+ with st.chat_message("user"):
72
+ st.markdown(prompt)
73
+
74
+ with st.chat_message("assistant"):
75
+ # We use st.status to show the "Thought Signatures" and Action Loops live
76
+ with st.status("Agent Reasoning...", expanded=True) as status:
77
+ response = st.session_state.chat.send_message(prompt)
78
+
79
+ # 1. Display Internal Reasoning (Thought Summary)
80
+ if response.candidates[0].thought_summary:
81
+ st.info(f"**Thought Signature Path:**\n{response.candidates[0].thought_summary}")
82
+
83
+ # 2. Display Action Loop: Code Execution & Search
84
+ for part in response.candidates[0].content.parts:
85
+ if part.executable_code:
86
+ st.code(part.executable_code.code, language="python", label="Agent-Generated Script")
87
+ if part.code_execution_result:
88
+ st.success(f"Execution Output: {part.code_execution_result.output}")
89
+
90
+ status.update(label="Discovery Finalized", state="complete")
91
+
92
+ st.markdown(response.text)
93
+ st.session_state.messages.append({"role": "assistant", "content": response.text})