import os import gradio as gr from langchain.chat_models import ChatOpenAI from langchain import LLMChain, PromptTemplate from langchain.memory import ConversationBufferMemory # ✅ Correct way to fetch the API key OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") # ✅ This MUST be passed explicitly if running outside OpenAI-hosted envs if not OPENAI_API_KEY: raise ValueError("OPENAI_API_KEY is not set in the environment variables.") # ✅ Template template = """You are a helpful assistant to answer user queries and coding questions. Act like the best programmer and explain everything like explaining it to a 5-year-old. {chat_history} User: {user_message} Chatbot:""" # ✅ Prompt prompt = PromptTemplate( input_variables=["chat_history", "user_message"], template=template ) # ✅ Memory memory = ConversationBufferMemory(memory_key="chat_history") # ❌ FIXED: temperature must be a float, not a string llm_chain = LLMChain( llm=ChatOpenAI(temperature=0.5, model_name="gpt-3.5-turbo", openai_api_key=OPENAI_API_KEY), prompt=prompt, verbose=True, memory=memory, ) # ✅ Function needs to return a response AND history (for gr.ChatInterface) def get_text_response(user_message, history): response = llm_chain.predict(user_message=user_message) # History must be returned for the Gradio chat interface to maintain context return response # ✅ Create interface demo = gr.ChatInterface(fn=get_text_response) # ✅ Required for Hugging Face Spaces (they call this file) demo.launch()