Skip to content

armgit / burr

Public Imported from GitHub
0

Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.

Uber commit to make rebasing simpler:

elijahbenizzya6389c07bedf
diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml
index cc55cd08..106c2bc8 100644
--- a/.github/workflows/python-package.yml
+++ b/.github/workflows/python-package.yml
@@ -23,17 +23,17 @@ jobs:
strategy:
fail-fast: false
matrix:
- python-version: ["3.9", "3.10", "3.11", "3.12"]
+ python-version: ['3.9', '3.10', '3.11', '3.12']
steps:
- - uses: actions/checkout@v3
- - name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v3
- with:
- python-version: ${{ matrix.python-version }}
- - name: Install dependencies
- run: |
- python -m pip install -e ".[tests,tracking-client]"
- - name: Run tests
- run: |
- python -m pytest tests
+ - uses: actions/checkout@v3
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v3
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install dependencies
+ run: |
+ python -m pip install -e ".[tests,tracking-client]"
+ - name: Run tests
+ run: |
+ python -m pytest tests
diff --git a/burr/tracking/common/models.py b/burr/tracking/common/models.py
index ec847786..c3438632 100644
--- a/burr/tracking/common/models.py
+++ b/burr/tracking/common/models.py
@@ -1,6 +1,8 @@
import datetime
import inspect
-from typing import Any, Dict, Optional
+from typing import Any, Dict, Optional, Union
+
+from pydantic import field_serializer
from burr.core import Action
from burr.core.action import FunctionBasedAction
@@ -93,6 +95,19 @@ class BeginEntryModel(IdentifyingModel):
type: str = "begin_entry"
+def _serialize_object(d: object) -> Union[dict, list, object]:
+ if isinstance(d, list):
+ return [_serialize_object(x) for x in d]
+ elif isinstance(d, dict):
+ return {k: _serialize_object(v) for k, v in d.items()}
+ elif hasattr(d, "model_dump"):
+ return d.model_dump()
+ elif hasattr(d, "to_json"):
+ return d.to_json()
+ else:
+ return d
+
+
class EndEntryModel(IdentifyingModel):
"""Pydantic model that represents an entry for the end of a step"""
@@ -102,3 +117,11 @@ class EndEntryModel(IdentifyingModel):
exception: Optional[str]
state: Dict[str, Any] # TODO -- consider logging updates to the state so we can recreate
type: str = "end_entry"
+
+ @field_serializer("result")
+ def serialize_result(self, result):
+ return _serialize_object(result)
+
+ @field_serializer("state")
+ def serialize_state(self, state):
+ return _serialize_object(state)
diff --git a/burr/tracking/server/run.sh b/burr/tracking/server/run.sh
new file mode 100644
index 00000000..9b99fe44
--- /dev/null
+++ b/burr/tracking/server/run.sh
@@ -0,0 +1 @@
+uvicorn run:app --host 0.0.0.0 --port 7241
diff --git a/examples/counter/application.py b/examples/counter/application.py
index fbbdbe4b..e41f4aab 100644
--- a/examples/counter/application.py
+++ b/examples/counter/application.py
@@ -12,7 +12,7 @@ def counter(state: State) -> Tuple[dict, State]:
return result, state.update(**result)
-def application(count_up_to: int = 10, log_file: str = None):
+def application(count_up_to: int = 100, log_file: str = None):
return (
burr.core.ApplicationBuilder()
.with_state(counter=0)
@@ -33,5 +33,5 @@ if __name__ == "__main__":
app = application(log_file="counter.jsonl")
action, state, result = app.run(halt_after=["result"])
app.visualize(output_file_path="digraph", include_conditions=True, view=False, format="png")
- assert state["counter"] == 10
+ assert state["counter"] == 100
print(state["counter"])
diff --git a/examples/gpt/README.md b/examples/gpt/README.md
index 1bb68acf..27da5bcf 100644
--- a/examples/gpt/README.md
+++ b/examples/gpt/README.md
@@ -19,7 +19,6 @@ The state machine this encapsulates takes the following form:
![State Machine](digraph.png)
-
Note that it is currently wired up to handle errors in the state machine, but the actions do not respect that yet. Coming soon.
We have three files:
@@ -28,7 +27,6 @@ We have three files:
- [requirements.txt](requirements.txt) -- Just the requirements. All this needs is Burr/Streamlit/openai
- [streamlit_app.py](streamlit_app.py) -- This contains a simple Streamlit app to interact with the cow
-
You must have your `OPENAI_API_KEY` set in your environment. You can do this by running.
To run on streamlit, you can launch the app:
diff --git a/examples/gpt/streamlit_app.py b/examples/gpt/streamlit_app.py
index ed114678..4185a0c0 100644
--- a/examples/gpt/streamlit_app.py
+++ b/examples/gpt/streamlit_app.py
@@ -42,7 +42,9 @@ def retrieve_state():
# TODO --enable usage of hamilton. Currently its not wiring in inputs
# But it should be easy enough
state = AppState.from_empty(
- app=chatbot_application.application(use_hamilton=False),
+ app=chatbot_application.application(
+ use_hamilton=False,
+ ),
)
else:
state = get_state()
diff --git a/examples/multi-agent-collaboration/application.py b/examples/multi-agent-collaboration/application.py
new file mode 100644
index 00000000..ec01b9c1
--- /dev/null
+++ b/examples/multi-agent-collaboration/application.py
@@ -0,0 +1,207 @@
+import func_agent
+from langchain_community.tools.tavily_search import TavilySearchResults
+from langchain_experimental.utilities import PythonREPL
+
+from burr import core
+from burr.core import Action, ApplicationBuilder, State
+from burr.core.action import action
+from burr.lifecycle import PostRunStepHook
+from hamilton import driver
+
+# @action(reads=["code"], writes=["code_result"])
+# def run_code(state: State) -> tuple[dict, State]:
+# _code = state["code"]
+# try:
+# result = repl.run(_code)
+# except BaseException as e:
+# _code_result = {"status": "error", "result": f"Failed to execute. Error: {repr(e)}"
+# return {"result": f"Failed to execute. Error: {repr(e)}"}, state.update(code_result=_code_result)
+# _code_result = {"status": "success", "result": result}
+# return {"status": "success", "result": result}, state.update(code_result=_code_result)
+#
+# @action(reads=["code"], writes=["code_result"])
+# def run_tavily(state: State) -> tuple[dict, State]:
+# _code = state["code"]
+# try:
+# result = repl.run(_code)
+# except BaseException as e:
+# _code_result = {"status": "error", "result": f"Failed to execute. Error: {repr(e)}"
+# return {"result": f"Failed to execute. Error: {repr(e)}"}, state.update(code_result=_code_result)
+# _code_result = {"status": "success", "result": result}
+# return {"status": "success", "result": result}, state.update(code_result=_code_result)
+
+
+tool_dag = driver.Builder().with_modules(func_agent).build()
+
+repl = PythonREPL()
+
+
+def python_repl(code: str) -> dict:
+ """Use this to execute python code. If you want to see the output of a value,
+ you should print it out with `print(...)`. This is visible to the user.
+
+ :param code: string. The python code to execute.
+ :return: the output
+ """
+ try:
+ result = repl.run(code)
+ except BaseException as e:
+ return {"error": repr(e), "status": "error"}
+ return {"status": "success", "code": f"```python\n{code}\n```", "Stdout": result}
+
+
+@action(reads=["query", "messages"], writes=["messages", "next_hop"])
+def chart_generator(state: State) -> tuple[dict, State]:
+ query = state["query"]
+ result = tool_dag.execute(
+ ["executed_tool_calls", "parsed_tool_calls", "llm_function_message"],
+ inputs={
+ "tools": [python_repl],
+ "system_message": "Any charts you display will be visible by the user.",
+ "user_query": query,
+ "messages": state["messages"],
+ },
+ )
+ # _code = result["parsed_tool_calls"][0]["function_args"]["code"]
+ new_messages = [result["llm_function_message"]]
+ for tool_name, tool_result in result["executed_tool_calls"]:
+ new_messages.append(tool_result)
+ if len(new_messages) == 1:
+ if new_messages[0]["content"] and "FINAL ANSWER" in new_messages[0]["content"]:
+ next_hop = "complete"
+ else:
+ next_hop = "continue"
+ else:
+ # assess tool results
+ next_hop = "self"
+ state = state.update(next_hop=next_hop)
+ for message in new_messages:
+ state = state.append(messages=message)
+ return result, state
+
+
+tavily_tool = TavilySearchResults(max_results=5)
+
+
+@action(reads=["query", "messages"], writes=["messages", "next_hop"])
+def researcher(state: State) -> tuple[dict, State]:
+ query = state["query"]
+ result = tool_dag.execute(
+ ["executed_tool_calls", "parsed_tool_calls", "llm_function_message"],
+ inputs={
+ "tools": [tavily_tool],
+ "system_message": "You should provide accurate data for the chart generator to use.",
+ "user_query": query,
+ "messages": state["messages"],
+ },
+ )
+ new_messages = [result["llm_function_message"]]
+ for tool_name, tool_result in result["executed_tool_calls"]:
+ new_messages.append(tool_result)
+ if len(new_messages) == 1:
+ if "FINAL ANSWER" in new_messages[0]["content"]:
+ next_hop = "complete"
+ else:
+ next_hop = "continue"
+ else:
+ # assess tool results
+ next_hop = "self"
+ state = state.update(next_hop=next_hop)
+ for message in new_messages:
+ state = state.append(messages=message)
+ return result, state
+
+
+@action(reads=[], writes=[])
+def terminal_step(state: State) -> tuple[dict, State]:
+ return {}, state
+
+
+class PrintStepHook(PostRunStepHook):
+ def post_run_step(self, *, state: "State", action: "Action", **future_kwargs):
+ print("action=====\n", action)
+ print("state======\n", state)
+
+
+def main():
+ app = (
+ ApplicationBuilder()
+ .with_state(
+ messages=[],
+ query="Fetch the UK's GDP over the past 5 years,"
+ " then draw a line graph of it."
+ " Once you code it up, finish.",
+ next_hop="",
+ )
+ .with_actions(
+ researcher=researcher,
+ chart_generator=chart_generator,
+ terminal=terminal_step,
+ )
+ .with_transitions(
+ ("researcher", "researcher", core.expr("next_hop == 'self'")),
+ ("researcher", "chart_generator", core.expr("next_hop == 'continue'")),
+ ("chart_generator", "chart_generator", core.expr("next_hop == 'self'")),
+ ("chart_generator", "researcher", core.expr("next_hop == 'continue'")),
+ (
+ "researcher",
+ "terminal",
+ core.expr("next_hop == 'complete'"),
+ ), # core.expr("'FINAL ANSWER' in messages[-1]['content']")),
+ (
+ "chart_generator",
+ "terminal",
+ core.expr("next_hop == 'complete'"),
+ ), # core.expr("'FINAL ANSWER' in messages[-1]['content']")),
+ )
+ .with_entrypoint("researcher")
+ .with_hooks(PrintStepHook())
+ .build()
+ )
+ app.run(until=["terminal"])
+ # return app
+
+
+if __name__ == "__main__":
+ main()
+ import sys
+
+ sys.exit(0)
+ """TODO:
+ 1. need to figure out the messages state.
+ 2. the current design is each DAG run also calls the tool.
+ 3. so need to then update messages history appropriately
+ so that the "agents" can iterate until they are done.
+
+ Note: https://github.com/langchain-ai/langgraph/blob/main/examples/multi_agent/multi-agent-collaboration.ipynb
+ Is a little messy to figure out. So best to approach from first
+ principles what is actually going on.
+
+ """
+ repl = PythonREPL()
+ tavily_tool = TavilySearchResults(max_results=5)
+ result = tool_dag.execute(
+ ["executed_tool_calls"],
+ inputs={
+ "tools": [tavily_tool],
+ "system_message": "You should provide accurate data for the chart generator to use.",
+ "user_query": "Fetch the UK's GDP over the past 5 years,"
+ " then draw a line graph of it."
+ " Once you code it up, finish.",
+ },
+ )
+ import pprint
+
+ pprint.pprint(result)
+
+ result = tool_dag.execute(
+ ["executed_tool_calls"],
+ inputs={
+ "tools": [python_repl],
+ "system_message": "Any charts you display will be visible by the user.",
+ "user_query": "Draw a simple line graph of y = x",
+ },
+ )
+ import pprint
+
+ pprint.pprint(result)
diff --git a/examples/multi-agent-collaboration/func_agent.py b/examples/multi-agent-collaboration/func_agent.py
new file mode 100644
index 00000000..eb033f99
--- /dev/null
+++ b/examples/multi-agent-collaboration/func_agent.py
@@ -0,0 +1,256 @@
+import inspect
+import json
+from typing import Callable
+
+import openai
+from langchain_core.utils.function_calling import convert_to_openai_function
+
+
+def llm_client() -> openai.OpenAI:
+ return openai.OpenAI()
+
+
+def tool_names(tool_function_specs: list[dict]) -> list[str]:
+ return [tool["function"]["name"] for tool in tool_function_specs]
+
+
+def _langchain_tool_spec(tool: Callable) -> dict:
+ t = convert_to_openai_function(tool)
+ # print(t)
+ return t
+
+
+def _tool_function_spec(tool: Callable) -> dict:
+ # TODO: maybe just get people to wrap any external tool in a function
+ # to make it clear WTF is going on.
+ if hasattr(tool, "name") and hasattr(tool, "description") and hasattr(tool, "args_schema"):
+ return {"type": "function", "function": _langchain_tool_spec(tool)}
+ func_sig = inspect.signature(tool)
+ name = tool.__name__
+ docstring = inspect.getdoc(tool)
+ doc_lines = docstring.split("\n") if docstring else []
+ description = ""
+ for line in doc_lines:
+ stripped = line.strip()
+ if stripped.startswith(":"):
+ # we have reached the end of the description
+ break
+ description += stripped + "\n"
+ description = description.strip()
+ param_descriptions = {}
+ for line in doc_lines:
+ stripped = line.strip()
+ if stripped.startswith(":param"):
+ parts = stripped.split(" ", 2)
+ param_name = parts[1].strip(":")
+ param_description = parts[2]
+ param_descriptions[param_name] = param_description
+ parameters = func_sig.parameters
+ func_parameters = {}
+ required = []
+ for param_name, param in parameters.items():
+ param_type = param.annotation
+ param_description = param_descriptions.get(param_name, "")
+ if param_type == str:
+ param_type = "string"
+ elif param_type == int:
+ param_type = "integer"
+ elif param_type == float:
+ param_type = "float"
+ else:
+ raise ValueError(f"Unsupported parameter type: {param_type}")
+ func_parameters[param_name] = {
+ "type": param_type,
+ "description": param_description,
+ }
+ if param.default == inspect.Parameter.empty:
+ required.append(param_name)
+ else:
+ func_parameters[param_name]["description"] += f" Defaults to {param.default}."
+
+ return {
+ "type": "function",
+ "function": {
+ "name": name,
+ "description": description,
+ "parameters": {
+ "type": "object",
+ "properties": func_parameters,
+ "required": required,
+ },
+ },
+ }
+
+
+def tool_function_specs(tools: list[Callable]) -> list[dict]:
+ return [_tool_function_spec(tool) for tool in tools]
+
+
+def base_system_prompt(tool_names: list[str], system_message: str) -> str:
+ return (
+ "You are a helpful AI assistant, collaborating with other assistants."
+ " Use the provided tools to progress towards answering the question."
+ " If you are unable to fully answer, that's OK, another assistant with different tools "
+ " will help where you left off. Execute what you can to make progress."
+ " If you or any of the other assistants have the final answer or deliverable,"
+ " prefix your response with FINAL ANSWER so the team knows to stop."
+ f" You have access to the following tools: {tool_names}.\n{system_message}"
+ )
+
+
+def get_current_weather(location: str, unit: str = "fahrenheit") -> str:
+ """Get the current weather in a given location
+
+ :param location: the location to get the weather for.
+ :param unit: the unit of temperature to return. Celsius or Fahrenheit.
+ :return: JSON string with the location and temperature, and unit.
+ """
+ if "tokyo" in location.lower():
+ return json.dumps({"location": "Tokyo", "temperature": "10", "unit": unit})
+ elif "san francisco" in location.lower():
+ return json.dumps({"location": "San Francisco", "temperature": "72", "unit": unit})
+ elif "paris" in location.lower():
+ return json.dumps({"location": "Paris", "temperature": "22", "unit": unit})
+ else:
+ return json.dumps({"location": location, "temperature": "unknown"})
+
+
+def message_history(base_system_prompt: str, user_query: str, messages: list[dict]) -> list[dict]:
+ base = [
+ {"role": "system", "content": base_system_prompt},
+ {"role": "user", "content": user_query},
+ ]
+ sanitized_messages = []
+ for message in messages:
+ message_copy = message.copy()
+ if not isinstance(message_copy["content"], str) and message_copy["content"] is not None:
+ message_copy["content"] = (
+ json.dumps(message_copy["content"]) if message_copy["content"] else None
+ )
+ sanitized_messages.append(message_copy)
+ return base + sanitized_messages
+
+
+def llm_function_response(
+ message_history: list[dict],
+ tool_function_specs: list[dict],
+ llm_client: openai.OpenAI,
+) -> object:
+ """Creates the function response from the LLM model for the given prompt & functions.
+
+ :param base_system_prompt:
+ :param tool_function_specs:
+ :param user_query:
+ :param llm_client:
+ :return:
+ """
+ response = llm_client.chat.completions.create(
+ model="gpt-4-1106-preview",
+ messages=message_history,
+ tools=tool_function_specs,
+ tool_choice="auto",
+ )
+ response_message = response.choices[0].message
+ return response_message
+ # tool_calls = response_message.tool_calls
+ # return response.choices[0].message.content
+
+
+def llm_function_message(llm_function_response: object) -> dict:
+ if llm_function_response.tool_calls:
+ return {
+ "role": llm_function_response.role,
+ "content": None,
+ "tool_calls": [
+ {
+ "id": t.id,
+ "type": "function",
+ "function": {"name": t.function.name, "arguments": t.function.arguments},
+ }
+ for t in llm_function_response.tool_calls
+ ],
+ }
+ return {
+ "role": "assistant",
+ "content": llm_function_response.content,
+ }
+
+
+def parsed_tool_calls(llm_function_response: object) -> list[dict]:
+ """Parses the tool calls from the LLM response message.
+
+ :param llm_function_response: The response from the LLM model.
+ :return: The parsed tool calls.
+ """
+ tool_calls = llm_function_response.tool_calls
+ parsed_calls = []
+ if tool_calls:
+ for tool_call in tool_calls:
+ func_call = {
+ "id": tool_call.id,
+ "function_name": tool_call.function.name,
+ "function_args": tool_call.function.arguments,
+ }
+ parsed_calls.append(func_call)
+ return parsed_calls
+
+
+def executed_tool_calls(
+ parsed_tool_calls: list[dict], tools: list[Callable]
+) -> list[tuple[str, dict]]:
+ """Executes the parsed tool calls.
+
+ :param parsed_tool_calls: The parsed tool calls.
+ :param tools: The tools to execute.
+ :return: The results of the tool calls.
+ """
+ results = []
+ for tool_call in parsed_tool_calls:
+ tool_name = tool_call["function_name"]
+ tool_args = tool_call["function_args"]
+ for tool in tools:
+ name = getattr(tool, "name", None)
+ if name is None:
+ name = tool.__name__
+ if name == tool_name:
+ kwargs = json.loads(tool_args)
+ if hasattr(tool, "_run"):
+ result = tool._run(**kwargs)
+ else:
+ result = tool(**kwargs)
+ results.append(
+ (
+ tool_name,
+ {
+ "tool_call_id": tool_call["id"],
+ "role": "tool",
+ "name": tool_name,
+ "content": result, # note: might not be a string.
+ },
+ )
+ )
+ # TODO: do we add a sentinel if no tool call was required.
+ return results
+
+
+if __name__ == "__main__":
+ jspec = _tool_function_spec(get_current_weather)
+ import pprint
+
+ pprint.pprint(jspec)
+
+ import __main__
+
+ from hamilton import driver
+
+ dr = driver.Builder().with_modules(__main__).build()
+ result = dr.execute(
+ ["executed_tool_calls"],
+ inputs={
+ "tools": [get_current_weather],
+ "system_message": "You are an accurate weather forecaster.",
+ "user_query": "What is the weather in Tokyo, Japan? Use celsius.",
+ "messages": [],
+ },
+ )
+ print(result)
diff --git a/examples/multi-agent-collaboration/lcel_application.py b/examples/multi-agent-collaboration/lcel_application.py
new file mode 100644
index 00000000..53edfb72
--- /dev/null
+++ b/examples/multi-agent-collaboration/lcel_application.py
@@ -0,0 +1,187 @@
+import json
+from typing import Annotated
+
+from langchain_community.tools.tavily_search import TavilySearchResults
+from langchain_core.messages import FunctionMessage, HumanMessage
+from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
+from langchain_core.tools import tool
+from langchain_core.utils.function_calling import convert_to_openai_function
+from langchain_experimental.utilities import PythonREPL
+from langchain_openai import ChatOpenAI
+from langgraph.prebuilt.tool_executor import ToolExecutor, ToolInvocation
+
+from burr import core
+from burr.core import Action, State, action, default, expr
+from burr.lifecycle import PostRunStepHook
+
+tavily_tool = TavilySearchResults(max_results=5)
+
+# Warning: This executes code locally, which can be unsafe when not sandboxed
+
+repl = PythonREPL()
+
+
+def create_agent(llm, tools, system_message: str):
+ """Helper function to create an agent with a system message and tools."""
+ functions = [convert_to_openai_function(t) for t in tools]
+
+ prompt = ChatPromptTemplate.from_messages(
+ [
+ (
+ "system",
+ "You are a helpful AI assistant, collaborating with other assistants."
+ " Use the provided tools to progress towards answering the question."
+ " If you are unable to fully answer, that's OK, another assistant with different tools "
+ " will help where you left off. Execute what you can to make progress."
+ " If you or any of the other assistants have the final answer or deliverable,"
+ " prefix your response with FINAL ANSWER so the team knows to stop."
+ " You have access to the following tools: {tool_names}.\n{system_message}",
+ ),
+ MessagesPlaceholder(variable_name="messages"),
+ ]
+ )
+ prompt = prompt.partial(system_message=system_message)
+ prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
+ return prompt | llm.bind_functions(functions)
+
+
+@tool
+def python_repl(code: Annotated[str, "The python code to execute to generate your chart."]):
+ """Use this to execute python code. If you want to see the output of a value,
+ you should print it out with `print(...)`. This is visible to the user."""
+ try:
+ result = repl.run(code)
+ except BaseException as e:
+ return f"Failed to execute. Error: {repr(e)}"
+ return f"Succesfully executed:\n```python\n{code}\n```\nStdout: {result}"
+
+
+# Helper function to create a node for a given agent
+def _agent_node(messages: list, sender: str, agent, name: str) -> dict:
+ result = agent.invoke({"messages": messages, "sender": sender})
+ # We convert the agent output into a format that is suitable to append to the global state
+ if isinstance(result, FunctionMessage):
+ pass
+ else:
+ result = HumanMessage(**result.dict(exclude={"type", "name"}), name=name)
+ return {
+ "messages": result,
+ # Since we have a strict workflow, we can
+ # track the sender so we know who to pass to next.
+ "sender": name,
+ }
+
+
+# Objects for the agents
+llm = ChatOpenAI(model="gpt-4-1106-preview")
+research_agent = create_agent(
+ llm,
+ [tavily_tool],
+ system_message="You should provide accurate data for the chart generator to use.",
+)
+chart_agent = create_agent(
+ llm,
+ [python_repl],
+ system_message="Any charts you display will be visible by the user.",
+)
+
+
+@action(reads=["messages", "sender"], writes=["messages", "sender"])
+def research_node(state: State) -> tuple[dict, State]:
+ # Research agent and node
+ result = _agent_node(state["messages"], state["sender"], research_agent, "Researcher")
+ return result, state.append(messages=result["messages"]).update(sender="Researcher")
+
+
+@action(reads=["messages", "sender"], writes=["messages", "sender"])
+def chart_node(state: State) -> tuple[dict, State]:
+ result = _agent_node(state["messages"], state["sender"], chart_agent, "Chart Generator")
+ return result, state.append(messages=result["messages"]).update(sender="Chart Generator")
+
+
+tools = [tavily_tool, python_repl]
+tool_executor = ToolExecutor(tools)
+
+
+@action(reads=["messages"], writes=["messages"])
+def tool_node(state: State) -> tuple[dict, State]:
+ """This runs tools in the graph
+
+ It takes in an agent action and calls that tool and returns the result."""
+ messages = state["messages"]
+ # Based on the continue condition
+ # we know the last message involves a function call
+ last_message = messages[-1]
+ # We construct an ToolInvocation from the function_call
+ tool_input = json.loads(last_message.additional_kwargs["function_call"]["arguments"])
+ # We can pass single-arg inputs by value
+ if len(tool_input) == 1 and "__arg1" in tool_input:
+ tool_input = next(iter(tool_input.values()))
+ tool_name = last_message.additional_kwargs["function_call"]["name"]
+ action = ToolInvocation(
+ tool=tool_name,
+ tool_input=tool_input,
+ )
+ # We call the tool_executor and get back a response
+ response = tool_executor.invoke(action)
+ # We use the response to create a FunctionMessage
+ function_message = FunctionMessage(
+ content=f"{tool_name} response: {str(response)}", name=action.tool
+ )
+ # We return a list, because this will get added to the existing list
+ return {"messages": [function_message]}, state.append(messages=function_message)
+
+
+@action(reads=[], writes=[])
+def terminal_step(state: State) -> tuple[dict, State]:
+ return {}, state
+
+
+class PrintStepHook(PostRunStepHook):
+ def post_run_step(self, *, state: "State", action: "Action", **future_kwargs):
+ print("action=====\n", action)
+ print("state======\n", state)
+
+
+def application():
+ app = (
+ core.ApplicationBuilder()
+ .with_state(
+ messages=[
+ HumanMessage(
+ content="Fetch the UK's GDP over the past 5 years,"
+ " then draw a line graph of it."
+ " Once you code it up, finish."
+ )
+ ],
+ sender=None,
+ )
+ .with_actions(
+ researcher=research_node,
+ charter=chart_node,
+ call_tool=tool_node,
+ terminal=terminal_step,
+ )
+ .with_transitions(
+ ("researcher", "call_tool", expr("'function_call' in messages[-1].additional_kwargs")),
+ ("researcher", "terminal", expr("'FINAL ANSWER' in messages[-1].content")),
+ ("researcher", "charter", default),
+ ("charter", "call_tool", expr("'function_call' in messages[-1].additional_kwargs")),
+ ("charter", "terminal", expr("'FINAL ANSWER' in messages[-1].content")),
+ ("charter", "researcher", default),
+ ("call_tool", "researcher", expr("sender == 'Researcher'")),
+ ("call_tool", "charter", expr("sender == 'Chart Generator'")),
+ )
+ .with_entrypoint("researcher")
+ .with_hooks(PrintStepHook())
+ .with_tracker("lcel-multi-agent")
+ .build()
+ )
+ app.visualize(
+ output_file_path="lcel-multi-agent", include_conditions=True, view=True, format="png"
+ )
+ app.run(until=["terminal"])
+
+
+if __name__ == "__main__":
+ application()
diff --git a/telemetry/ui/src/components/routes/app/StateView.tsx b/telemetry/ui/src/components/routes/app/StateView.tsx
new file mode 100644
index 00000000..003b3926
--- /dev/null
+++ b/telemetry/ui/src/components/routes/app/StateView.tsx
@@ -0,0 +1,22 @@
+import { Step } from '../../../api';
+import JsonView from '@uiw/react-json-view';
+
+export const StateView = (props: {
+ currentStep: Step | undefined;
+ priorStep: Step | undefined;
+}) => {
+ const stateData = props.currentStep?.step_end_log?.state;
+ const resultData = props.currentStep?.step_end_log?.result;
+
+ if (stateData === undefined || resultData === null) {
+ return <></>;
+ }
+ return (
+ <div className="h-full overflow-y-scroll pl-3">
+ <h1 className="text-lg text-gray-600 font-semibold">State</h1>
+ <JsonView value={stateData} collapsed={2} />
+ <h1 className="text-lg text-gray-600 font-semibold">Result</h1>
+ <JsonView value={resultData} collapsed={2} />
+ </div>
+ );
+};