-
Notifications
You must be signed in to change notification settings - Fork 1
/
agent.py
396 lines (343 loc) · 13.2 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
384
385
386
387
388
389
390
391
392
393
394
395
396
import operator
import os
import typing as t
from enum import Enum
from langchain_aws import ChatBedrock
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI
from langgraph.graph import END, START, StateGraph
from langgraph.graph.state import CompiledStateGraph
from langgraph.prebuilt import ToolNode
from prompts import PR_COMMENT_PROMPT, PR_FETCHER_PROMPT, REPO_ANALYZER_PROMPT
from tenacity import retry, stop_after_attempt, wait_exponential
from tools import DiffFormatter, get_pr_diff, get_pr_metadata
from langchain_core.runnables.graph import MermaidDrawMethod
from composio_langgraph import Action, App, ComposioToolSet, WorkspaceType
class Model(str, Enum):
CLAUDE = "claude"
OPENAI = "openai"
model = Model.CLAUDE
def print_graph(graph: CompiledStateGraph):
# Import necessary modules
import os
from io import BytesIO
from IPython.display import Image, display
from PIL import Image
# Generate the Mermaid PNG
png_data = graph.get_graph().draw_mermaid_png(
draw_method=MermaidDrawMethod.API,
)
# Create a PIL Image from the PNG data
image = Image.open(BytesIO(png_data))
# Save the image
output_path = "workflow_graph.png"
image.save(output_path)
def add_thought_to_request(request: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
request["thought"] = {
"type": "string",
"description": "Provide the thought of the agent in a small paragraph in concise way. This is a required field.",
"required": True,
}
return request
def pop_thought_from_request(request: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
request.pop("thought", None)
return request
def _github_pulls_create_review_comment_post_proc(response: dict) -> dict:
if response["successfull"]:
return {"message": "commented sucessfully"}
return {"error": response["error"]}
def _github_list_commits_post_proc(response: dict) -> dict:
if not response["successfull"]:
return {"error": response["error"]}
commits = []
for commit in response.get("data", {}).get("details", []):
commits.append(
{
"sha": commit["sha"],
"author": commit["commit"]["author"]["name"],
"message": commit["commit"]["message"],
"date": commit["commit"]["author"]["date"],
}
)
return {"commits": commits}
def _github_diff_post_proc(response: dict) -> dict:
if not response["successfull"]:
return {"error": response["error"]}
return {"diff": DiffFormatter(response["data"]["details"]).parse_and_format()}
def _github_get_a_pull_request_post_proc(response: dict):
if not response["successfull"]:
return {"error": response["error"]}
pr_content = response.get("data", {}).get("details", [])
contents = pr_content.split("\n\n---")
pr_content = ""
for i, content in enumerate(contents):
if "diff --git" in content:
index = content.index("diff --git")
content_filtered = content[:index]
if i != len(contents) - 1:
content_filtered += "\n".join(content.splitlines()[-4:])
else:
content_filtered = content
pr_content += content_filtered
return {
"details": pr_content,
"message": "PR content fetched successfully, proceed with getting the diff of PR or individual commits",
}
def _github_list_review_comments_on_a_pull_request_post_proc(response: dict) -> dict:
if not response["successfull"]:
return {"error": response["error"]}
comments = []
for comment in response.get("data", {}).get("details", []):
comments.append(
{
"diff_hunk": comment["diff_hunk"],
"commit_id": comment["commit_id"],
"body": comment["body"],
}
)
return {"comments": comments}
def get_graph(repo_path):
toolset = ComposioToolSet(
workspace_config=WorkspaceType.Host(),
metadata={
App.CODE_ANALYSIS_TOOL: {
"dir_to_index_path": repo_path,
"create_index": False
}
},
processors={
"pre": {
App.GITHUB: pop_thought_from_request,
App.FILETOOL: pop_thought_from_request,
App.CODE_ANALYSIS_TOOL: pop_thought_from_request,
},
"schema": {
App.GITHUB: add_thought_to_request,
App.FILETOOL: add_thought_to_request,
App.CODE_ANALYSIS_TOOL: add_thought_to_request,
},
"post": {
Action.GITHUB_CREATE_AN_ISSUE_COMMENT: _github_pulls_create_review_comment_post_proc,
Action.GITHUB_CREATE_A_REVIEW_COMMENT_FOR_A_PULL_REQUEST: _github_pulls_create_review_comment_post_proc,
Action.GITHUB_LIST_COMMITS_ON_A_PULL_REQUEST: _github_list_commits_post_proc,
Action.GITHUB_GET_A_COMMIT: _github_diff_post_proc,
Action.GITHUB_GET_A_PULL_REQUEST: _github_get_a_pull_request_post_proc,
Action.GITHUB_LIST_REVIEW_COMMENTS_ON_A_PULL_REQUEST: _github_list_review_comments_on_a_pull_request_post_proc,
},
},
)
fetch_pr_tools = [
*toolset.get_tools(
actions=[
Action.GITHUB_GET_A_PULL_REQUEST,
Action.GITHUB_LIST_COMMITS_ON_A_PULL_REQUEST,
Action.GITHUB_GET_A_COMMIT,
get_pr_diff,
get_pr_metadata,
]
)
]
repo_analyzer_tools = [
*toolset.get_tools(
actions=[
Action.CODE_ANALYSIS_TOOL_GET_CLASS_INFO,
Action.CODE_ANALYSIS_TOOL_GET_METHOD_BODY,
Action.CODE_ANALYSIS_TOOL_GET_METHOD_SIGNATURE,
# Action.FILETOOL_LIST_FILES,
Action.FILETOOL_OPEN_FILE,
Action.FILETOOL_SCROLL,
# Action.FILETOOL_FIND_FILE,
Action.FILETOOL_SEARCH_WORD,
]
)
]
comment_on_pr_tools = [
*toolset.get_tools(
actions=[
Action.GITHUB_GET_A_COMMIT,
Action.GITHUB_CREATE_A_REVIEW_COMMENT_FOR_A_PULL_REQUEST,
Action.GITHUB_CREATE_AN_ISSUE_COMMENT,
]
)
]
dummy_tools = toolset.get_tools(
actions=[
Action.FILETOOL_CHANGE_WORKING_DIRECTORY,
Action.FILETOOL_GIT_CLONE,
Action.CODE_ANALYSIS_TOOL_CREATE_CODE_MAP,
]
)
if model == Model.CLAUDE:
client = ChatBedrock(
# credentials_profile_name="default",
model_id="anthropic.claude-3-5-sonnet-20241022-v2:0",
region_name="us-west-2",
model_kwargs={"temperature": 0, "max_tokens": 8192},
)
else:
client = ChatOpenAI(
model="gpt-4-1106-preview",
temperature=0,
max_completion_tokens=4096,
api_key=os.environ["OPENAI_API_KEY"],
)
class AgentState(t.TypedDict):
messages: t.Annotated[t.Sequence[BaseMessage], operator.add]
sender: str
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10),
)
def invoke_with_retry(agent, state):
return agent.invoke(state)
def create_agent_node(agent, name):
def agent_node(state):
if model == Model.CLAUDE and isinstance(state["messages"][-1], AIMessage):
state["messages"].append(HumanMessage(content="Placeholder message"))
try:
result = invoke_with_retry(agent, state)
except Exception as e:
print(f"Failed to invoke agent after 3 attempts: {str(e)}")
result = AIMessage(
content="I apologize, but I encountered an error and couldn't complete the task. Please try again or rephrase your request.",
name=name,
)
if not isinstance(result, ToolMessage):
if isinstance(result, dict):
result_dict = result
else:
result_dict = result.dict()
result = AIMessage(
**{
k: v
for k, v in result_dict.items()
if k not in ["type", "name"]
},
name=name,
)
return {"messages": [result], "sender": name}
return agent_node
def create_agent(system_prompt, tools):
prompt = ChatPromptTemplate.from_messages(
[
("system", system_prompt),
MessagesPlaceholder(variable_name="messages"),
]
)
llm = client
if tools:
# return prompt | llm.bind_tools(tools)
return prompt | llm.bind_tools(tools)
else:
return prompt | llm
fetch_pr_agent_name = "Fetch-PR-Agent"
fetch_pr_agent = create_agent(PR_FETCHER_PROMPT, fetch_pr_tools)
fetch_pr_agent_node = create_agent_node(fetch_pr_agent, fetch_pr_agent_name)
repo_analyzer_agent_name = "Repo-Analyzer-Agent"
repo_analyzer_agent = create_agent(REPO_ANALYZER_PROMPT, repo_analyzer_tools)
repo_analyzer_agent_node = create_agent_node(
repo_analyzer_agent, repo_analyzer_agent_name
)
comment_on_pr_agent_name = "Comment-On-PR-Agent"
comment_on_pr_agent = create_agent(PR_COMMENT_PROMPT, comment_on_pr_tools)
comment_on_pr_agent_node = create_agent_node(
comment_on_pr_agent, comment_on_pr_agent_name
)
workflow = StateGraph(AgentState)
workflow.add_edge(START, fetch_pr_agent_name)
workflow.add_node(fetch_pr_agent_name, fetch_pr_agent_node)
workflow.add_node(repo_analyzer_agent_name, repo_analyzer_agent_node)
workflow.add_node(comment_on_pr_agent_name, comment_on_pr_agent_node)
workflow.add_node("fetch_pr_tools_node", ToolNode(fetch_pr_tools))
workflow.add_node("repo_analyzer_tools_node", ToolNode(repo_analyzer_tools))
workflow.add_node("comment_on_pr_tools_node", ToolNode(comment_on_pr_tools))
def fetch_pr_router(
state,
) -> t.Literal["fetch_pr_tools_node", "continue", "analyze_repo"]:
messages = state["messages"]
for message in reversed(messages):
if isinstance(message, AIMessage):
last_ai_message = message
break
else:
last_ai_message = messages[-1]
if last_ai_message.tool_calls:
return "fetch_pr_tools_node"
if "ANALYZE REPO" in last_ai_message.content:
return "analyze_repo"
return "continue"
workflow.add_conditional_edges(
"fetch_pr_tools_node",
lambda x: x["sender"],
{fetch_pr_agent_name: fetch_pr_agent_name},
)
workflow.add_conditional_edges(
fetch_pr_agent_name,
fetch_pr_router,
{
"continue": fetch_pr_agent_name,
"fetch_pr_tools_node": "fetch_pr_tools_node",
"analyze_repo": repo_analyzer_agent_name,
},
)
def repo_analyzer_router(
state,
) -> t.Literal["repo_analyzer_tools_node", "continue", "comment_on_pr"]:
messages = state["messages"]
for message in reversed(messages):
if isinstance(message, AIMessage):
last_ai_message = message
break
else:
last_ai_message = messages[-1]
if last_ai_message.tool_calls:
return "repo_analyzer_tools_node"
if "ANALYSIS COMPLETED" in last_ai_message.content:
return "comment_on_pr"
return "continue"
workflow.add_conditional_edges(
"repo_analyzer_tools_node",
lambda x: x["sender"],
{repo_analyzer_agent_name: repo_analyzer_agent_name},
)
workflow.add_conditional_edges(
repo_analyzer_agent_name,
repo_analyzer_router,
{
"continue": repo_analyzer_agent_name,
"repo_analyzer_tools_node": "repo_analyzer_tools_node",
"comment_on_pr": comment_on_pr_agent_name,
},
)
def comment_on_pr_router(
state,
) -> t.Literal["comment_on_pr_tools_node", "continue", "__end__"]:
messages = state["messages"]
for message in reversed(messages):
if isinstance(message, AIMessage):
last_ai_message = message
break
else:
last_ai_message = messages[-1]
if last_ai_message.tool_calls:
return "comment_on_pr_tools_node"
if "REVIEW COMPLETED" in last_ai_message.content:
return "__end__"
return "continue"
workflow.add_conditional_edges(
"comment_on_pr_tools_node",
lambda x: x["sender"],
{comment_on_pr_agent_name: comment_on_pr_agent_name},
)
workflow.add_conditional_edges(
comment_on_pr_agent_name,
comment_on_pr_router,
{
"continue": comment_on_pr_agent_name,
"comment_on_pr_tools_node": "comment_on_pr_tools_node",
"__end__": END,
},
)
graph = workflow.compile()
return graph, toolset