Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531import streamlit as stimport osimport anthropicfrom langraph.graph import Graph, StateGraphfrom langraph.prelude import Containerfrom langraph.checkpoint import persistfrom langchain_anthropic import ChatAnthropicimport jsonfrom typing import Dict, List, Optional, Any, TypedDictimport timeimport pandas as pd
# Set page configurationst.set_page_config( page_title="Thinking Agent System", page_icon="🧠", layout="wide", initial_sidebar_state="expanded")
# Session state initializationif "messages" not in st.session_state: st.session_state.messages = []if "thinking_logs" not in st.session_state: st.session_state.thinking_logs = []if "agent_graph" not in st.session_state: st.session_state.agent_graph = Noneif "current_step" not in st.session_state: st.session_state.current_step = 0if "persona_configs" not in st.session_state: st.session_state.persona_configs = { "researcher": { "name": "Researcher", "description": "A careful researcher who examines all angles of a problem", "system_prompt": """You are a thoughtful researcher who carefully analyzes questions or problems.Your role is to break down complex questions, consider different approaches, identify assumptions, and provide comprehensive analysis. Consider multiple perspectives and potential weaknesses in different lines of reasoning.Your goal is to explore the problem space thoroughly before jumping to conclusions.""" }, "critic": { "name": "Critic", "description": "Identifies potential issues and challenges with approaches", "system_prompt": """You are a thoughtful critic who examines potential flaws or weaknesses in reasoning.Your role is to find potential issues with an approach, identify hidden assumptions, and suggest alternative ways of looking at problems.You're not negative, but constructively critical - your goal is to strengthen the analysis.""" }, "synthesizer": { "name": "Synthesizer", "description": "Pulls together insights into a cohesive response", "system_prompt": """You are a thoughtful synthesizer who pulls together different insights into a coherent whole.Your role is to examine the components of analysis that have been done, identify the key themes and insights,and create a unified response that incorporates the most important elements.You should balance detail with clarity, ensuring the final response is both comprehensive and accessible.""" }, "meta_agent": { "name": "Meta Agent", "description": "Coordinates the thinking process across agents", "system_prompt": """You are the coordinator of a multi-agent thinking system. Your job is to:1. Understand the user's question2. Decide which thinking agents need to be engaged and in what order3. Pass information between agents as needed4. Determine when sufficient analysis has been done to provide a response5. Ensure the process is both thorough and efficient
You have these agents at your disposal:- Researcher: Breaks down problems and explores them thoroughly- Critic: Examines potential flaws in reasoning and suggests alternatives- Synthesizer: Pulls together insights into a cohesive response
Think carefully about how to best deploy these agents for each query.""" } }
# Function to create and configure the Claude clientdef get_claude_client(): api_key = os.environ.get("ANTHROPIC_API_KEY", st.session_state.get("anthropic_api_key", "")) if not api_key: st.error("Please set your Anthropic API key in the settings.") return None return anthropic.Anthropic(api_key=api_key)
# Function to create a LangChain ChatAnthropic instancedef get_langchain_claude(): api_key = os.environ.get("ANTHROPIC_API_KEY", st.session_state.get("anthropic_api_key", "")) if not api_key: st.error("Please set your Anthropic API key in the settings.") return None return ChatAnthropic( model="claude-3-7-sonnet-20250219", temperature=0.1, anthropic_api_key=api_key )
# Load or create agent graphdef create_agent_graph(): # Create a typed dict for agent state class AgentState(TypedDict): query: str thoughts: Dict[str, List[str]] current_agent: str final_response: Optional[str] history: List[Dict[str, Any]] # Initialize the graph graph = StateGraph(AgentState) # Define the nodes (agents) @graph.node def initialize(state: AgentState) -> AgentState: return { **state, "thoughts": {"meta_agent": [], "researcher": [], "critic": [], "synthesizer": []}, "current_agent": "meta_agent", "history": [] } @graph.node def meta_agent(state: AgentState) -> AgentState: client = get_claude_client() if not client: return state system_prompt = st.session_state.persona_configs["meta_agent"]["system_prompt"] # Construct the message based on history and current query history_text = "" if state.get("history"): for entry in state["history"]: if entry.get("agent") and entry.get("thought"): history_text += f"\n## {entry['agent']} thought:\n{entry['thought']}\n" message = client.messages.create( model="claude-3-7-sonnet-20250219", system=system_prompt, messages=[ { "role": "user", "content": f"User query: {state['query']}\n\n" f"Current thinking process:\n{history_text}\n\n" f"What should be the next step in the thinking process? Which agent should handle it next, " f"and what specific aspect should they focus on? Or is the analysis sufficient to generate a final response?" } ], temperature=0.1, max_tokens=1000 ) thought = message.content[0].text # Update the state updated_thoughts = state["thoughts"].copy() updated_thoughts["meta_agent"] = updated_thoughts.get("meta_agent", []) + [thought] # Determine the next agent from the meta agent's response next_agent = "meta_agent" # Default to meta_agent if "researcher should" in thought.lower() or "have the researcher" in thought.lower(): next_agent = "researcher" elif "critic should" in thought.lower() or "have the critic" in thought.lower(): next_agent = "critic" elif "synthesizer should" in thought.lower() or "have the synthesizer" in thought.lower(): next_agent = "synthesizer" elif "final response" in thought.lower() or "sufficient analysis" in thought.lower(): next_agent = "final" updated_history = state.get("history", []).copy() + [{"agent": "Meta Agent", "thought": thought}] return { **state, "thoughts": updated_thoughts, "current_agent": next_agent, "history": updated_history } @graph.node def researcher(state: AgentState) -> AgentState: client = get_claude_client() if not client: return state system_prompt = st.session_state.persona_configs["researcher"]["system_prompt"] # Construct the message based on history and current query history_text = "" if state.get("history"): for entry in state["history"]: if entry.get("agent") and entry.get("thought"): history_text += f"\n## {entry['agent']} thought:\n{entry['thought']}\n" message = client.messages.create( model="claude-3-7-sonnet-20250219", system=system_prompt, messages=[ { "role": "user", "content": f"User query: {state['query']}\n\n" f"Current thinking process:\n{history_text}\n\n" f"Please provide your analysis as the Researcher agent." } ], temperature=0.1, max_tokens=1500 ) thought = message.content[0].text # Update the state updated_thoughts = state["thoughts"].copy() updated_thoughts["researcher"] = updated_thoughts.get("researcher", []) + [thought] updated_history = state.get("history", []).copy() + [{"agent": "Researcher", "thought": thought}] return { **state, "thoughts": updated_thoughts, "current_agent": "meta_agent", # Return to meta agent for next direction "history": updated_history } @graph.node def critic(state: AgentState) -> AgentState: client = get_claude_client() if not client: return state system_prompt = st.session_state.persona_configs["critic"]["system_prompt"] # Construct the message based on history and current query history_text = "" if state.get("history"): for entry in state["history"]: if entry.get("agent") and entry.get("thought"): history_text += f"\n## {entry['agent']} thought:\n{entry['thought']}\n" message = client.messages.create( model="claude-3-7-sonnet-20250219", system=system_prompt, messages=[ { "role": "user", "content": f"User query: {state['query']}\n\n" f"Current thinking process:\n{history_text}\n\n" f"Please provide your critical analysis as the Critic agent." } ], temperature=0.1, max_tokens=1500 ) thought = message.content[0].text # Update the state updated_thoughts = state["thoughts"].copy() updated_thoughts["critic"] = updated_thoughts.get("critic", []) + [thought] updated_history = state.get("history", []).copy() + [{"agent": "Critic", "thought": thought}] return { **state, "thoughts": updated_thoughts, "current_agent": "meta_agent", # Return to meta agent for next direction "history": updated_history } @graph.node def synthesizer(state: AgentState) -> AgentState: client = get_claude_client() if not client: return state system_prompt = st.session_state.persona_configs["synthesizer"]["system_prompt"] # Construct the message based on history and current query history_text = "" if state.get("history"): for entry in state["history"]: if entry.get("agent") and entry.get("thought"): history_text += f"\n## {entry['agent']} thought:\n{entry['thought']}\n" message = client.messages.create( model="claude-3-7-sonnet-20250219", system=system_prompt, messages=[ { "role": "user", "content": f"User query: {state['query']}\n\n" f"Current thinking process:\n{history_text}\n\n" f"Please synthesize the insights and provide a cohesive analysis as the Synthesizer agent." } ], temperature=0.1, max_tokens=1500 ) thought = message.content[0].text # Update the state updated_thoughts = state["thoughts"].copy() updated_thoughts["synthesizer"] = updated_thoughts.get("synthesizer", []) + [thought] updated_history = state.get("history", []).copy() + [{"agent": "Synthesizer", "thought": thought}] return { **state, "thoughts": updated_thoughts, "current_agent": "meta_agent", # Return to meta agent for next direction "history": updated_history } @graph.node def finalize(state: AgentState) -> AgentState: client = get_claude_client() if not client: return state # Construct the message based on history and current query history_text = "" if state.get("history"): for entry in state["history"]: if entry.get("agent") and entry.get("thought"): history_text += f"\n## {entry['agent']} thought:\n{entry['thought']}\n" message = client.messages.create( model="claude-3-7-sonnet-20250219", system="You are a thoughtful AI assistant that provides well-reasoned, comprehensive responses.", messages=[ { "role": "user", "content": f"User query: {state['query']}\n\n" f"Here is the complete thinking process that went into answering this query:\n{history_text}\n\n" f"Based on all of this thinking, provide a final, comprehensive response to the user's query." } ], temperature=0.1, max_tokens=2000 ) final_response = message.content[0].text return { **state, "final_response": final_response, "current_agent": "done" } # Define the edges graph.add_edge("initialize", "meta_agent") graph.add_conditional_edges( "meta_agent", lambda state: state["current_agent"], { "researcher": "researcher", "critic": "critic", "synthesizer": "synthesizer", "final": "finalize", "meta_agent": "meta_agent" # For cases where meta agent needs another step } ) graph.add_edge("researcher", "meta_agent") graph.add_edge("critic", "meta_agent") graph.add_edge("synthesizer", "meta_agent") # Compile the graph compiled_graph = graph.compile() return compiled_graph
# Function to run the agent graphdef run_agent_graph(query): if not st.session_state.agent_graph: st.session_state.agent_graph = create_agent_graph() # Reset the current step counter st.session_state.current_step = 0 # Clear previous thinking logs st.session_state.thinking_logs = [] # Start with initial state initial_state = {"query": query} # Execute the graph with checkpointing # We'll use the checkpoint functionality to track each step @persist(to="memory") def run_with_checkpoints(graph, initial_state): return graph.run(initial_state) result = run_with_checkpoints(st.session_state.agent_graph, initial_state) # Process the result for display if result and "history" in result: for step in result["history"]: st.session_state.thinking_logs.append(step) # Return the final response if result and "final_response" in result: return result["final_response"] else: return "I wasn't able to generate a response. Please try again or check the settings."
# UI Layoutst.sidebar.title("🧠 Thinking Agent System")
# Tabs for different viewstabs = st.tabs(["Chat", "Thinking Process", "Agent Configuration"])
with tabs[0]: # Chat tab st.header("Chat with the Thinking Agent") # Display chat messages for message in st.session_state.messages: with st.chat_message(message["role"]): st.write(message["content"]) # User input if prompt := st.chat_input("What's on your mind?"): # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) # Display user message with st.chat_message("user"): st.write(prompt) # Show thinking indicator with st.chat_message("assistant"): with st.spinner("Thinking..."): response = run_agent_graph(prompt) # Display the response st.write(response) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response})
with tabs[1]: # Thinking Process tab st.header("Agent Thinking Process") if not st.session_state.thinking_logs: st.info("No thinking process to display yet. Start a conversation to see the agents at work.") else: for i, log in enumerate(st.session_state.thinking_logs): step_num = i + 1 with st.expander(f"Step {step_num}: {log.get('agent', 'Unknown Agent')}", expanded=True): st.markdown(log.get("thought", "No thought recorded"))
with tabs[2]: # Agent Configuration tab st.header("Configure Agent Personas") # Select agent to configure selected_agent = st.selectbox( "Select agent to configure:", options=list(st.session_state.persona_configs.keys()), format_func=lambda x: st.session_state.persona_configs[x]["name"] ) # Edit the selected agent if selected_agent: with st.form(f"edit_{selected_agent}"): st.subheader(f"Edit {st.session_state.persona_configs[selected_agent]['name']}") name = st.text_input( "Agent Name", value=st.session_state.persona_configs[selected_agent]["name"] ) description = st.text_area( "Description", value=st.session_state.persona_configs[selected_agent]["description"], height=100 ) system_prompt = st.text_area( "System Prompt", value=st.session_state.persona_configs[selected_agent]["system_prompt"], height=300 ) if st.form_submit_button("Save Changes"): st.session_state.persona_configs[selected_agent]["name"] = name st.session_state.persona_configs[selected_agent]["description"] = description st.session_state.persona_configs[selected_agent]["system_prompt"] = system_prompt # Recreate the agent graph with updated configs st.session_state.agent_graph = create_agent_graph() st.success(f"Updated {name} configuration successfully!")
# Settings in the sidebarwith st.sidebar.expander("⚙️ Settings"): api_key = st.text_input( "Anthropic API Key", type="password", value=st.session_state.get("anthropic_api_key", ""), help="Enter your Anthropic API key here" ) if api_key: st.session_state.anthropic_api_key = api_key if st.button("Test Connection"): client = get_claude_client() if client: try: response = client.messages.create( model="claude-3-7-sonnet-20250219", messages=[{"role": "user", "content": "Hello"}], max_tokens=10 ) st.success("Connection successful!") except Exception as e: st.error(f"Connection failed: {str(e)}")
# Display some information about the appwith st.sidebar.expander("ℹ️ About"): st.markdown(""" This app demonstrates a multi-agent thinking system powered by Claude 3.7. The system uses multiple specialized agents with different perspectives to analyze problems: - **Meta Agent**: Coordinates the thinking process - **Researcher**: Explores the problem space thoroughly - **Critic**: Identifies flaws in reasoning - **Synthesizer**: Combines insights into a coherent response You can observe the thinking process in the "Thinking Process" tab and configure the agents in the "Agent Configuration" tab. """)
# Create the agent graph on app startup if it doesn't existif not st.session_state.agent_graph: st.session_state.agent_graph = create_agent_graph()app.pyAdded+531