duroodia commited on
Commit
d3e6758
Β·
verified Β·
1 Parent(s): 7adc4b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -81
app.py CHANGED
@@ -1,114 +1,92 @@
1
  import os
2
  import asyncio
3
  import streamlit as st
4
- from pydantic import BaseModel
5
  from dotenv import load_dotenv
6
- from agents import (
7
- Agent,
8
- InputGuardrail,
9
- GuardrailFunctionOutput,
10
- Runner,
11
- OpenAIChatCompletionsModel,
12
- RunConfig,
13
- AsyncOpenAI,
14
- )
15
 
16
  # ------------------------------
17
  # 1. Load environment variables
18
  # ------------------------------
19
  load_dotenv()
20
- GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
21
 
22
  if not GEMINI_API_KEY:
23
- st.error("❌ GEMINI_API_KEY is not set in the .env file.")
24
  st.stop()
25
 
26
  # ------------------------------
27
- # 2. Gemini client
28
- # ------------------------------
29
- external_client = AsyncOpenAI(
30
- api_key=GEMINI_API_KEY,
31
- base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
32
- )
33
-
34
- # ------------------------------
35
- # 3. Gemini model
36
  # ------------------------------
37
- model = OpenAIChatCompletionsModel(
38
- model="gemini-2.0-flash", # can be gemini-1.5-flash or gemini-1.5-pro
39
- openai_client=external_client,
40
- )
41
 
42
  # ------------------------------
43
- # 4. RunConfig
44
- # ------------------------------
45
- config = RunConfig(
46
- model=model,
47
- model_provider=external_client,
48
- tracing_disabled=True
49
- )
50
-
51
- # ------------------------------
52
- # 5. Guardrail output schema
53
  # ------------------------------
54
  class RequirementOutput(BaseModel):
55
  is_requirement: bool
56
  reasoning: str
57
 
58
  # ------------------------------
59
- # 6. Guardrail agent
60
  # ------------------------------
61
- guardrail_agent = Agent(
62
- name="Guardrail check",
63
- instructions=(
64
- "You are a filter agent. "
65
- "Your job is to decide if the user query is safe, relevant, and should be answered. "
66
- "- If the query is about math, history, or general learning β†’ set is_requirement=True. "
67
- "- If the query is harmful, unsafe, spam, or irrelevant β†’ set is_requirement=False. "
68
- "Always explain your reasoning briefly."
69
- ),
70
- output_type=RequirementOutput,
71
- )
72
 
73
- # ------------------------------
74
- # 7. Math & History tutor agents
75
- # ------------------------------
76
- math_tutor_agent = Agent(
77
- name="Math Tutor",
78
- handoff_description="Specialist agent for Math Tutoring",
79
- instructions="You provide help with math-related queries. Explain step by step with reasoning and examples.",
80
- )
81
-
82
- history_tutor_agent = Agent(
83
- name="History Tutor",
84
- handoff_description="Specialist agent for History Tutoring",
85
- instructions="You provide assistance with history-related queries. Explain important events and context clearly.",
86
- )
 
87
 
88
  # ------------------------------
89
- # 8. Guardrail function
90
  # ------------------------------
91
- async def requirement_guardrail(ctx, agent, input_data):
92
- result = await Runner.run(guardrail_agent, input_data, context=ctx.context, run_config=config)
93
- final_output = result.final_output_as(RequirementOutput)
94
 
95
- return GuardrailFunctionOutput(
96
- output_info=final_output,
97
- tripwire_triggered=not final_output.is_requirement
98
- )
99
 
100
  # ------------------------------
101
- # 9. Triage agent
102
  # ------------------------------
103
- triage_agent = Agent(
104
- name="Triage Agent",
105
- instructions="You decide which agent (Math or History) should handle the query.",
106
- handoffs=[math_tutor_agent, history_tutor_agent],
107
- input_guardrails=[InputGuardrail(guardrail_function=requirement_guardrail)],
108
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
  # ------------------------------
111
- # 10. Streamlit UI
112
  # ------------------------------
113
  st.set_page_config(page_title="Multiple Agents App", page_icon="πŸ€–", layout="centered")
114
  st.title("πŸ€– Multiple Agents Tutor (Math + History)")
@@ -118,11 +96,13 @@ user_query = st.text_input("Enter your question:", placeholder="e.g., What is 10
118
  submit = st.button("Get Answer")
119
 
120
  if submit and user_query.strip():
121
- async def run_agent():
122
- result = await Runner.run(triage_agent, user_query, run_config=config)
123
- return result.final_output
 
 
124
 
125
  with st.spinner("Thinking... πŸ€”"):
126
- answer = asyncio.run(run_agent())
127
  st.success("βœ… Answer:")
128
  st.write(answer)
 
1
  import os
2
  import asyncio
3
  import streamlit as st
 
4
  from dotenv import load_dotenv
5
+ import google.generativeai as genai
6
+ from pydantic import BaseModel
 
 
 
 
 
 
 
7
 
8
  # ------------------------------
9
  # 1. Load environment variables
10
  # ------------------------------
11
  load_dotenv()
12
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
13
 
14
  if not GEMINI_API_KEY:
15
+ st.error("❌ GEMINI_API_KEY is not set in Secrets.")
16
  st.stop()
17
 
18
  # ------------------------------
19
+ # 2. Configure Gemini client
 
 
 
 
 
 
 
 
20
  # ------------------------------
21
+ genai.configure(api_key=GEMINI_API_KEY)
22
+ model = genai.GenerativeModel("gemini-1.5-flash")
 
 
23
 
24
  # ------------------------------
25
+ # 3. Guardrail output schema
 
 
 
 
 
 
 
 
 
26
  # ------------------------------
27
  class RequirementOutput(BaseModel):
28
  is_requirement: bool
29
  reasoning: str
30
 
31
  # ------------------------------
32
+ # 4. Guardrail check
33
  # ------------------------------
34
+ async def requirement_guardrail(query: str) -> RequirementOutput:
35
+ guardrail_prompt = f"""
36
+ Decide if the user query should be answered.
 
 
 
 
 
 
 
 
37
 
38
+ Query: {query}
39
+
40
+ Rules:
41
+ - If query is about math, history, or learning β†’ is_requirement=True.
42
+ - If query is unsafe, spam, or irrelevant β†’ is_requirement=False.
43
+ Always explain your reasoning.
44
+ """
45
+
46
+ resp = model.generate_content(guardrail_prompt)
47
+ text = resp.text.strip()
48
+
49
+ if "true" in text.lower():
50
+ return RequirementOutput(is_requirement=True, reasoning=text)
51
+ else:
52
+ return RequirementOutput(is_requirement=False, reasoning=text)
53
 
54
  # ------------------------------
55
+ # 5. Math & History agents
56
  # ------------------------------
57
+ async def math_tutor(query: str) -> str:
58
+ resp = model.generate_content(f"Explain step by step: {query}")
59
+ return resp.text
60
 
61
+ async def history_tutor(query: str) -> str:
62
+ resp = model.generate_content(f"Explain clearly: {query}")
63
+ return resp.text
 
64
 
65
  # ------------------------------
66
+ # 6. Triage agent
67
  # ------------------------------
68
+ async def triage_agent(query: str) -> str:
69
+ triage_prompt = f"""
70
+ Decide which agent should answer.
71
+
72
+ Query: {query}
73
+
74
+ Options: Math Tutor or History Tutor.
75
+ Reply with exactly one: "math" or "history".
76
+ """
77
+
78
+ resp = model.generate_content(triage_prompt)
79
+ decision = resp.text.strip().lower()
80
+
81
+ if "math" in decision:
82
+ return await math_tutor(query)
83
+ elif "history" in decision:
84
+ return await history_tutor(query)
85
+ else:
86
+ return "πŸ€– Sorry, I could not decide which tutor should handle this question."
87
 
88
  # ------------------------------
89
+ # 7. Streamlit UI
90
  # ------------------------------
91
  st.set_page_config(page_title="Multiple Agents App", page_icon="πŸ€–", layout="centered")
92
  st.title("πŸ€– Multiple Agents Tutor (Math + History)")
 
96
  submit = st.button("Get Answer")
97
 
98
  if submit and user_query.strip():
99
+ async def run_query():
100
+ guardrail = await requirement_guardrail(user_query)
101
+ if not guardrail.is_requirement:
102
+ return f"❌ Blocked by guardrail: {guardrail.reasoning}"
103
+ return await triage_agent(user_query)
104
 
105
  with st.spinner("Thinking... πŸ€”"):
106
+ answer = asyncio.run(run_query())
107
  st.success("βœ… Answer:")
108
  st.write(answer)