-
Notifications
You must be signed in to change notification settings - Fork 867
/
agent.py
383 lines (348 loc) · 11.8 KB
/
agent.py
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import pickle
from enum import Enum
from typing import Any, Dict, Mapping, Optional, Sequence, Union
from langchain_core.messages import AnyMessage
from langchain_core.runnables import (
ConfigurableField,
RunnableBinding,
)
from langgraph.checkpoint import CheckpointAt
from langgraph.graph.message import Messages
from langgraph.pregel import Pregel
from app.agent_types.tools_agent import get_tools_agent_executor
from app.agent_types.xml_agent import get_xml_agent_executor
from app.chatbot import get_chatbot_executor
from app.checkpoint import PostgresCheckpoint
from app.llms import (
get_anthropic_llm,
get_google_llm,
get_mixtral_fireworks,
get_ollama_llm,
get_openai_llm,
)
from app.retrieval import get_retrieval_executor
from app.tools import (
RETRIEVAL_DESCRIPTION,
TOOLS,
ActionServer,
Arxiv,
AvailableTools,
Connery,
DallE,
DDGSearch,
PressReleases,
PubMed,
Retrieval,
SecFilings,
Tavily,
TavilyAnswer,
Wikipedia,
YouSearch,
get_retrieval_tool,
get_retriever,
)
Tool = Union[
ActionServer,
Connery,
DDGSearch,
Arxiv,
YouSearch,
SecFilings,
PressReleases,
PubMed,
Wikipedia,
Tavily,
TavilyAnswer,
Retrieval,
DallE,
]
class AgentType(str, Enum):
GPT_35_TURBO = "GPT 3.5 Turbo"
GPT_4 = "GPT 4 Turbo"
GPT_4O = "GPT 4o"
AZURE_OPENAI = "GPT 4 (Azure OpenAI)"
CLAUDE2 = "Claude 2"
BEDROCK_CLAUDE2 = "Claude 2 (Amazon Bedrock)"
GEMINI = "GEMINI"
OLLAMA = "Ollama"
DEFAULT_SYSTEM_MESSAGE = "You are a helpful assistant."
CHECKPOINTER = PostgresCheckpoint(serde=pickle, at=CheckpointAt.END_OF_STEP)
def get_agent_executor(
tools: list,
agent: AgentType,
system_message: str,
interrupt_before_action: bool,
):
if agent == AgentType.GPT_35_TURBO:
llm = get_openai_llm()
return get_tools_agent_executor(
tools, llm, system_message, interrupt_before_action, CHECKPOINTER
)
elif agent == AgentType.GPT_4:
llm = get_openai_llm(model="gpt-4-turbo")
return get_tools_agent_executor(
tools, llm, system_message, interrupt_before_action, CHECKPOINTER
)
elif agent == AgentType.GPT_4O:
llm = get_openai_llm(model="gpt-4o")
return get_tools_agent_executor(
tools, llm, system_message, interrupt_before_action, CHECKPOINTER
)
elif agent == AgentType.AZURE_OPENAI:
llm = get_openai_llm(azure=True)
return get_tools_agent_executor(
tools, llm, system_message, interrupt_before_action, CHECKPOINTER
)
elif agent == AgentType.CLAUDE2:
llm = get_anthropic_llm()
return get_tools_agent_executor(
tools, llm, system_message, interrupt_before_action, CHECKPOINTER
)
elif agent == AgentType.BEDROCK_CLAUDE2:
llm = get_anthropic_llm(bedrock=True)
return get_xml_agent_executor(
tools, llm, system_message, interrupt_before_action, CHECKPOINTER
)
elif agent == AgentType.GEMINI:
llm = get_google_llm()
return get_tools_agent_executor(
tools, llm, system_message, interrupt_before_action, CHECKPOINTER
)
elif agent == AgentType.OLLAMA:
llm = get_ollama_llm()
return get_tools_agent_executor(
tools, llm, system_message, interrupt_before_action, CHECKPOINTER
)
else:
raise ValueError("Unexpected agent type")
class ConfigurableAgent(RunnableBinding):
tools: Sequence[Tool]
agent: AgentType
system_message: str = DEFAULT_SYSTEM_MESSAGE
retrieval_description: str = RETRIEVAL_DESCRIPTION
interrupt_before_action: bool = False
assistant_id: Optional[str] = None
thread_id: Optional[str] = None
user_id: Optional[str] = None
def __init__(
self,
*,
tools: Sequence[Tool],
agent: AgentType = AgentType.GPT_35_TURBO,
system_message: str = DEFAULT_SYSTEM_MESSAGE,
assistant_id: Optional[str] = None,
thread_id: Optional[str] = None,
retrieval_description: str = RETRIEVAL_DESCRIPTION,
interrupt_before_action: bool = False,
kwargs: Optional[Mapping[str, Any]] = None,
config: Optional[Mapping[str, Any]] = None,
**others: Any,
) -> None:
others.pop("bound", None)
_tools = []
for _tool in tools:
if _tool["type"] == AvailableTools.RETRIEVAL:
if assistant_id is None or thread_id is None:
raise ValueError(
"Both assistant_id and thread_id must be provided if Retrieval tool is used"
)
_tools.append(
get_retrieval_tool(assistant_id, thread_id, retrieval_description)
)
else:
tool_config = _tool.get("config", {})
_returned_tools = TOOLS[_tool["type"]](**tool_config)
if isinstance(_returned_tools, list):
_tools.extend(_returned_tools)
else:
_tools.append(_returned_tools)
_agent = get_agent_executor(
_tools, agent, system_message, interrupt_before_action
)
agent_executor = _agent.with_config({"recursion_limit": 50})
super().__init__(
tools=tools,
agent=agent,
system_message=system_message,
retrieval_description=retrieval_description,
bound=agent_executor,
kwargs=kwargs or {},
config=config or {},
)
class LLMType(str, Enum):
GPT_35_TURBO = "GPT 3.5 Turbo"
GPT_4 = "GPT 4 Turbo"
GPT_4O = "GPT 4o"
AZURE_OPENAI = "GPT 4 (Azure OpenAI)"
CLAUDE2 = "Claude 2"
BEDROCK_CLAUDE2 = "Claude 2 (Amazon Bedrock)"
GEMINI = "GEMINI"
MIXTRAL = "Mixtral"
OLLAMA = "Ollama"
def get_chatbot(
llm_type: LLMType,
system_message: str,
):
if llm_type == LLMType.GPT_35_TURBO:
llm = get_openai_llm()
elif llm_type == LLMType.GPT_4:
llm = get_openai_llm(gpt_4=True)
elif llm_type == LLMType.AZURE_OPENAI:
llm = get_openai_llm(azure=True)
elif llm_type == LLMType.CLAUDE2:
llm = get_anthropic_llm()
elif llm_type == LLMType.BEDROCK_CLAUDE2:
llm = get_anthropic_llm(bedrock=True)
elif llm_type == LLMType.GEMINI:
llm = get_google_llm()
elif llm_type == LLMType.MIXTRAL:
llm = get_mixtral_fireworks()
elif llm_type == LLMType.OLLAMA:
llm = get_ollama_llm()
else:
raise ValueError("Unexpected llm type")
return get_chatbot_executor(llm, system_message, CHECKPOINTER)
class ConfigurableChatBot(RunnableBinding):
llm: LLMType
system_message: str = DEFAULT_SYSTEM_MESSAGE
user_id: Optional[str] = None
def __init__(
self,
*,
llm: LLMType = LLMType.GPT_35_TURBO,
system_message: str = DEFAULT_SYSTEM_MESSAGE,
kwargs: Optional[Mapping[str, Any]] = None,
config: Optional[Mapping[str, Any]] = None,
**others: Any,
) -> None:
others.pop("bound", None)
chatbot = get_chatbot(llm, system_message)
super().__init__(
llm=llm,
system_message=system_message,
bound=chatbot,
kwargs=kwargs or {},
config=config or {},
)
chatbot = (
ConfigurableChatBot(llm=LLMType.GPT_35_TURBO, checkpoint=CHECKPOINTER)
.configurable_fields(
llm=ConfigurableField(id="llm_type", name="LLM Type"),
system_message=ConfigurableField(id="system_message", name="Instructions"),
)
.with_types(
input_type=Messages,
output_type=Sequence[AnyMessage],
)
)
class ConfigurableRetrieval(RunnableBinding):
llm_type: LLMType
system_message: str = DEFAULT_SYSTEM_MESSAGE
assistant_id: Optional[str] = None
thread_id: Optional[str] = None
user_id: Optional[str] = None
def __init__(
self,
*,
llm_type: LLMType = LLMType.GPT_35_TURBO,
system_message: str = DEFAULT_SYSTEM_MESSAGE,
assistant_id: Optional[str] = None,
thread_id: Optional[str] = None,
kwargs: Optional[Mapping[str, Any]] = None,
config: Optional[Mapping[str, Any]] = None,
**others: Any,
) -> None:
others.pop("bound", None)
retriever = get_retriever(assistant_id, thread_id)
if llm_type == LLMType.GPT_35_TURBO:
llm = get_openai_llm()
elif llm_type == LLMType.GPT_4:
llm = get_openai_llm(model="gpt-4-turbo")
elif llm_type == LLMType.GPT_4O:
llm = get_openai_llm(model="gpt-4o")
elif llm_type == LLMType.AZURE_OPENAI:
llm = get_openai_llm(azure=True)
elif llm_type == LLMType.CLAUDE2:
llm = get_anthropic_llm()
elif llm_type == LLMType.BEDROCK_CLAUDE2:
llm = get_anthropic_llm(bedrock=True)
elif llm_type == LLMType.GEMINI:
llm = get_google_llm()
elif llm_type == LLMType.MIXTRAL:
llm = get_mixtral_fireworks()
elif llm_type == LLMType.OLLAMA:
llm = get_ollama_llm()
else:
raise ValueError("Unexpected llm type")
chatbot = get_retrieval_executor(llm, retriever, system_message, CHECKPOINTER)
super().__init__(
llm_type=llm_type,
system_message=system_message,
bound=chatbot,
kwargs=kwargs or {},
config=config or {},
)
chat_retrieval = (
ConfigurableRetrieval(llm_type=LLMType.GPT_35_TURBO, checkpoint=CHECKPOINTER)
.configurable_fields(
llm_type=ConfigurableField(id="llm_type", name="LLM Type"),
system_message=ConfigurableField(id="system_message", name="Instructions"),
assistant_id=ConfigurableField(
id="assistant_id", name="Assistant ID", is_shared=True
),
thread_id=ConfigurableField(id="thread_id", name="Thread ID", is_shared=True),
)
.with_types(
input_type=Dict[str, Any],
output_type=Dict[str, Any],
)
)
agent: Pregel = (
ConfigurableAgent(
agent=AgentType.GPT_35_TURBO,
tools=[],
system_message=DEFAULT_SYSTEM_MESSAGE,
retrieval_description=RETRIEVAL_DESCRIPTION,
assistant_id=None,
thread_id=None,
)
.configurable_fields(
agent=ConfigurableField(id="agent_type", name="Agent Type"),
system_message=ConfigurableField(id="system_message", name="Instructions"),
interrupt_before_action=ConfigurableField(
id="interrupt_before_action",
name="Tool Confirmation",
description="If Yes, you'll be prompted to continue before each tool is executed.\nIf No, tools will be executed automatically by the agent.",
),
assistant_id=ConfigurableField(
id="assistant_id", name="Assistant ID", is_shared=True
),
thread_id=ConfigurableField(id="thread_id", name="Thread ID", is_shared=True),
tools=ConfigurableField(id="tools", name="Tools"),
retrieval_description=ConfigurableField(
id="retrieval_description", name="Retrieval Description"
),
)
.configurable_alternatives(
ConfigurableField(id="type", name="Bot Type"),
default_key="agent",
prefix_keys=True,
chatbot=chatbot,
chat_retrieval=chat_retrieval,
)
.with_types(
input_type=Messages,
output_type=Sequence[AnyMessage],
)
)
if __name__ == "__main__":
import asyncio
from langchain.schema.messages import HumanMessage
async def run():
async for m in agent.astream_events(
HumanMessage(content="whats your name"),
config={"configurable": {"user_id": "2", "thread_id": "test1"}},
version="v1",
):
print(m)
asyncio.run(run())