Cleanup workspace

#2
by JonCard - opened
flask_requirements.txt DELETED
@@ -1,5 +0,0 @@
1
- flask
2
- langchain
3
- openai
4
- python-dotenv
5
- langchain_openai
 
 
 
 
 
 
gradio_requirements.txt DELETED
@@ -1,5 +0,0 @@
1
- gradio==5.32.1
2
- langchain
3
- openai
4
- python-dotenv
5
- langchain_openai
 
 
 
 
 
 
hf_gradio_ai_app.py DELETED
@@ -1,157 +0,0 @@
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
- # 🤖 G34: 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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
hf_streamlit_ai_app.py DELETED
@@ -1,128 +0,0 @@
1
- # Block 2: Create the Streamlit Application File (app.py)
2
- import streamlit as st
3
- from langchain_openai import ChatOpenAI
4
- from langchain.prompts import ChatPromptTemplate
5
-
6
- # --- Page Configuration ---
7
- st.set_page_config(
8
- page_title="AI Chat Assistant",
9
- page_icon="🤖",
10
- layout="wide",
11
- initial_sidebar_state="expanded"
12
- )
13
-
14
- st.title("🤖 Streamlit AI Chat Assistant")
15
- st.markdown("""
16
- Welcome! Ask any question to the AI assistant. This application uses OpenAI's `gpt-4o-mini` model.
17
- Enter your OpenAI API Key in the sidebar to begin.
18
- """)
19
-
20
- # --- API Key Handling ---
21
- openai_api_key = None
22
-
23
- # Attempt to get API key from st.secrets (for deployed apps)
24
- try:
25
- openai_api_key = st.secrets["OPENAI_API_KEY"]
26
- if openai_api_key:
27
- st.sidebar.success("API key loaded from st.secrets!")
28
- else: # Handle case where secret exists but is empty
29
- st.sidebar.warning("OpenAI API Key found in st.secrets but it's empty. Please provide a valid key.")
30
- except (KeyError, FileNotFoundError): # FileNotFoundError for local st.secrets.toml if used
31
- st.sidebar.info("OpenAI API Key not found in st.secrets. Please enter it below for this session.")
32
-
33
- # Fallback to user input if not found in secrets or if secret was empty
34
- if not openai_api_key:
35
- openai_api_key_input = st.sidebar.text_input(
36
- "Enter your OpenAI API Key:",
37
- type="password",
38
- key="api_key_input_sidebar",
39
- help="Your API key is used only for this session and not stored."
40
- )
41
- if openai_api_key_input:
42
- openai_api_key = openai_api_key_input
43
-
44
- if not openai_api_key:
45
- st.warning("Please provide your OpenAI API Key in the sidebar to use the chat.")
46
- st.stop() # Stop execution if no API key is available
47
-
48
- # --- LangChain Setup (Cached for efficiency) ---
49
- @st.cache_resource # Caches the LLM and prompt template
50
- def get_langchain_components(_api_key_for_cache): # Parameter ensures cache reacts to API key changes if necessary
51
- """Initializes and returns the LangChain LLM and prompt template."""
52
- llm = ChatOpenAI(openai_api_key=_api_key_for_cache, model_name="gpt-4o-mini")
53
-
54
- prompt_template_str = """
55
- You are a knowledgeable and friendly AI assistant.
56
- Your goal is to provide clear, concise, and helpful answers to the user's questions.
57
- If you don't know the answer to a specific question, it's better to say so rather than inventing one.
58
-
59
- User Question: {user_input}
60
-
61
- AI Response:
62
- """
63
- prompt = ChatPromptTemplate.from_template(prompt_template_str)
64
- return llm, prompt
65
-
66
- try:
67
- llm, prompt_template = get_langchain_components(openai_api_key)
68
- except Exception as e:
69
- st.error(f"Failed to initialize AI components. Error: {e}. Check your API key and model access.")
70
- st.stop()
71
-
72
- # --- Initialize session state for storing chat messages ---
73
- if "messages" not in st.session_state:
74
- st.session_state.messages = []
75
-
76
- # --- Display existing chat messages ---
77
- for message in st.session_state.messages:
78
- with st.chat_message(message["role"]):
79
- st.markdown(message["content"])
80
-
81
- # --- Chat Input and AI Response Logic ---
82
- if user_query := st.chat_input("What would you like to ask?"):
83
- # Add user message to session state and display it
84
- st.session_state.messages.append({"role": "user", "content": user_query})
85
- with st.chat_message("user"):
86
- st.markdown(user_query)
87
-
88
- # Get and display AI response
89
- with st.chat_message("assistant"):
90
- message_placeholder = st.empty() # For "Thinking..." message and then the actual response
91
- with st.spinner("AI is thinking..."):
92
- try:
93
- chain = prompt_template | llm
94
- ai_response_message = chain.invoke({"user_input": user_query})
95
- ai_response_content = ai_response_message.content
96
-
97
- message_placeholder.markdown(ai_response_content)
98
- # Add AI response to session state
99
- st.session_state.messages.append({"role": "assistant", "content": ai_response_content})
100
-
101
- except Exception as e:
102
- error_message = f"Sorry, I encountered an error: {str(e)}"
103
- message_placeholder.error(error_message)
104
- st.session_state.messages.append({"role": "assistant", "content": error_message})
105
-
106
- # --- Sidebar Options ---
107
- with st.sidebar:
108
- st.divider()
109
- if st.button("Clear Chat History", key="clear_chat"):
110
- st.session_state.messages = []
111
- st.success("Chat history cleared!")
112
- st.rerun() # Rerun to update the UI immediately
113
-
114
- st.markdown("---")
115
- st.subheader("About")
116
- st.info(
117
- "This is a Streamlit application demonstrating an AI chat interface "
118
- "using LangChain and OpenAI's gpt-4o-mini model."
119
- )
120
-
121
-
122
- # --- Block 3: Run the Streamlit Application ---
123
-
124
- # To start your streamlit app, run the following command in your terminal:
125
-
126
- # streamlit run hf_streamlit_ai_app.py
127
- # Make sure you have the required packages installed:
128
- # pip install streamlit langchain openai langchain_openai -q
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
localhost_ai_app.py DELETED
@@ -1,97 +0,0 @@
1
- # localhost_ai_app.py
2
-
3
- # # Block 1: Set up dependencies
4
- # On a local machine, you would typically run this in your terminal inside a virtual environment to install the necessary packages.
5
- # \!pip install flask langchain openai python-dotenv langchain_openai -q -q -q
6
-
7
- # # Block 2: Import Libraries and Configure API Key
8
-
9
- # import the dependencies
10
- import os
11
- from flask import Flask, request, jsonify
12
- from langchain_openai import ChatOpenAI
13
- from langchain.prompts import ChatPromptTemplate
14
- from dotenv import load_dotenv
15
-
16
- # Load environment variables from .env file
17
- load_dotenv()
18
-
19
- # --- OpenAI API Key Configuration ---
20
- # This relies on the OPENAI_API_KEY being set in your .env file
21
- api_key = os.getenv("OPENAI_API_KEY")
22
-
23
- # # Block 3: Define Prompt Template and Initialize LangChain with OpenAI
24
-
25
- # Initialize the OpenAI LLM
26
- # You can choose different models
27
- # The script will fail here if api_key is None (i.e., not found in .env)
28
- # OPENAI MODEL REFERENCE - (https://platform.openai.com/docs/models)
29
- llm = ChatOpenAI(openai_api_key=api_key, model_name="gpt-4o-mini")
30
-
31
- # Define the prompt template
32
- # This template instructs the AI and includes a placeholder for user input.
33
- prompt_template_str = """
34
- You are a helpful AI assistant. Answer the user's question clearly and concisely.
35
-
36
- User Question: {user_input}
37
-
38
- AI Response:
39
- """
40
- prompt_template = ChatPromptTemplate.from_template(prompt_template_str)
41
-
42
- print("LangChain components initialized.")
43
-
44
- # Block 4: Set up Flask Application and Implement Chat Endpoint
45
-
46
- # --- Set up Flask Application ---
47
- app = Flask(__name__)
48
- print("Flask application created.")
49
-
50
- @app.route('/chat', methods=['POST'])
51
- def chat_endpoint():
52
- try:
53
- data = request.get_json()
54
- if not data or 'user_input' not in data:
55
- return jsonify({"error": "No user_input provided in JSON payload."}), 400
56
-
57
- user_input = data['user_input']
58
-
59
- # Create the LangChain chain (Prompt + LLM)
60
- # LCEL (LangChain Expression Language) is used here
61
- chain = prompt_template | llm
62
-
63
- # Invoke the chain with the user's input
64
- ai_response_message = chain.invoke({"user_input": user_input})
65
-
66
- # The response from ChatOpenAI is an AIMessage object, access its content
67
- ai_response_content = ai_response_message.content
68
-
69
- return jsonify({"ai_response": ai_response_content})
70
-
71
- except Exception as e:
72
- # Log the error for debugging on the server side
73
- print(f"Error processing request: {e}") # Basic logging
74
- return jsonify({"error": "An error occurred while processing your request.", "details": str(e)}), 500
75
-
76
- print("Flask /chat endpoint configured.")
77
-
78
- # # Block 5: Run Locally (Start the Flask Server)
79
-
80
- # Steps to run the Flask application:
81
- # 1. Activate your virtual environment.
82
- # 2. Enter "python3 localhost_ai_app.py" into your terminal.
83
- # 3. In a new terminal, with your flask server running, enter "curl -X POST -H "Content-Type: application/json" -d '{"user_input":"Hello, AI! Whats the capital of Norway?"}' http://127.0.0.1:8000/chat"
84
-
85
- # --- Run Flask Application ---
86
- if __name__ == '__main__':
87
- if not api_key:
88
- print("--------------------------------------------------------------------")
89
- print("ERROR: OpenAI API key not found.")
90
- print("Please create a .env file in the same directory as this script with:")
91
- print("OPENAI_API_KEY=\"your_openai_api_key_here\"")
92
- print("--------------------------------------------------------------------")
93
- else:
94
- print("Starting Flask server...")
95
- # host='0.0.0.0' makes it accessible from your network, not just localhost
96
- # debug=True is useful for development, provides more error details
97
- app.run(host='0.0.0.0', port=8000, debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
streamlit_requirements.txt DELETED
@@ -1,4 +0,0 @@
1
- streamlit
2
- langchain
3
- openai
4
- langchain_openai