Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233342 unmodified lines373839404142434445464748491 unmodified line5152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import osimport yamlimport gradio as grfrom langchain.agents import initialize_agent, Toolfrom langchain.prompts import PromptTemplatefrom langchain_huggingface import HuggingFaceEndpoint # Correct import# Load environment variablesHF_API_KEY = os.environ.get("HUGGINGFACEHUB_API_TOKEN") # Correct environment variable nameHF_MODEL_ID = os.environ.get("HF_MODEL_ID", "google/flan-t5-xxl")# Load prompt templateswith open("prompts.yaml", 'r') as stream:all_prompts = yaml.safe_load(stream)prompt_templates = all_prompts["prompts"] # Access the nested 'prompts' dictionary# Now you can access prompt_templates["default"], prompt_templates["system_prompt"], etc.prompt_template = PromptTemplate(input_variables=["user_input", "tool_names", "tools"],template=prompt_templates["default"] # This will now work!)# Define the get_motivational_quote tooldef get_motivational_quote():quotes = ["Believe you can and you're halfway there.","Your limitation—it's only your imagination.","Push yourself, because no one else is going to do it for you.","Great things never come from comfort zones.","Dream it. Wish it. Do it."]import randomreturn random.choice(quotes)2 unmodified linesTool(name="MotivationalQuote",func=get_motivational_quote,description="Use this tool to get a motivational quote. It takes no input.", # Clear description)]# Initialize the language modelfrom langchain_huggingface import HuggingFaceEndpointllm = HuggingFaceEndpoint(repo_id=HF_MODEL_ID,temperature=0.7,1 unmodified linehuggingfacehub_api_token=HF_API_KEY,)# Create the prompt templateprompt_template = PromptTemplate(input_variables=["user_input", "tool_names", "tools"],template=prompt_templates["default"] # Use the default prompt)# Initialize the agentagent = initialize_agent(tools,llm, # Make sure llm is passed hereagent="zero-shot-react-description",verbose=True,prompt=prompt_template)def chat_with_agent(user_input, history):# ... (rest of the function)try:bot_response = agent(user_input) # Use agent(user_input) or agent.invoke(user_input)except Exception as e:bot_response = f"Sorry, an error occurred: {e}"history.append({"role": "user", "content": user_input})history.append({"role": "assistant", "content": bot_response})return history# Create Gradio Chat UIwith gr.Blocks() as demo:gr.Markdown("### Welcome to MotivationAgent! 🌟\nType a message to receive a motivational quote or an uplifting response.")chatbot = gr.Chatbot(label="MotivationAgent", type="messages")user_input = gr.Textbox(placeholder="Ask me for motivation... (e.g., 'I need inspiration')")submit_btn = gr.Button("Send")submit_btn.click(chat_with_agent, inputs=[user_input, chatbot], outputs=chatbot)demo.launch()1234567891011121314151617181920212223242 unmodified lines27282930313233343536371 unmodified line39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import osimport yamlimport gradio as grfrom langchain.agents import Toolfrom langchain.prompts import PromptTemplatefrom langchain_huggingface import HuggingFaceEndpointimport json # For parsing JSON responses (if needed)# Load environment variablesHF_API_KEY = os.environ.get("HUGGINGFACEHUB_API_TOKEN")HF_MODEL_ID = os.environ.get("HF_MODEL_ID", "google/flan-t5-xxl")# Load prompt templateswith open("prompts.yaml", 'r') as stream:all_prompts = yaml.safe_load(stream)prompt_templates = all_prompts["prompts"]# Define tools (example)def get_motivational_quote():quotes = [# ... (your quotes)]import randomreturn random.choice(quotes)2 unmodified linesTool(name="MotivationalQuote",func=get_motivational_quote,description="Use this tool to get a motivational quote. It takes no input.",)]# Initialize LLMllm = HuggingFaceEndpoint(repo_id=HF_MODEL_ID,temperature=0.7,1 unmodified linehuggingfacehub_api_token=HF_API_KEY,)# Create Prompt Templatessystem_prompt = PromptTemplate(template=prompt_templates["system_prompt"], input_variables=["tools"])planning_prompt = PromptTemplate(template=prompt_templates["planning"]["initial_plan"], input_variables=["task", "tools", "answer_facts"])# ... (create PromptTemplates for other prompts as needed)default_prompt = PromptTemplate(template=prompt_templates["default"], input_variables=["user_input"])# Agent Logic (Custom Loop - This needs significant implementation)def agent_loop(user_input):facts = "" # Initialize factsplan = planning_prompt.format(task=user_input, tools=tools, answer_facts=facts)print("Initial Plan:", plan)# Example (Very simplified - you MUST expand this)llm_response = llm(system_prompt.format(tools=tools) + plan) # Call LLM with system and plan promptsprint("LLM Response:", llm_response)# *** PARSE LLM RESPONSE ***# This is where you need to extract the next action (tool call or direct answer)# from the LLM's response. You'll likely need a specific format in the LLM's output.# Example (assuming the LLM outputs JSON):try:response_json = json.loads(llm_response) # This will only work if the LLM response is valid JSONaction = response_json.get("action")action_input = response_json.get("action_input")if action == "MotivationalQuote":quote = get_motivational_quote()return quote# ... handle other actions (tool calls or direct answers)elif action == "final_answer":return action_inputelse:return "I don't know how to do that yet."except json.JSONDecodeError:return "Invalid LLM Response. I don't know how to do that yet."# *** UPDATE FACTS AND PLAN ***# After each action, update the facts and create a new plan if needed.# This will depend on the LLM's response and the results of tool calls.# ...# Example (replace with your actual logic)return "Agent response (replace with actual agent output)"def chat_with_agent(user_input, history):if not user_input.strip():return history + [{"role": "assistant", "content": "Please enter a message to start the conversation!"}]bot_response = agent_loop(user_input)history.append({"role": "user", "content": user_input})history.append({"role": "assistant", "content": bot_response})return history# Gradio UIwith gr.Blocks() as demo:# ... (Gradio UI code as before)demo.launch()
app.py+57-48