NitinBot001 commited on
Commit
3c51633
·
verified ·
1 Parent(s): 1eb8183

Update disease.py

Browse files
Files changed (1) hide show
  1. disease.py +141 -144
disease.py CHANGED
@@ -1,145 +1,142 @@
1
- import os
2
- import json
3
- from flask import Flask, request, jsonify
4
- import google.generativeai as genai
5
- import dotenv
6
-
7
- dotenv.load_dotenv()
8
-
9
- # --- Configuration ---
10
- FACT_SHEET_DIR = "Text_Files"
11
-
12
- # --- System Instruction for the Gemini Model ---
13
- # This instruction guides the model's behavior, ensuring it stays on task
14
- # and uses only the tools and information we provide.
15
- SYSTEM_INSTRUCTION = """
16
- You are a helpful Health Fact Sheet Assistant. Your role is to answer questions
17
- about specific diseases based ONLY on the information contained in the fact sheets
18
- provided to you through the get_disease_fact_sheet tool.
19
- Generate response in same language as user query.
20
-
21
- Follow these rules strictly:
22
- 1. Use the fact sheet for answers whenever possible.
23
- 2. To get information, call the get_disease_fact_sheet function.
24
- 3. If the fact sheet doesn't cover the answer, reply using general knowledge and include a disclaimer.
25
- 4. First, check the user's query to see which disease it refers to, then fetch that fact sheet.
26
- 5. If the query isn't about a specific disease, reply using general knowledge with a disclaimer.
27
- 6. Keep responses clear, short, and simple. Don't mention the source of the information.
28
- """
29
-
30
- # Configure the Google Generative AI SDK.
31
- try:
32
- # This will automatically look for the GOOGLE_API_KEY environment variable.
33
- genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
34
-
35
- # Initialize the Gemini model with the system instruction.
36
- # We recommend using a model that is highly optimized for tool use.
37
- model = genai.GenerativeModel(
38
- 'gemini-1.5-flash',
39
- system_instruction=SYSTEM_INSTRUCTION
40
- )
41
- except Exception as e:
42
- print(f"Error configuring Google Generative AI: {e}")
43
- print("Please make sure your GOOGLE_API_KEY environment variable is set.")
44
- model = None
45
-
46
- # --- Flask App Initialization ---
47
- app = Flask(__name__)
48
-
49
-
50
- # --- Helper Functions (Tool Implementation) ---
51
-
52
- def get_available_diseases():
53
- """Scans the directory for available disease fact sheets."""
54
- if not os.path.isdir(FACT_SHEET_DIR):
55
- return []
56
- # Create a clean list of names from filenames (e.g., "Chickenpox_and_Shingles.txt" -> "Chickenpox and Shingles")
57
- return [os.path.splitext(f)[0].replace('_', ' ') for f in os.listdir(FACT_SHEET_DIR) if f.endswith(".txt")]
58
-
59
- def get_disease_fact_sheet(disease_name: str):
60
- """
61
- This is the actual Python function that gets executed by the model.
62
- It reads the content of a specific disease's text file from the local directory.
63
- """
64
- print(f"--- TOOL EXECUTION: Running get_disease_fact_sheet(disease_name='{disease_name}') ---")
65
- # Convert the friendly name back to a filename format
66
- filename = disease_name.replace(' ', '_') + ".txt"
67
- filepath = os.path.join(FACT_SHEET_DIR, filename)
68
-
69
- if os.path.exists(filepath):
70
- with open(filepath, 'r', encoding='utf-8') as f:
71
- content = f.read()
72
- print(f"--- SUCCESS: Found and read '{filename}' ---")
73
- # Return a dictionary, which will be implicitly handled by the Gemini SDK
74
- return {"disease": disease_name, "content": content}
75
- else:
76
- print(f"--- ERROR: Fact sheet not found for '{disease_name}' ---")
77
- return {"error": f"Fact sheet not found for the disease: {disease_name}."}
78
-
79
-
80
- # --- Main API Endpoint ---
81
-
82
- @app.route('/ask', methods=['POST'])
83
- def ask_question():
84
- """
85
- Handles user queries by orchestrating the interaction with the Gemini model,
86
- which is guided by the system instruction to use the provided tools and context.
87
- """
88
- if not model:
89
- return jsonify({"error": "Gemini client is not configured. Check your API key."}), 500
90
-
91
- data = request.get_json()
92
- if not data or 'query' not in data:
93
- return jsonify({"error": "Request must be JSON and contain a 'query' field."}), 400
94
-
95
- user_query = data['query']
96
- print(f"\n=================================================")
97
- print(f"Received new query: '{user_query}'")
98
- print(f"=================================================")
99
-
100
-
101
- available_diseases = get_available_diseases()
102
- if not available_diseases:
103
- return jsonify({"error": f"No fact sheets found in the '{FACT_SHEET_DIR}' directory."}), 500
104
-
105
- # === Orchestration with Gemini ===
106
- try:
107
- # We start a chat session. The model will automatically handle calling the
108
- # function and using its output to generate a final answer, thanks to
109
- # automatic function calling and the system instruction.
110
- chat = model.start_chat(enable_automatic_function_calling=True)
111
-
112
- # Construct a more informative prompt for the model.
113
- prompt = f"""
114
- Here is the user's question: '{user_query}'
115
-
116
- Please use your tools to answer it. The available diseases you can look up are:
117
- {', '.join(available_diseases)}
118
- """
119
-
120
- print("--- Sending request to Gemini... ---")
121
- # Send the user's query and the definitions of the available tools
122
- response = chat.send_message(
123
- prompt,
124
- tools=[get_disease_fact_sheet] # Pass the actual function reference
125
- )
126
-
127
- final_answer = response.text
128
- print(f"--- Gemini's Final Answer: ---\n{final_answer}\n")
129
- return jsonify({"response": final_answer})
130
-
131
- except Exception as e:
132
- print(f"--- An unexpected error occurred: {e} ---")
133
- return jsonify({"error": f"Gemini API Error: {e}"}), 500
134
-
135
-
136
- # --- To run the app ---
137
- if __name__ == '__main__':
138
- # Make sure the Text_Files directory exists before starting
139
- if not os.path.isdir(FACT_SHEET_DIR):
140
- print(f"CRITICAL ERROR: The directory '{FACT_SHEET_DIR}' does not exist.")
141
- print("Please create it and populate it with the disease .txt files.")
142
- else:
143
- print("Starting Flask server...")
144
- print(f"Fact sheets loaded for: {', '.join(get_available_diseases())}")
145
  app.run(debug=True, port=5001)
 
1
+ import os
2
+ import json
3
+ from flask import Flask, request, jsonify
4
+ import google.generativeai as genai
5
+
6
+ # --- Configuration ---
7
+ FACT_SHEET_DIR = "Text_Files"
8
+
9
+ # --- System Instruction for the Gemini Model ---
10
+ # This instruction guides the model's behavior, ensuring it stays on task
11
+ # and uses only the tools and information we provide.
12
+ SYSTEM_INSTRUCTION = """
13
+ You are a helpful Health Fact Sheet Assistant. Your role is to answer questions
14
+ about specific diseases based ONLY on the information contained in the fact sheets
15
+ provided to you through the get_disease_fact_sheet tool.
16
+ Generate response in same language as user query.
17
+
18
+ Follow these rules strictly:
19
+ 1. Use the fact sheet for answers whenever possible.
20
+ 2. To get information, call the get_disease_fact_sheet function.
21
+ 3. If the fact sheet doesn't cover the answer, reply using general knowledge and include a disclaimer.
22
+ 4. First, check the user's query to see which disease it refers to, then fetch that fact sheet.
23
+ 5. If the query isn't about a specific disease, reply using general knowledge with a disclaimer.
24
+ 6. Keep responses clear, short, and simple. Don't mention the source of the information.
25
+ """
26
+
27
+ # Configure the Google Generative AI SDK.
28
+ try:
29
+ # This will automatically look for the GOOGLE_API_KEY environment variable.
30
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
31
+
32
+ # Initialize the Gemini model with the system instruction.
33
+ # We recommend using a model that is highly optimized for tool use.
34
+ model = genai.GenerativeModel(
35
+ 'gemini-1.5-flash',
36
+ system_instruction=SYSTEM_INSTRUCTION
37
+ )
38
+ except Exception as e:
39
+ print(f"Error configuring Google Generative AI: {e}")
40
+ print("Please make sure your GOOGLE_API_KEY environment variable is set.")
41
+ model = None
42
+
43
+ # --- Flask App Initialization ---
44
+ app = Flask(__name__)
45
+
46
+
47
+ # --- Helper Functions (Tool Implementation) ---
48
+
49
+ def get_available_diseases():
50
+ """Scans the directory for available disease fact sheets."""
51
+ if not os.path.isdir(FACT_SHEET_DIR):
52
+ return []
53
+ # Create a clean list of names from filenames (e.g., "Chickenpox_and_Shingles.txt" -> "Chickenpox and Shingles")
54
+ return [os.path.splitext(f)[0].replace('_', ' ') for f in os.listdir(FACT_SHEET_DIR) if f.endswith(".txt")]
55
+
56
+ def get_disease_fact_sheet(disease_name: str):
57
+ """
58
+ This is the actual Python function that gets executed by the model.
59
+ It reads the content of a specific disease's text file from the local directory.
60
+ """
61
+ print(f"--- TOOL EXECUTION: Running get_disease_fact_sheet(disease_name='{disease_name}') ---")
62
+ # Convert the friendly name back to a filename format
63
+ filename = disease_name.replace(' ', '_') + ".txt"
64
+ filepath = os.path.join(FACT_SHEET_DIR, filename)
65
+
66
+ if os.path.exists(filepath):
67
+ with open(filepath, 'r', encoding='utf-8') as f:
68
+ content = f.read()
69
+ print(f"--- SUCCESS: Found and read '{filename}' ---")
70
+ # Return a dictionary, which will be implicitly handled by the Gemini SDK
71
+ return {"disease": disease_name, "content": content}
72
+ else:
73
+ print(f"--- ERROR: Fact sheet not found for '{disease_name}' ---")
74
+ return {"error": f"Fact sheet not found for the disease: {disease_name}."}
75
+
76
+
77
+ # --- Main API Endpoint ---
78
+
79
+ @app.route('/ask', methods=['POST'])
80
+ def ask_question():
81
+ """
82
+ Handles user queries by orchestrating the interaction with the Gemini model,
83
+ which is guided by the system instruction to use the provided tools and context.
84
+ """
85
+ if not model:
86
+ return jsonify({"error": "Gemini client is not configured. Check your API key."}), 500
87
+
88
+ data = request.get_json()
89
+ if not data or 'query' not in data:
90
+ return jsonify({"error": "Request must be JSON and contain a 'query' field."}), 400
91
+
92
+ user_query = data['query']
93
+ print(f"\n=================================================")
94
+ print(f"Received new query: '{user_query}'")
95
+ print(f"=================================================")
96
+
97
+
98
+ available_diseases = get_available_diseases()
99
+ if not available_diseases:
100
+ return jsonify({"error": f"No fact sheets found in the '{FACT_SHEET_DIR}' directory."}), 500
101
+
102
+ # === Orchestration with Gemini ===
103
+ try:
104
+ # We start a chat session. The model will automatically handle calling the
105
+ # function and using its output to generate a final answer, thanks to
106
+ # automatic function calling and the system instruction.
107
+ chat = model.start_chat(enable_automatic_function_calling=True)
108
+
109
+ # Construct a more informative prompt for the model.
110
+ prompt = f"""
111
+ Here is the user's question: '{user_query}'
112
+
113
+ Please use your tools to answer it. The available diseases you can look up are:
114
+ {', '.join(available_diseases)}
115
+ """
116
+
117
+ print("--- Sending request to Gemini... ---")
118
+ # Send the user's query and the definitions of the available tools
119
+ response = chat.send_message(
120
+ prompt,
121
+ tools=[get_disease_fact_sheet] # Pass the actual function reference
122
+ )
123
+
124
+ final_answer = response.text
125
+ print(f"--- Gemini's Final Answer: ---\n{final_answer}\n")
126
+ return jsonify({"response": final_answer})
127
+
128
+ except Exception as e:
129
+ print(f"--- An unexpected error occurred: {e} ---")
130
+ return jsonify({"error": f"Gemini API Error: {e}"}), 500
131
+
132
+
133
+ # --- To run the app ---
134
+ if __name__ == '__main__':
135
+ # Make sure the Text_Files directory exists before starting
136
+ if not os.path.isdir(FACT_SHEET_DIR):
137
+ print(f"CRITICAL ERROR: The directory '{FACT_SHEET_DIR}' does not exist.")
138
+ print("Please create it and populate it with the disease .txt files.")
139
+ else:
140
+ print("Starting Flask server...")
141
+ print(f"Fact sheets loaded for: {', '.join(get_available_diseases())}")
 
 
 
142
  app.run(debug=True, port=5001)