-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmulti_agent.py
More file actions
192 lines (155 loc) · 5.88 KB
/
Copy pathmulti_agent.py
File metadata and controls
192 lines (155 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import functools
import os
from typing import Any, Generator, Literal, Optional
import mlflow
from databricks.sdk import WorkspaceClient
from databricks_langchain import (
ChatDatabricks,
UCFunctionToolkit,
)
from databricks_langchain.genie import GenieAgent
from langchain_core.runnables import RunnableLambda
from langgraph.graph import END, StateGraph
from langgraph.graph.state import CompiledStateGraph
from langgraph.prebuilt import create_react_agent
from mlflow.langchain.chat_agent_langgraph import ChatAgentState
from mlflow.pyfunc import ChatAgent
from mlflow.types.agent import (
ChatAgentChunk,
ChatAgentMessage,
ChatAgentResponse,
ChatContext,
)
from pydantic import BaseModel
#####################################################
## Create a GenieAgent with access to a Genie Space:
#####################################################
GENIE_SPACE_ID = "" # Insert your Genie Space ID here:
genie_agent_description = "This genie agent can answer ..."
genie_agent = GenieAgent(
genie_space_id=GENIE_SPACE_ID,
genie_agent_name="Genie",
client=WorkspaceClient(
host=os.getenv("DB_MODEL_SERVING_HOST_URL"),
token=os.getenv("DATABRICKS_GENIE_PAT"),
),
)
############################################
# Define your LLM endpoint and system prompt
############################################
LLM_ENDPOINT_NAME = "databricks-claude-3-7-sonnet"
llm = ChatDatabricks(endpoint=LLM_ENDPOINT_NAME)
#############################
# Define the supervisor agent
#############################
MAX_ITERATIONS = 3
worker_descriptions = {
"Genie": genie_agent_description,
}
formatted_descriptions = "\n".join(
f"- {name}: {desc}" for name, desc in worker_descriptions.items()
)
system_prompt = f"Decide between routing between the following workers or ending the conversation if an answer is provided. \n{formatted_descriptions}"
options = ["FINISH"] + list(worker_descriptions.keys())
FINISH = {"next_node": "FINISH"}
def supervisor_agent(state):
count = state.get("iteration_count", 0) + 1
if count > MAX_ITERATIONS:
return FINISH
class nextNode(BaseModel):
next_node: Literal[tuple(options)]
preprocessor = RunnableLambda(
lambda state: [{"role": "system", "content": system_prompt}] + state["messages"]
)
supervisor_chain = preprocessor | llm.with_structured_output(nextNode)
next_node = supervisor_chain.invoke(state).next_node
# if routed back to the same node, exit the loop
if state.get("next_node") == next_node:
return FINISH
return {
"iteration_count": count,
"next_node": next_node
}
#######################################
# Define our multiagent graph structure
#######################################
def agent_node(state, agent, name):
result = agent.invoke(state)
return {
"messages": [
{
"role": "assistant",
"content": result["messages"][-1].content,
"name": name,
}
]
}
def final_answer(state):
prompt = "Using only the content in the messages, respond to the previous user question using the answer given by the other assistant messages."
preprocessor = RunnableLambda(
lambda state: state["messages"] + [{"role": "user", "content": prompt}]
)
final_answer_chain = preprocessor | llm
return {"messages": [final_answer_chain.invoke(state)]}
class AgentState(ChatAgentState):
next_node: str
iteration_count: int
genie_node = functools.partial(agent_node, agent=genie_agent, name="Genie")
workflow = StateGraph(AgentState)
workflow.add_node("Genie", genie_node)
workflow.add_node("supervisor", supervisor_agent)
workflow.add_node("final_answer", final_answer)
workflow.set_entry_point("supervisor")
# We want our workers to ALWAYS "report back" to the supervisor when done
for worker in worker_descriptions.keys():
workflow.add_edge(worker, "supervisor")
# Let the supervisor decide which next node to go
workflow.add_conditional_edges(
"supervisor",
lambda x: x["next_node"],
{**{k: k for k in worker_descriptions.keys()}, "FINISH": "final_answer"},
)
workflow.add_edge("final_answer", END)
multi_agent = workflow.compile()
###################################
# Wrap our multi-agent in ChatAgent
###################################
class LangGraphChatAgent(ChatAgent):
def __init__(self, agent: CompiledStateGraph):
self.agent = agent
def predict(
self,
messages: list[ChatAgentMessage],
context: Optional[ChatContext] = None,
custom_inputs: Optional[dict[str, Any]] = None,
) -> ChatAgentResponse:
request = {
"messages": [m.model_dump_compat(exclude_none=True) for m in messages]
}
messages = []
for event in self.agent.stream(request, stream_mode="updates"):
for node_data in event.values():
messages.extend(
ChatAgentMessage(**msg) for msg in node_data.get("messages", [])
)
return ChatAgentResponse(messages=messages)
def predict_stream(
self,
messages: list[ChatAgentMessage],
context: Optional[ChatContext] = None,
custom_inputs: Optional[dict[str, Any]] = None,
) -> Generator[ChatAgentChunk, None, None]:
request = {
"messages": [m.model_dump_compat(exclude_none=True) for m in messages]
}
for event in self.agent.stream(request, stream_mode="updates"):
for node_data in event.values():
yield from (
ChatAgentChunk(**{"delta": msg})
for msg in node_data.get("messages", [])
)
# Create the agent object, and specify it as the agent object to use when
# loading the agent back for inference via mlflow.models.set_model():
mlflow.langchain.autolog()
AGENT = LangGraphChatAgent(multi_agent)
mlflow.models.set_model(AGENT)