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.

Adds README to multi-agent-collaboration example

Stefan Krawczyk4cb543029117
diff --git a/examples/multi-agent-collaboration/README.md b/examples/multi-agent-collaboration/README.md
index e69de29b..784da94e 100644
--- a/examples/multi-agent-collaboration/README.md
+++ b/examples/multi-agent-collaboration/README.md
@@ -0,0 +1,66 @@
+# Multi Agent Collaboration
+
+This example resembles the example from following [cookbook](https://github.com/langchain-ai/langgraph/blob/main/examples/multi_agent/multi-agent-collaboration.ipynb).
+
+There are three implementations:
+
+1. `hamilton_application.py` -- this uses [Hamilton](https://github.com/dagworks-inc/hamilton) inside the actions.
+2. `lecl_application.py` -- this uses LangChain's LCEL inside the actions.
+3. `application.py` -- this tries to simplify the graph to have tool calling happen inside the actions.
+
+# `hamilton_application.py` vs `lecl_application.py`:
+
+- They should be functionally equivalent, except that langchain uses deprecated
+openai tool constructs underneath, while Hamilton uses the non-deprecated function calling
+constructs.
+- Compare the two examples to see the code. Burr however doesn't change.
+
+## show me the prompts
+With Hamilton the prompts can be found in `func_agent.py`.
+
+With LangChain that's difficult. You'll need to dive into their code to see what ends up being sent.
+
+# Tracing
+You'll see that both `hamilton_application.py` and `lecl_application.py`
+have some lightweight `tracing` set up. This is a simple way to plug into Burr's
+tracer functionality -- this will allow you to see more in the Burr UI.
+
+More functionality is on the roadmap!
+
+# Running the example
+
+Install the dependencies:
+
+```bash
+pip install "burr[start]" -r requirements.txt
+```
+
+Make sure you have the API Keys in your environment:
+
+```bash
+export OPENAI_API_KEY=YOUR_KEY
+export TAVILY_API_KEY=YOUR_KEY
+```
+
+
+To run the example, you can do:
+
+```bash
+python hamilton_application.py
+```
+Application run:
+![hamilton image](hamilton-multi-agent-v2.png)
+
+or
+```bash
+python lecl_application.py
+```
+Application run:
+![lcel image](lcel-multi-agent.png)
+
+or
+```bash
+python application.py
+```
+Application run:
+![simpler hamilton image](hamilton-multi-agent.png)
diff --git a/examples/multi-agent-collaboration/application.py b/examples/multi-agent-collaboration/application.py
index cfb459b3..3a2eda62 100644
--- a/examples/multi-agent-collaboration/application.py
+++ b/examples/multi-agent-collaboration/application.py
@@ -10,7 +10,9 @@ from burr.lifecycle import PostRunStepHook
from burr.tracking import client as burr_tclient
# Initialize some things needed for tools.
+# see func_agent.py for the code for this pipeline
tool_dag = driver.Builder().with_modules(func_agent).build()
+# Will run code provided by the LLM.
repl = PythonREPL()
@@ -30,7 +32,14 @@ def python_repl(code: str) -> dict:
@action(reads=["query", "messages"], writes=["messages", "next_hop"])
def chart_generator(state: State) -> tuple[dict, State]:
+ """
+ Generates a chart based on the provided query and updates the state.
+
+ :param state: The current state of the application.
+ :return: A tuple containing the result of the tool execution and the updated state.
+ """
query = state["query"]
+ # see func_agent.py for the code for this pipeline
result = tool_dag.execute(
["executed_tool_calls", "parsed_tool_calls", "llm_function_message"],
inputs={
@@ -63,7 +72,14 @@ tavily_tool = TavilySearchResults(max_results=5)
@action(reads=["query", "messages"], writes=["messages", "next_hop"])
def researcher(state: State) -> tuple[dict, State]:
+ """
+ Performs research based on the provided query and updates the state.
+
+ :param state: The current state of the application.
+ :return: A tuple containing the result of the tool execution and the updated state.
+ """
query = state["query"]
+ # see func_agent.py for the code for this pipeline
result = tool_dag.execute(
["executed_tool_calls", "parsed_tool_calls", "llm_function_message"],
inputs={
@@ -92,16 +108,20 @@ def researcher(state: State) -> tuple[dict, State]:
@action(reads=[], writes=[])
def terminal_step(state: State) -> tuple[dict, State]:
+ """One can express a terminal action like this."""
return {}, state
class PrintStepHook(PostRunStepHook):
+ """Example of a post run step hook that prints the state and action."""
+
def post_run_step(self, *, state: "State", action: "Action", **future_kwargs):
print("action=====\n", action)
print("state======\n", state)
def default_state_and_entry_point() -> tuple[dict, str]:
+ """Default state and entry point for the application."""
return {
"messages": [],
"query": "Fetch the UK's GDP over the past 5 years,"
@@ -112,6 +132,11 @@ def default_state_and_entry_point() -> tuple[dict, str]:
def main(app_instance_id: str = None):
+ """
+ Builds the application and runs it.
+
+ :param app_instance_id: The ID of the application instance to load the state from.
+ """
project_name = "demo:hamilton-multi-agent"
if app_instance_id:
state, entry_point = burr_tclient.LocalTrackingClient.load_state(
@@ -138,12 +163,12 @@ def main(app_instance_id: str = None):
"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(entry_point)
.with_hooks(PrintStepHook())
@@ -157,8 +182,13 @@ def main(app_instance_id: str = None):
if __name__ == "__main__":
- # Add an app_id to restart from last sequence in that state
- # e.g. fine the ID in the UI and then put it in here "app_4d1618d2-79d1-4d89-8e3f-70c216c71e63"
+ """
+ The entry point of the application.
+
+ If an app_id is provided, the application will restart from the last
+ sequence in that state.
+ E.g. fine the ID in the UI and then put it in here "app_4d1618d2-79d1-4d89-8e3f-70c216c71e63"
+ """
_app_id = None
main(_app_id)
diff --git a/examples/multi-agent-collaboration/func_agent.py b/examples/multi-agent-collaboration/func_agent.py
index 8d95e04b..b80788af 100644
--- a/examples/multi-agent-collaboration/func_agent.py
+++ b/examples/multi-agent-collaboration/func_agent.py
@@ -1,3 +1,8 @@
+"""
+Hamilton module that defines the pipeline for
+hitting an LLM model and asking it what to do.
+"""
+
import inspect
import json
from typing import Callable
@@ -11,18 +16,29 @@ def llm_client() -> openai.OpenAI:
def tool_names(tool_function_specs: list[dict]) -> list[str]:
+ """Get the names of the tools from the tool function specs."""
return [tool["function"]["name"] for tool in tool_function_specs]
def _langchain_tool_spec(tool: Callable) -> dict:
+ """Converts a tool to a langchain tool spec."""
t = convert_to_openai_function(tool)
# print(t)
return t
def _tool_function_spec(tool: Callable) -> dict:
+ """Converts a python function into a specification for function calling.
+
+ This is a little hacky. But it works.
+
+ It takes a function, introspects it, and returns a spec.
+
+ :param tool:
+ :return:
+ """
# TODO: maybe just get people to wrap any external tool in a function
- # to make it clear WTF is going on.
+ # to make it clear what 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)
@@ -83,10 +99,12 @@ def _tool_function_spec(tool: Callable) -> dict:
def tool_function_specs(tools: list[Callable]) -> list[dict]:
+ """Converts a list of tools into a list of tool function specs."""
return [_tool_function_spec(tool) for tool in tools]
def base_system_prompt(tool_names: list[str], system_message: str) -> str:
+ """Creates the base system prompt for the pipeline."""
return (
"You are a helpful AI assistant, collaborating with other assistants."
" Use the provided tools to progress towards answering the question."
@@ -118,6 +136,13 @@ def get_current_weather(location: str, unit: str = "fahrenheit") -> str:
def message_history(base_system_prompt: str, user_query: str, messages: list[dict]) -> list[dict]:
+ """Creates the message history for the LLM model.
+
+ :param base_system_prompt:
+ :param user_query:
+ :param messages:
+ :return:
+ """
base = [
{"role": "system", "content": base_system_prompt},
{"role": "user", "content": user_query},
@@ -152,13 +177,12 @@ def llm_function_response(
tool_choice="auto",
)
return response
- # tool_calls = response_message.tool_calls
- # return response.choices[0].message.content
def llm_function_message(
llm_function_response: openai.types.chat.chat_completion.ChatCompletion,
) -> dict:
+ """Parses the LLM response message. Does extra parsing for tool invocations."""
response_message = llm_function_response.choices[0].message
if response_message.tool_calls:
return {
@@ -166,7 +190,7 @@ def llm_function_message(
"content": None,
"tool_calls": [
{
- "id": t.uid,
+ "id": t.id,
"type": "function",
"function": {"name": t.function.name, "arguments": t.function.arguments},
}
@@ -193,7 +217,7 @@ def parsed_tool_calls(
if tool_calls:
for tool_call in tool_calls:
func_call = {
- "id": tool_call.uid,
+ "id": tool_call.id,
"function_name": tool_call.function.name,
"function_args": tool_call.function.arguments,
}
@@ -244,6 +268,7 @@ def executed_tool_calls(
if __name__ == "__main__":
+ # some code to test a few things.
jspec = _tool_function_spec(get_current_weather)
import pprint
diff --git a/examples/multi-agent-collaboration/hamilton-multi-agent.png b/examples/multi-agent-collaboration/hamilton-multi-agent.png
new file mode 100644
index 00000000..b4c3129f
Binary files /dev/null and b/examples/multi-agent-collaboration/hamilton-multi-agent.png differ
diff --git a/examples/multi-agent-collaboration/hamilton_application.py b/examples/multi-agent-collaboration/hamilton_application.py
index 73faf0e1..183bf87b 100644
--- a/examples/multi-agent-collaboration/hamilton_application.py
+++ b/examples/multi-agent-collaboration/hamilton_application.py
@@ -1,3 +1,9 @@
+"""
+Hamilton version of the multi-agent collaboration example.
+
+This also adds a tracer to the Hamilton DAG to trace the execution of the nodes
+within the Action so that they also show up in the Burr UI.
+"""
import json
from typing import Any, Dict, Optional
@@ -15,7 +21,7 @@ from burr.visibility import ActionSpanTracer, TracerFactory
class SimpleTracer(h_lifecycle.NodeExecutionHook):
- """Simple Hamilton Tracer"""
+ """Simple Hamilton Tracer that plugs into Burr's tracing capture."""
def __init__(self, tracer: TracerFactory):
self._tracer: TracerFactory = tracer
@@ -56,6 +62,7 @@ class SimpleTracer(h_lifecycle.NodeExecutionHook):
def initialize_tool_dag(agent_name: str, tracer: TracerFactory) -> driver.Driver:
+ """Initialize the tool DAG with the tracer."""
tracer = SimpleTracer(tracer)
# Initialize some things needed for tools.
tool_dag = driver.Builder().with_modules(func_agent).with_adapters(tracer).build()
@@ -79,8 +86,14 @@ def python_repl(code: str) -> dict:
return {"status": "success", "code": f"```python\n{code}\n```", "Stdout": result}
-@action(reads=["query", "messages"], writes=["messages", "next_hop"])
+@action(reads=["query", "messages"], writes=["messages"])
def chart_generator(state: State, __tracer: TracerFactory) -> tuple[dict, State]:
+ """The chart generator action.
+
+ :param state: state of the application
+ :param __tracer: burr tracer that gets injected.
+ :return:
+ """
query = state["query"]
tool_dag = initialize_tool_dag("chart_generator", __tracer)
result = tool_dag.execute(
@@ -104,8 +117,14 @@ def chart_generator(state: State, __tracer: TracerFactory) -> tuple[dict, State]
tavily_tool = TavilySearchResults(max_results=5)
-@action(reads=["query", "messages"], writes=["messages", "next_hop"])
+@action(reads=["query", "messages"], writes=["messages"])
def researcher(state: State, __tracer: TracerFactory) -> tuple[dict, State]:
+ """The researcher action.
+
+ :param state: state of the application
+ :param __tracer: the burr tracer that gets injected.
+ :return:
+ """
query = state["query"]
tool_dag = initialize_tool_dag("researcher", __tracer)
result = tool_dag.execute(
@@ -130,9 +149,7 @@ tools = [tavily_tool, python_repl]
@action(reads=["messages", "parsed_tool_calls"], writes=["messages", "parsed_tool_calls"])
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."""
+ """Given a tool call, execute it and return the result."""
new_messages = []
parsed_tool_calls = state["parsed_tool_calls"]
@@ -147,11 +164,11 @@ def tool_node(state: State) -> tuple[dict, State]:
if name == tool_name:
tool_found = True
kwargs = json.loads(tool_args)
+ # Execute the tool!
if hasattr(tool, "_run"):
result = tool._run(**kwargs)
else:
result = tool(**kwargs)
- # str_result = str(result)
new_messages.append(
{
"tool_call_id": tool_call["id"],
@@ -176,12 +193,15 @@ def terminal_step(state: State) -> tuple[dict, State]:
class PrintStepHook(PostRunStepHook):
+ """Prints the action and state after each step."""
+
def post_run_step(self, *, state: "State", action: "Action", **future_kwargs):
print("action=====\n", action)
print("state======\n", state)
def default_state_and_entry_point() -> tuple[dict, str]:
+ """Returns the default state and entry point for the application."""
return {
"messages": [],
"query": "Fetch the UK's GDP over the past 5 years,"
@@ -192,12 +212,18 @@ def default_state_and_entry_point() -> tuple[dict, str]:
}, "researcher"
-def main(app_instance_id: str = None, sequence_number: int = -1):
+def main(app_instance_id: str = None, sequence_number: int = None):
+ """Main function to run the application."""
project_name = "demo:hamilton-multi-agent-v1"
if app_instance_id:
- state, entry_point = burr_tclient.LocalTrackingClient.load_state(
- project_name, app_instance_id, sequence_no=sequence_number
- )
+ tracker = burr_tclient.LocalTrackingClient(project_name)
+ persisted_state = tracker.load("demo", app_id=app_instance_id, sequence_no=sequence_number)
+ if not persisted_state:
+ print(f"Warning: No persisted state found for app_id {app_instance_id}.")
+ state, entry_point = default_state_and_entry_point()
+ else:
+ state = persisted_state["state"]
+ entry_point = persisted_state["position"]
else:
state, entry_point = default_state_and_entry_point()
# look up app_id for particular user
@@ -230,6 +256,7 @@ def main(app_instance_id: str = None, sequence_number: int = -1):
("tool_node", "researcher", core.expr("sender == 'researcher'")),
("tool_node", "chart_generator", core.expr("sender == 'chart_generator'")),
)
+ .with_identifiers(partition_key="demo")
.with_entrypoint(entry_point)
.with_hooks(PrintStepHook())
.with_tracker(project=project_name)
@@ -244,12 +271,12 @@ def main(app_instance_id: str = None, sequence_number: int = -1):
if __name__ == "__main__":
# Add an app_id to restart from last sequence in that state
# e.g. fine the ID in the UI and then put it in here "app_f0e4a918-b49c-4ee1-9d2b-30c15104c51c"
- # _app_id = None # "app_4ed5b3b3-0f38-4b37-aed7-559d506174c7"
- _app_id = "app_4ed5b3b3-0f38-4b37-aed7-559d506174c7"
+ _app_id = None # "app_4ed5b3b3-0f38-4b37-aed7-559d506174c7"
+ _app_id = "8458dc58-7b6c-430b-9ab3-23450774f883"
# _sequence_no = None # 23
- _sequence_no = 23
- main(None, None)
- # main(_app_id, _sequence_no)
+ _sequence_no = 5
+ # main(None, None)
+ main(_app_id, _sequence_no)
# some test code
# tavily_tool = TavilySearchResults(max_results=5)
diff --git a/examples/multi-agent-collaboration/lcel-multi-agent.png b/examples/multi-agent-collaboration/lcel-multi-agent.png
new file mode 100644
index 00000000..0a869a95
Binary files /dev/null and b/examples/multi-agent-collaboration/lcel-multi-agent.png differ
diff --git a/examples/multi-agent-collaboration/lcel_application.py b/examples/multi-agent-collaboration/lcel_application.py
index 128349dc..bfb5cd05 100644
--- a/examples/multi-agent-collaboration/lcel_application.py
+++ b/examples/multi-agent-collaboration/lcel_application.py
@@ -1,3 +1,10 @@
+"""
+Langchain version of the multi-agent collaboration example.
+
+This also adds a tracer to the Langchain calls to trace the execution of the nodes
+within the Action so that they also show up in the Burr UI. This is a
+very simple tracer, it could easily be extended to include more information.
+"""
import json
from typing import Annotated, Any, Optional
from uuid import UUID
@@ -27,16 +34,14 @@ repl = PythonREPL()
class LangChainTracer(BaseCallbackHandler):
+ """Example tracer to plug into Burr's tracing capture."""
+
def __init__(self, tracer: TracerFactory):
self._tracer: TracerFactory = tracer
self.active_spans = {}
def on_llm_start(self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any) -> Any:
"""Run when LLM starts running."""
- # print("LLM STARTED")
- # print(prompts)
- # print(serialized)
- # print(kwargs)
model_name = kwargs["invocation_params"]["model_name"]
run_id = kwargs["run_id"]
name = (model_name + "_" + str(run_id))[:30]
@@ -53,11 +58,6 @@ class LangChainTracer(BaseCallbackHandler):
**kwargs: Any,
) -> Any:
"""Run when LLM ends running."""
- # print("LLM ENDED")
- # print(response)
- # print(run_id)
- # print(parent_run_id)
- # print(kwargs)
model_name = response.llm_output["model_name"]
name = (model_name + "_" + str(run_id))[:30]
context_manager = self.active_spans.pop(name)
@@ -101,6 +101,7 @@ def python_repl(code: Annotated[str, "The python code to execute to generate you
# Helper function to create a node for a given agent
def _agent_node(messages: list, sender: str, agent, name: str, tracer: TracerFactory) -> dict:
+ """Helper function to create a node for a given agent."""
tracer = LangChainTracer(tracer)
result = agent.invoke({"messages": messages, "sender": sender}, config={"callbacks": [tracer]})
# We convert the agent output into a format that is suitable to append to the global state
@@ -139,6 +140,7 @@ def research_node(state: State, __tracer: TracerFactory) -> tuple[dict, State]:
@action(reads=["messages", "sender"], writes=["messages", "sender"])
def chart_node(state: State, __tracer: TracerFactory) -> tuple[dict, State]:
+ # Chart agent and node
result = _agent_node(
state["messages"], state["sender"], chart_agent, "Chart Generator", __tracer
)
@@ -206,12 +208,20 @@ def default_state_and_entry_point() -> tuple[dict, str]:
def main(app_instance_id: str = None):
+ """Main function to run the multi-agent collaboration example.
+
+ Pass in an app_instance_id to restart from a previous run.
+ """
project_name = "demo:hamilton-multi-agent"
if app_instance_id:
- initial_state, entry_point = burr_tclient.LocalTrackingClient.load_state(
- project_name, app_instance_id
- )
- # TODO: rehydrate langchain objects from JSON
+ tracker = burr_tclient.LocalTrackingClient(project_name)
+ persisted_state = tracker.load("demo", app_id=app_instance_id, sequence_no=None)
+ if not persisted_state:
+ print(f"Warning: No persisted state found for app_id {app_instance_id}.")
+ initial_state, entry_point = default_state_and_entry_point()
+ else:
+ initial_state = persisted_state["state"]
+ entry_point = persisted_state["position"]
else:
initial_state, entry_point = default_state_and_entry_point()
app = (
diff --git a/examples/multi-agent-collaboration/requirements.txt b/examples/multi-agent-collaboration/requirements.txt
new file mode 100644
index 00000000..5c9d0fad
--- /dev/null
+++ b/examples/multi-agent-collaboration/requirements.txt
@@ -0,0 +1,7 @@
+burr
+langchain-community
+langchain-core
+langchain-experimental
+langgraph
+openai
+sf-hamilton[visualization]
diff --git a/pyproject.toml b/pyproject.toml
index 3afbeae6..57964172 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "burr"
-version = "0.11.0"
+version = "0.11.2"
dependencies = [] # yes, there are none
requires-python = ">=3.9"
authors = [