Wall06 commited on
Commit
336f8fb
·
verified ·
1 Parent(s): 2f5117c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -63
app.py CHANGED
@@ -3,86 +3,91 @@ import os
3
  from google import genai
4
  from google.genai import types
5
 
6
- # 1. Setup API Client
7
- # On Hugging Face, add your key to "Settings > Secrets"
8
- api_key = os.environ.get("GOOGLE_API_KEY")
9
- client = genai.Client(api_key=api_key)
10
-
11
- st.set_page_config(page_title="Gemini 3 Hypothesis Engine", layout="wide")
12
  st.title("🔬 Advanced Scientific Hypothesis Engine")
 
13
 
14
- # 2. Initialize Stateful Chat History (Including Thought Signatures)
15
- if "messages" not in st.session_state:
16
- st.session_state.messages = []
17
 
18
- # 3. Model Configuration (Action Era Settings)
19
- config = types.GenerateContentConfig(
20
- thinking_config=types.ThinkingConfig(
21
- include_thoughts=True,
22
- thinking_level="HIGH" # Forces deep reasoning
23
- ),
24
- tools=[
25
- types.Tool(google_search=types.GoogleSearch()), # Real-time verification
26
- types.Tool(code_execution=types.CodeExecution()) # Math/Logic verification
27
- ],
28
- system_instruction="""You are a Senior Scientific Research Agent.
29
- Your goal is to find contradictions and novel links across multiple research papers.
30
- When a user asks a question, scan the provided context, propose a hypothesis,
31
- and use your Python tool to verify the mathematical feasibility of your theory."""
32
- )
33
 
34
- # 4. UI: Sidebar for Paper Uploads
35
- with st.sidebar:
36
- st.header("Research Materials")
37
- uploaded_files = st.file_uploader("Upload PDFs", type="pdf", accept_multiple_files=True)
38
- if st.button("Clear History"):
39
- st.session_state.messages = []
40
- st.rerun()
 
 
 
 
 
 
 
 
 
41
 
42
- # 5. The Development Loop
43
- def process_query(user_input):
44
- # Add user message to history
45
- st.session_state.messages.append(types.Content(role="user", parts=[types.Part.from_text(user_input)]))
46
-
47
- # Generate content using the full history (this preserves the state)
48
- response = client.models.generate_content(
49
  model="gemini-3-pro-preview",
50
- contents=st.session_state.messages,
51
- config=config
 
 
 
 
 
 
 
 
 
 
52
  )
53
-
54
- # Save the model's response (this contains the mandatory thought_signature)
55
- st.session_state.messages.append(response.candidates[0].content)
56
- return response
57
 
58
- # 6. Streamlit Chat Interface
 
 
 
 
 
 
 
 
 
59
  for msg in st.session_state.messages:
60
- role = "user" if msg.role == "user" else "assistant"
61
- with st.chat_message(role):
62
- # We only display text parts to the user
63
- for part in msg.parts:
64
- if part.text:
65
- st.markdown(part.text)
66
 
67
- if prompt := st.chat_input("Enter a scientific mystery to solve..."):
 
68
  with st.chat_message("user"):
69
  st.markdown(prompt)
70
-
71
  with st.chat_message("assistant"):
72
- with st.status("Thinking & Verifying...", expanded=True) as status:
73
- response = process_query(prompt)
 
74
 
75
- # SHOWING THE "ADVANCED" LEVEL: Display the AI's internal reasoning
76
  if response.candidates[0].thought_summary:
77
- st.info(f"**Reasoning Path:** {response.candidates[0].thought_summary}")
78
 
79
- # Show if the AI used tools (Code/Search)
80
  for part in response.candidates[0].content.parts:
81
  if part.executable_code:
82
- st.code(part.executable_code.code, language="python")
83
  if part.code_execution_result:
84
- st.success(f"Execution Result: {part.code_execution_result.output}")
85
 
86
- status.update(label="Hypothesis Ready!", state="complete")
87
-
88
- st.markdown(response.text)
 
 
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})