New1 / app.py
RootDeveloperDS's picture
Update app.py
7b8c245 verified
Raw History Blame Contribute Delete
1.54 kB
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()