Spaces:
Sleeping
Sleeping
Update app.py
Browse files37 unmodified lines3839404142434445464711 unmodified lines596061626364653 unmodified lines697071727374754 unmodified lines80818283848586878889909192939495969798991001011021031041051061071081 unmodified line1101111121131141151161171181191201211221231241251 unmodified line12712812913013113213313413513613713813914014114214314414514614714837 unmodified lineselse: # Southern locationsreturn {"temperature": "30°C", "description": "Very Sunny"}# --- Modified Agent Function ---# Change return type hint for clarity if desired, e.g., AsyncGenerator[str, None]# Or keep it simple, Gradio infers based on yieldsasync def stream_from_agent(message: str, history: List[List[str]]) -> AsyncGenerator[str, None]:"""Processes message through LangChain agent, yielding intermediate steps as strings."""# Convert Gradio history to LangChain messages11 unmodified lineslc_messages.append(HumanMessage(content=message))# Initialize the agent (consider initializing outside the function if stateful across calls)llm = ChatOpenAI(temperature=0, model="gpt-4")memory = MemorySaver() # Be mindful of memory state if agent is re-initialized every timetools = [get_lat_lng, get_weather]3 unmodified lines# Using a fixed one like "abc123" means all users share the same memory if server restarts aren't frequentthread_id = "user_session_" + str(os.urandom(4).hex()) # Example: generate unique IDfull_response = "" # Accumulate the response partsasync for chunk in agent_executor.astream_events({"messages": lc_messages},4 unmodified linesdata = chunk["data"]if event == "on_chat_model_stream":# Stream content from the LLM (final answer parts)content = data["chunk"].contentif content:full_response += contentyield full_response # Yield the accumulating final responseelif event == "on_tool_start":# Show tool usage starttool_input_str = str(data.get('input', '')) # Get tool input safelyyield f"🛠️ Using tool: **{data['name']}** with input: `{tool_input_str}`"elif event == "on_tool_end":# Show tool result (optional, can make chat verbose)tool_output_str = str(data.get('output', '')) # Get tool output safely# Find the corresponding start message to potentially update, or just yield new message# For simplicity, just yield the result as a new message lineyield f"Tool **{data['name']}** finished.\nResult: `{tool_output_str}`"# Yield the accumulated response again after tool use in case LLM continuesif full_response:yield full_response# Ensure the final accumulated response is yielded if not already done by the last LLM chunk# (stream might end on tool end sometimes)if full_response and (not chunk or chunk["event"] != "on_chat_model_stream"):yield full_response1 unmodified line# --- Gradio Interface (mostly unchanged) ---demo = gr.ChatInterface(fn=stream_from_agent,# No type="messages" needed when yielding strings; ChatInterface handles it.title="🌤️ Weather Assistant",description="Ask about the weather anywhere! Watch as I gather the information step by step.",examples=[["What's the weather like in Tokyo?"],["Is it sunny in Paris right now?"],["Should I bring an umbrella in New York today?"]],# Example icons removed for simplicity, ensure they are accessible if added backcache_examples=False, # Turn off caching initially to ensure it's not the issuesave_history=True,editable=True,)1 unmodified lineif __name__ == "__main__":# Load environment variablestry:from dotenv import load_dotenvprint("Attempting to load .env file...")loaded = load_dotenv()if loaded:print(".env file loaded successfully.")else:print(".env file not found or empty.")# Check if the key is loadedopenai_api_key = os.getenv("OPENAI_API_KEY")if openai_api_key:print("OPENAI_API_KEY found.")else:print("Warning: OPENAI_API_KEY not found in environment variables.")except ImportError:print("dotenv not installed, skipping .env load.")pass# Add server_name="0.0.0.0" if running in Docker or need external accessdemo.launch(debug=True, server_name="0.0.0.0")37 unmodified lines383940414243444511 unmodified lines5758596061623 unmodified lines666768697071724 unmodified lines7778798081828384858687888990919293949596971 unmodified line991001011021031041051061071081 unmodified line11011111211311411511611711837 unmodified lineselse: # Southern locationsreturn {"temperature": "30°C", "description": "Very Sunny"}async def Answer_from_agent(message: str, history: List[List[str]]) -> AsyncGenerator[str, None]:"""Processes message through LangChain agent, yielding intermediate steps as strings."""# Convert Gradio history to LangChain messages11 unmodified lineslc_messages.append(HumanMessage(content=message))llm = ChatOpenAI(temperature=0, model="gpt-4")memory = MemorySaver() # Be mindful of memory state if agent is re-initialized every timetools = [get_lat_lng, get_weather]3 unmodified lines# Using a fixed one like "abc123" means all users share the same memory if server restarts aren't frequentthread_id = "user_session_" + str(os.urandom(4).hex()) # Example: generate unique IDfull_response = ""async for chunk in agent_executor.astream_events({"messages": lc_messages},4 unmodified linesdata = chunk["data"]if event == "on_chat_model_stream":content = data["chunk"].contentif content:full_response += contentyield full_responseelif event == "on_tool_start":tool_input_str = str(data.get('input', ''))yield f"🛠️ Using tool: **{data['name']}** with input: `{tool_input_str}`"elif event == "on_tool_end":tool_output_str = str(data.get('output', ''))yield f"Tool **{data['name']}** finished.\nResult: `{tool_output_str}`"if full_response:yield full_responseif full_response and (not chunk or chunk["event"] != "on_chat_model_stream"):yield full_response1 unmodified line# --- Gradio Interface (mostly unchanged) ---demo = gr.ChatInterface(fn=stream_from_agent,type="messages",title="🤖 AGent template",description="Ask about the weather anywhere! Watch as I gather the information step by step.",cache_examples=False,save_history=True,editable=True,)1 unmodified lineif __name__ == "__main__":# Load environment variablestry:openai_api_key = os.getenv("OPENAI_API_KEY")if openai_api_key:print("OPENAI_API_KEY found.")else:print("Warning: OPENAI_API_KEY not found in environment variables.")demo.launch(debug=True, server_name="0.0.0.0")
app.py+9-39