benisc90 commited on
Commit
3fd1c50
·
verified ·
1 Parent(s): 4e614e6

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. .env +1 -0
  2. README.md +2 -8
  3. gradio_requirements.txt +5 -0
  4. hf_gradio_ai_app.py +157 -0
  5. requirements.txt +5 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ OPENAI_API_KEY="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"
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
  title: Team43TestApp
3
- emoji: 🏢
4
- colorFrom: pink
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 5.33.0
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: Team43TestApp
3
+ app_file: hf_gradio_ai_app.py
 
 
4
  sdk: gradio
5
+ sdk_version: 5.32.1
 
 
6
  ---
 
 
gradio_requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio==5.32.1
2
+ langchain
3
+ openai
4
+ python-dotenv
5
+ langchain_openai
hf_gradio_ai_app.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Answer the user's question clearly, concisely, and in a conversational tone.
49
+ If you don't know the answer or a question is ambiguous, ask for clarification or state that you don't know.
50
+
51
+ User Question: {user_input}
52
+
53
+ AI Response:
54
+ """
55
+ LANGCHAIN_PROMPT_TEMPLATE = ChatPromptTemplate.from_template(prompt_template_str)
56
+
57
+ INITIAL_AI_SETUP_MESSAGE = "<p style='color:green; font-weight:bold;'>AI Components Initialized Successfully! Ready to chat.</p>"
58
+ print("AI Components Initialized Successfully!")
59
+ return True # Indicate success
60
+ except Exception as e:
61
+ 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>"
62
+ LANGCHAIN_LLM = None
63
+ LANGCHAIN_PROMPT_TEMPLATE = None
64
+ print(f"ERROR: Failed to initialize AI components: {str(e)}")
65
+ return False # Indicate failure
66
+
67
+ # --- Attempt to initialize AI components when the script loads ---
68
+ AI_INITIALIZED_SUCCESSFULLY = initialize_ai_components()
69
+
70
+ def ai_chat_response_function(user_message, chat_history):
71
+ """
72
+ This is the core function called by Gradio's ChatInterface.
73
+ It takes the user's message and the chat history, and returns the AI's response string.
74
+ """
75
+ if not AI_INITIALIZED_SUCCESSFULLY or not LANGCHAIN_LLM or not LANGCHAIN_PROMPT_TEMPLATE:
76
+ # Use the globally set error message from initialization
77
+ # Clean up HTML for plain error string if needed, or pass raw if Markdown supports it
78
+ error_msg_text = INITIAL_AI_SETUP_MESSAGE.replace("<p style='color:red; font-weight:bold;'>", "").replace("</p>", "")
79
+ return f"ERROR: AI is not ready. Status: {error_msg_text}"
80
+
81
+ # Proceed with generating response if components are ready
82
+ try:
83
+ # Create the LangChain chain (Prompt + LLM)
84
+ chain = LANGCHAIN_PROMPT_TEMPLATE | LANGCHAIN_LLM
85
+
86
+ # Invoke the chain with the user's input
87
+ ai_response = chain.invoke({"user_input": user_message})
88
+
89
+ # Return the content of the AI's response
90
+ return ai_response.content
91
+ except Exception as e:
92
+ print(f"Error during LangChain invocation: {e}") # Log for server-side debugging
93
+ return f"Sorry, an error occurred while trying to get a response: {str(e)}"
94
+
95
+ # --- Gradio Interface Definition using gr.Blocks for layout control ---
96
+ 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:
97
+ gr.Markdown(
98
+ """
99
+ # 🤖 AI Chatbot with Gradio, LangChain & OpenAI
100
+ Powered by OpenAI's `gpt-4o-mini` model.
101
+ OpenAI API Key is loaded from your `.env` file.
102
+ """
103
+ )
104
+
105
+ # Display the initial AI setup status
106
+ gr.Markdown(INITIAL_AI_SETUP_MESSAGE)
107
+
108
+ gr.Markdown("---") # Visual separator
109
+ gr.Markdown("## Chat Interface")
110
+
111
+ # Gradio ChatInterface for the main chat functionality
112
+ chat_interface_component = gr.ChatInterface(
113
+ fn=ai_chat_response_function, # The function that handles chat logic
114
+ chatbot=gr.Chatbot(
115
+ height=550,
116
+ show_label=False,
117
+ placeholder="AI's responses will appear here." if AI_INITIALIZED_SUCCESSFULLY else "AI is not available. Check setup status above.",
118
+ 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"),
119
+ type='messages'
120
+ ),
121
+ textbox=gr.Textbox(
122
+ placeholder="Type your message here and press Enter...",
123
+ show_label=False,
124
+ scale=7,
125
+ # Disable textbox if AI did not initialize successfully
126
+ interactive=AI_INITIALIZED_SUCCESSFULLY
127
+ ),
128
+ submit_btn="➡️ Send" if AI_INITIALIZED_SUCCESSFULLY else None, # Hide button if not ready
129
+ examples=[
130
+ "What is Paris, France known for?",
131
+ "Explain the concept of a Large Language Model (LLM) simply.",
132
+ "Can you give me a basic recipe for brownies?",
133
+ "Tell me an interesting fact about sunflowers."
134
+ ] if AI_INITIALIZED_SUCCESSFULLY else None, # Only show examples if AI is ready
135
+ title=None,
136
+ autofocus=True
137
+ )
138
+
139
+ # If AI initialization failed, you might want to make the ChatInterface non-interactive.
140
+ # One way is to conditionally enable/disable components or hide buttons as done above.
141
+ if not AI_INITIALIZED_SUCCESSFULLY:
142
+ # Further disable parts of the chat interface if needed, though ChatInterface
143
+ # doesn't have a simple 'interactive=False' for the whole thing.
144
+ # Hiding buttons and disabling textbox is a good start.
145
+ # The error message in `ai_chat_response_function` will also prevent interaction.
146
+ pass
147
+
148
+
149
+ # --- Main execution block to launch the Gradio app ---
150
+ if __name__ == '__main__':
151
+ print("Attempting to launch Gradio App...")
152
+ if not OPENAI_API_KEY_GLOBAL:
153
+ print("WARNING: OpenAI API Key was not found in environment variables or .env file.")
154
+ print("The application UI will launch, but AI functionality will be disabled.")
155
+ print("Please create a .env file with your OPENAI_API_KEY.")
156
+
157
+ gradio_app.launch(share=True, debug=True)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio==5.32.1
2
+ langchain
3
+ openai
4
+ python-dotenv
5
+ langchain_openai