DrishtiSharma commited on
Commit
03bda09
Β·
verified Β·
1 Parent(s): 6b1ac2e

Update interim.py

Browse files
Files changed (1) hide show
  1. interim.py +30 -41
interim.py CHANGED
@@ -1,6 +1,6 @@
1
  import streamlit as st
2
  from typing import TypedDict, Annotated
3
- from langgraph.graph import StateGraph, START, END
4
  from langgraph.checkpoint.memory import MemorySaver
5
  from langgraph.graph.message import add_messages
6
  from langchain_openai import ChatOpenAI
@@ -28,32 +28,25 @@ if openai_api_key and tavily_api_key:
28
  # Initialize LLM and Tools
29
  llm = ChatOpenAI(model="gpt-4o-mini")
30
  tool = TavilySearchResults(max_results=2)
31
- tools = [tool]
32
- llm_with_tools = llm.bind_tools(tools)
33
 
34
  # Agent Function
35
  def Agent(state: State):
36
- print("Agent received state:", state)
37
- # Force tool invocation
38
  response = llm_with_tools.invoke(state["messages"])
39
- print("Agent Response:", response)
40
  return {"messages": [response]}
41
 
42
  # Memory Checkpoint
43
  memory = MemorySaver()
44
 
45
- # Graph Definition
46
  graph = StateGraph(State)
47
  tool_node = ToolNode(tools=[tool])
48
 
49
  graph.add_node("Agent", Agent)
50
  graph.add_node("tools", tool_node)
51
-
52
- # Corrected Conditional Edge
53
- def always_true(state):
54
- return "True" # Return string "True"
55
-
56
- graph.add_conditional_edges("Agent", always_true, {"True": "tools"})
57
  graph.add_edge("tools", "Agent")
58
  graph.set_entry_point("Agent")
59
 
@@ -71,46 +64,42 @@ if openai_api_key and tavily_api_key:
71
 
72
  if st.button("Execute Workflow"):
73
  thread = {"configurable": {"thread_id": thread_id}}
74
- input_message = {'messages': HumanMessage(content=user_input)}
75
 
76
  st.write("### Execution Outputs")
77
  outputs = []
78
  for event in app.stream(input_message, thread, stream_mode="values"):
79
- if "messages" in event and event["messages"]:
80
- latest_message = event["messages"][-1].pretty_print()
81
- outputs.append(latest_message)
82
- st.code(latest_message)
83
 
84
  if outputs:
85
  st.subheader("Intermediate Outputs")
86
- for i, output in enumerate(outputs, 1):
87
- st.write(f"**Step {i}:**")
88
  st.code(output)
89
  else:
90
  st.warning("No outputs generated. Adjust your input to trigger tools.")
91
 
92
- # Snapshot of Current State
93
  st.subheader("Current State Snapshot")
94
  snapshot = app.get_state(thread)
95
- if snapshot.values["messages"]:
96
- current_message = snapshot.values["messages"][-1]
97
- st.code(current_message.pretty_print())
98
-
99
- # Safe Access to Tool Calls
100
- if hasattr(current_message, "tool_calls") and current_message.tool_calls:
101
- tool_call_id = current_message.tool_calls[0]["id"]
102
- manual_response = st.text_area("Manual Tool Response", "Enter response to continue...")
103
- if st.button("Update State"):
104
- new_messages = [
105
- ToolMessage(content=manual_response, tool_call_id=tool_call_id),
106
- AIMessage(content=manual_response),
107
- ]
108
- app.update_state(thread, {"messages": new_messages})
109
- st.success("State updated successfully!")
110
- st.code(app.get_state(thread).values["messages"][-1].pretty_print())
111
- else:
112
- st.warning("No tool calls available for manual updates.")
113
  else:
114
- st.warning("No state messages available.")
115
  else:
116
- st.error("API keys are missing! Please set `OPENAI_API_KEY` and `TAVILY_API_KEY` in Hugging Face Spaces Secrets.")
 
1
  import streamlit as st
2
  from typing import TypedDict, Annotated
3
+ from langgraph.graph import StateGraph
4
  from langgraph.checkpoint.memory import MemorySaver
5
  from langgraph.graph.message import add_messages
6
  from langchain_openai import ChatOpenAI
 
28
  # Initialize LLM and Tools
29
  llm = ChatOpenAI(model="gpt-4o-mini")
30
  tool = TavilySearchResults(max_results=2)
31
+ llm_with_tools = llm.bind_tools([tool])
 
32
 
33
  # Agent Function
34
  def Agent(state: State):
35
+ st.sidebar.write("Agent received state:", state["messages"])
 
36
  response = llm_with_tools.invoke(state["messages"])
37
+ st.sidebar.write("Agent Response:", response)
38
  return {"messages": [response]}
39
 
40
  # Memory Checkpoint
41
  memory = MemorySaver()
42
 
43
+ # Build the Graph
44
  graph = StateGraph(State)
45
  tool_node = ToolNode(tools=[tool])
46
 
47
  graph.add_node("Agent", Agent)
48
  graph.add_node("tools", tool_node)
49
+ graph.add_conditional_edges("Agent", tools_condition)
 
 
 
 
 
50
  graph.add_edge("tools", "Agent")
51
  graph.set_entry_point("Agent")
52
 
 
64
 
65
  if st.button("Execute Workflow"):
66
  thread = {"configurable": {"thread_id": thread_id}}
67
+ input_message = {"messages": [HumanMessage(content=user_input)]}
68
 
69
  st.write("### Execution Outputs")
70
  outputs = []
71
  for event in app.stream(input_message, thread, stream_mode="values"):
72
+ st.code(event["messages"][-1].content)
73
+ outputs.append(event["messages"][-1].content)
74
+ st.sidebar.write("Intermediate State:", event["messages"])
 
75
 
76
  if outputs:
77
  st.subheader("Intermediate Outputs")
78
+ for idx, output in enumerate(outputs, start=1):
79
+ st.write(f"**Step {idx}:**")
80
  st.code(output)
81
  else:
82
  st.warning("No outputs generated. Adjust your input to trigger tools.")
83
 
84
+ # Display Snapshot of State
85
  st.subheader("Current State Snapshot")
86
  snapshot = app.get_state(thread)
87
+ current_message = snapshot.values["messages"][-1]
88
+ st.code(current_message.pretty_print())
89
+
90
+ # Manual Update Section
91
+ if hasattr(current_message, "tool_calls") and current_message.tool_calls:
92
+ tool_call_id = current_message.tool_calls[0]["id"]
93
+ manual_response = st.text_area("Manual Tool Response", "Enter your response to continue execution...")
94
+ if st.button("Update State"):
95
+ new_messages = [
96
+ ToolMessage(content=manual_response, tool_call_id=tool_call_id),
97
+ AIMessage(content=manual_response),
98
+ ]
99
+ app.update_state(thread, {"messages": new_messages})
100
+ st.success("State updated successfully!")
101
+ st.code(app.get_state(thread).values["messages"][-1].pretty_print())
 
 
 
102
  else:
103
+ st.warning("No tool calls available for manual updates.")
104
  else:
105
+ st.error("API keys are missing! Please set `OPENAI_API_KEY` and `TAVILY_API_KEY` in Hugging Face Spaces Secrets.")