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

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +61 -49
src/streamlit_app.py CHANGED
@@ -12,7 +12,7 @@ st.caption("Powered by Gemini 3 Pro Reasoning & Action Loops")
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 ---
@@ -20,44 +20,48 @@ 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
 
@@ -72,22 +76,30 @@ if prompt := st.chat_input("Enter your research objective..."):
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})
 
 
12
  API_KEY = os.environ.get("GOOGLE_API_KEY")
13
 
14
  if not API_KEY:
15
+ st.error("Error: GOOGLE_API_KEY not found. Add it to your Space Secrets.")
16
  st.stop()
17
 
18
  # --- Initialize Gen AI Client ---
 
20
 
21
  # --- Define Advanced System Instructions ---
22
  SYSTEM_INSTRUCTIONS = """
23
+ You are a Senior Scientific Research Agent.
24
+ Your goal is to find contradictions and novel links across multiple research papers.
25
+ When a user asks a question, scan the provided context, propose a hypothesis,
26
+ and use your Python tool to verify the mathematical feasibility of your theory.
27
+ Use Thought Signatures to maintain your plan across multi-step tool calls.
 
 
 
 
 
28
  """
29
 
30
+ # --- Configuration for Action Era Reasoning ---
31
+ gen_config = types.GenerateContentConfig(
32
+ system_instruction=SYSTEM_INSTRUCTIONS,
33
+ thinking_config=types.ThinkingConfig(
34
+ include_thoughts=True,
35
+ thinking_level=types.ThinkingLevel.HIGH
36
+ ),
37
+ tools=[
38
+ types.Tool(google_search=types.GoogleSearchRetrieval()),
39
+ types.Tool(code_execution=types.ToolCodeExecution())
40
+ ],
41
+ temperature=1.0
42
+ )
43
+
44
+ # --- Robust Session Management (Fixes the NoneType Error) ---
45
+ if "messages" not in st.session_state:
 
 
46
  st.session_state.messages = []
47
 
48
+ # Initialize or Re-initialize Chat Session if it is missing
49
+ if "chat" not in st.session_state or st.session_state.chat is None:
50
+ try:
51
+ st.session_state.chat = client.chats.create(
52
+ model="gemini-3-pro-preview",
53
+ config=gen_config
54
+ )
55
+ except Exception as e:
56
+ st.error(f"Failed to initialize Gemini 3 Chat: {e}")
57
+ st.stop()
58
+
59
+ # --- UI Sidebar: Multi-Paper Ingest ---
60
  with st.sidebar:
61
  st.header("Research Corpus")
62
  uploaded_files = st.file_uploader("Upload PDFs (Max 1M Tokens)", type="pdf", accept_multiple_files=True)
63
  if st.button("Reset Lab State"):
64
+ st.session_state.chat = None # This will trigger re-initialization on rerun
65
  st.session_state.messages = []
66
  st.rerun()
67
 
 
76
  st.markdown(prompt)
77
 
78
  with st.chat_message("assistant"):
79
+ with st.status("Agent Reasoning & Verifying...", expanded=True) as status:
80
+ try:
81
+ # Double-check initialization before calling
82
+ if st.session_state.chat is None:
83
+ st.session_state.chat = client.chats.create(model="gemini-3-pro-preview", config=gen_config)
84
+
85
+ response = st.session_state.chat.send_message(prompt)
86
+
87
+ # Display Internal Reasoning (Thought Summary)
88
+ if response.candidates[0].thought_summary:
89
+ st.info(f"**Reasoning Path:**\n{response.candidates[0].thought_summary}")
90
+
91
+ # Display Action Loop: Code & Search
92
+ for part in response.candidates[0].content.parts:
93
+ if part.executable_code:
94
+ st.code(part.executable_code.code, language="python", label="Agent Script")
95
+ if part.code_execution_result:
96
+ st.success(f"Output: {part.code_execution_result.output}")
97
+
98
+ status.update(label="Analysis Complete", state="complete")
99
+
100
+ st.markdown(response.text)
101
+ st.session_state.messages.append({"role": "assistant", "content": response.text})
102
 
103
+ except Exception as e:
104
+ st.error(f"An error occurred during reasoning: {e}")
105
+ status.update(label="Error Occurred", state="error")