benisc90 commited on
Commit
371c6da
·
verified ·
1 Parent(s): 47b681a

Upload folder using huggingface_hub

Browse files
hf_gradio_ai_app.py CHANGED
@@ -73,7 +73,8 @@ def initialize_ai_components():
73
 
74
  The user will describe, in plain English, the type of query they would like to run on this clinical table.
75
  Do your best to provide a SQL query that would return the data they are looking for.
76
- If the user's prompt doesn't seem like a valid query request, just inform them that you cannot help with a task that is not query generation, and explain why their prompt doesn't look relevant to your function.
 
77
 
78
  User Question: {user_input}
79
 
 
73
 
74
  The user will describe, in plain English, the type of query they would like to run on this clinical table.
75
  Do your best to provide a SQL query that would return the data they are looking for.
76
+ The user may also ask for the schema of the table, or for a description of the columns.
77
+ If the user's prompt doesn't seem like a valid query request or a valid question about the schema, inform them that you cannot help with their request, and explain why their prompt doesn't look relevant to your function.
78
 
79
  User Question: {user_input}
80
 
hf_gradio_ai_app_Ben_Clinical_Query_draft3.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gradio_ai_chatbot_dotenv.py
2
+ #
3
+ # To run this script:
4
+ # 1. Create a .env file in the same directory with your OPENAI_API_KEY.
5
+ # Example .env file content:
6
+ # OPENAI_API_KEY="sk-yourActualOpenAIapiKeyGoesHere"
7
+ # 2. Install the required packages:
8
+ # pip install gradio langchain openai langchain_openai python-dotenv
9
+ # 3. Run the script from your terminal:
10
+ # python gradio_ai_chatbot_dotenv.py
11
+ #
12
+ # The script will output a local URL and potentially a public Gradio link.
13
+
14
+ import gradio as gr
15
+ from langchain_openai import ChatOpenAI
16
+ from langchain.prompts import ChatPromptTemplate
17
+ import os
18
+ from dotenv import load_dotenv
19
+
20
+ # --- Load environment variables from .env file ---
21
+ load_dotenv()
22
+
23
+ # --- Global variables and Initial Setup ---
24
+ OPENAI_API_KEY_GLOBAL = os.getenv("OPENAI_API_KEY")
25
+ LANGCHAIN_LLM = None
26
+ LANGCHAIN_PROMPT_TEMPLATE = None
27
+ INITIAL_AI_SETUP_MESSAGE = "" # To store status/error from initial setup
28
+
29
+ def initialize_ai_components():
30
+ """
31
+ Initializes LangChain components (LLM and prompt template) using the API key
32
+ from environment variables. Updates global variables and sets a status message.
33
+ """
34
+ global LANGCHAIN_LLM, LANGCHAIN_PROMPT_TEMPLATE, OPENAI_API_KEY_GLOBAL, INITIAL_AI_SETUP_MESSAGE
35
+
36
+ if not OPENAI_API_KEY_GLOBAL:
37
+ INITIAL_AI_SETUP_MESSAGE = "<p style='color:red; font-weight:bold;'>ERROR: OpenAI API Key not found. Please ensure it's in your .env file or environment variables.</p>"
38
+ print("ERROR: OpenAI API Key not found. Make sure it's in your .env file or environment.")
39
+ return False # Indicate failure
40
+
41
+ try:
42
+ # Initialize the LangChain LLM (OpenAI model)
43
+ LANGCHAIN_LLM = ChatOpenAI(openai_api_key=OPENAI_API_KEY_GLOBAL, model_name="gpt-4o-mini")
44
+
45
+ # Define the prompt template for the LLM
46
+ prompt_template_str = """
47
+ You are a helpful, friendly, and insightful AI assistant.
48
+ You will be given access to a dataset that contains a single table. This table contains sample clinical information that was collected during clinical encounters.
49
+ The rows in the table are per-encounter. Patients who have more frequent clinical encounters will therefore have more rows in the table.
50
+ The table has the following columns:
51
+ index: int64
52
+ ENCOUNTER_ID: int64
53
+ CLINICAL_NOTES: string
54
+ BIRTHDATE: string
55
+ FIRST: string
56
+ START: string
57
+ STOP: string
58
+ PATIENT_ID: int64
59
+ ENCOUNTERCLASS: string
60
+ CODE: int64
61
+ DESCRIPTION: string
62
+ BASE_ENCOUNTER_COST: float64
63
+ TOTAL_CLAIM_COST: float64
64
+ PAYER_COVERAGE: float64
65
+ REASONCODE: float64
66
+ REASONDESCRIPTION: string
67
+ PATIENT_AGE: int64
68
+ DESCRIPTION_OBSERVATIONS: string
69
+ DESCRIPTION_CONDITIONS: string
70
+ DESCRIPTION_MEDICATIONS: string
71
+ DESCRIPTION_PROCEDURES: string
72
+ CLINICAL_NOTES-embeddings: string
73
+
74
+ The user will describe, in plain English, the type of query they would like to run on this clinical table.
75
+ Do your best to provide a SQL query that would return the data they are looking for.
76
+ The user may also ask for the schema of the table, or for a description of the columns.
77
+ If the user's prompt doesn't seem like a valid query request or a valid question about the schema, inform them that you cannot help with their request, and explain why their prompt doesn't look relevant to your function.
78
+
79
+ User Question: {user_input}
80
+
81
+ AI Response:
82
+ """
83
+ LANGCHAIN_PROMPT_TEMPLATE = ChatPromptTemplate.from_template(prompt_template_str)
84
+
85
+ INITIAL_AI_SETUP_MESSAGE = "<p style='color:green; font-weight:bold;'>AI Components Initialized Successfully! Ready to chat. My purpose is to take in natural language questions about the clinical dataset and to generate a relevant SQL query.</p>"
86
+ print("AI Components Initialized Successfully!")
87
+ return True # Indicate success
88
+ except Exception as e:
89
+ INITIAL_AI_SETUP_MESSAGE = f"<p style='color:red; font-weight:bold;'>ERROR: Failed to initialize AI components. Error: {str(e)}. Please check your API key and model access.</p>"
90
+ LANGCHAIN_LLM = None
91
+ LANGCHAIN_PROMPT_TEMPLATE = None
92
+ print(f"ERROR: Failed to initialize AI components: {str(e)}")
93
+ return False # Indicate failure
94
+
95
+ # --- Attempt to initialize AI components when the script loads ---
96
+ AI_INITIALIZED_SUCCESSFULLY = initialize_ai_components()
97
+
98
+ def ai_chat_response_function(user_message, chat_history):
99
+ """
100
+ This is the core function called by Gradio's ChatInterface.
101
+ It takes the user's message and the chat history, and returns the AI's response string.
102
+ """
103
+ if not AI_INITIALIZED_SUCCESSFULLY or not LANGCHAIN_LLM or not LANGCHAIN_PROMPT_TEMPLATE:
104
+ # Use the globally set error message from initialization
105
+ # Clean up HTML for plain error string if needed, or pass raw if Markdown supports it
106
+ error_msg_text = INITIAL_AI_SETUP_MESSAGE.replace("<p style='color:red; font-weight:bold;'>", "").replace("</p>", "")
107
+ return f"ERROR: AI is not ready. Status: {error_msg_text}"
108
+
109
+ # Proceed with generating response if components are ready
110
+ try:
111
+ # Create the LangChain chain (Prompt + LLM)
112
+ chain = LANGCHAIN_PROMPT_TEMPLATE | LANGCHAIN_LLM
113
+
114
+ # Invoke the chain with the user's input
115
+ ai_response = chain.invoke({"user_input": user_message})
116
+
117
+ # Return the content of the AI's response
118
+ return ai_response.content
119
+ except Exception as e:
120
+ print(f"Error during LangChain invocation: {e}") # Log for server-side debugging
121
+ return f"Sorry, an error occurred while trying to get a response: {str(e)}"
122
+
123
+ # --- Gradio Interface Definition using gr.Blocks for layout control ---
124
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky), title="AI Chatbot (Gradio)") as gradio_app:
125
+ gr.Markdown(
126
+ """
127
+ # 🤖 AI Chatbot with Gradio, LangChain & OpenAI
128
+ Powered by OpenAI's `gpt-4o-mini` model.
129
+ OpenAI API Key is loaded from your `.env` file.
130
+ """
131
+ )
132
+
133
+ # Display the initial AI setup status
134
+ gr.Markdown(INITIAL_AI_SETUP_MESSAGE)
135
+
136
+ gr.Markdown("---") # Visual separator
137
+ gr.Markdown("## Chat Interface")
138
+
139
+ # Gradio ChatInterface for the main chat functionality
140
+ chat_interface_component = gr.ChatInterface(
141
+ fn=ai_chat_response_function, # The function that handles chat logic
142
+ chatbot=gr.Chatbot(
143
+ height=550,
144
+ show_label=False,
145
+ placeholder="AI's responses will appear here." if AI_INITIALIZED_SUCCESSFULLY else "AI is not available. Check setup status above.",
146
+ avatar_images=("https://raw.githubusercontent.com/svgmoji/svgmoji/main/packages/svgmoji__openmoji/svg/1F468-1F3FB-200D-1F9B0.svg", "https://raw.githubusercontent.com/gradio-app/gradio/main/gradio/icons/huggingface-logo.svg"),
147
+ type='messages'
148
+ ),
149
+ textbox=gr.Textbox(
150
+ placeholder="Type your message here and press Enter...",
151
+ show_label=False,
152
+ scale=7,
153
+ # Disable textbox if AI did not initialize successfully
154
+ interactive=AI_INITIALIZED_SUCCESSFULLY
155
+ ),
156
+ submit_btn="➡️ Send" if AI_INITIALIZED_SUCCESSFULLY else None, # Hide button if not ready
157
+ examples=[
158
+ "What is Paris, France known for?",
159
+ "Explain the concept of a Large Language Model (LLM) simply.",
160
+ "Can you give me a basic recipe for brownies?",
161
+ "Tell me an interesting fact about sunflowers."
162
+ ] if AI_INITIALIZED_SUCCESSFULLY else None, # Only show examples if AI is ready
163
+ title=None,
164
+ autofocus=True
165
+ )
166
+
167
+ # If AI initialization failed, you might want to make the ChatInterface non-interactive.
168
+ # One way is to conditionally enable/disable components or hide buttons as done above.
169
+ if not AI_INITIALIZED_SUCCESSFULLY:
170
+ # Further disable parts of the chat interface if needed, though ChatInterface
171
+ # doesn't have a simple 'interactive=False' for the whole thing.
172
+ # Hiding buttons and disabling textbox is a good start.
173
+ # The error message in `ai_chat_response_function` will also prevent interaction.
174
+ pass
175
+
176
+
177
+ # --- Main execution block to launch the Gradio app ---
178
+ if __name__ == '__main__':
179
+ print("Attempting to launch Gradio App...")
180
+ if not OPENAI_API_KEY_GLOBAL:
181
+ print("WARNING: OpenAI API Key was not found in environment variables or .env file.")
182
+ print("The application UI will launch, but AI functionality will be disabled.")
183
+ print("Please create a .env file with your OPENAI_API_KEY.")
184
+
185
+ gradio_app.launch(share=True, debug=True)