issue_definitions.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. import json
  2. import os
  3. import re
  4. from abc import ABC, abstractmethod
  5. from typing import Any, ClassVar
  6. import jinja2
  7. import requests
  8. from openhands.core.config import LLMConfig
  9. from openhands.core.logger import openhands_logger as logger
  10. from openhands.events.event import Event
  11. from openhands.llm.llm import LLM
  12. from openhands.resolver.github_issue import GithubIssue, ReviewThread
  13. class IssueHandlerInterface(ABC):
  14. issue_type: ClassVar[str]
  15. llm: LLM
  16. @abstractmethod
  17. def get_converted_issues(
  18. self, issue_numbers: list[int] | None = None, comment_id: int | None = None
  19. ) -> list[GithubIssue]:
  20. """Download issues from GitHub."""
  21. pass
  22. @abstractmethod
  23. def get_instruction(
  24. self,
  25. issue: GithubIssue,
  26. prompt_template: str,
  27. repo_instruction: str | None = None,
  28. ) -> tuple[str, list[str]]:
  29. """Generate instruction and image urls for the agent."""
  30. pass
  31. @abstractmethod
  32. def guess_success(
  33. self, issue: GithubIssue, history: list[Event]
  34. ) -> tuple[bool, list[bool] | None, str]:
  35. """Guess if the issue has been resolved based on the agent's output."""
  36. pass
  37. class IssueHandler(IssueHandlerInterface):
  38. issue_type: ClassVar[str] = 'issue'
  39. def __init__(self, owner: str, repo: str, token: str, llm_config: LLMConfig):
  40. self.download_url = 'https://api.github.com/repos/{}/{}/issues'
  41. self.owner = owner
  42. self.repo = repo
  43. self.token = token
  44. self.llm = LLM(llm_config)
  45. def _download_issues_from_github(self) -> list[Any]:
  46. url = self.download_url.format(self.owner, self.repo)
  47. headers = {
  48. 'Authorization': f'token {self.token}',
  49. 'Accept': 'application/vnd.github.v3+json',
  50. }
  51. params: dict[str, int | str] = {'state': 'open', 'per_page': 100, 'page': 1}
  52. all_issues = []
  53. # Get issues, page by page
  54. while True:
  55. response = requests.get(url, headers=headers, params=params)
  56. response.raise_for_status()
  57. issues = response.json()
  58. # No more issues, break the loop
  59. if not issues:
  60. break
  61. # Sanity check - the response is a list of dictionaries
  62. if not isinstance(issues, list) or any(
  63. [not isinstance(issue, dict) for issue in issues]
  64. ):
  65. raise ValueError('Expected list of dictionaries from Github API.')
  66. # Add the issues to the final list
  67. all_issues.extend(issues)
  68. assert isinstance(params['page'], int)
  69. params['page'] += 1
  70. return all_issues
  71. def _extract_image_urls(self, issue_body: str) -> list[str]:
  72. # Regular expression to match Markdown image syntax ![alt text](image_url)
  73. image_pattern = r'!\[.*?\]\((https?://[^\s)]+)\)'
  74. return re.findall(image_pattern, issue_body)
  75. def _extract_issue_references(self, body: str) -> list[int]:
  76. # First, remove code blocks as they may contain false positives
  77. body = re.sub(r'```.*?```', '', body, flags=re.DOTALL)
  78. # Remove inline code
  79. body = re.sub(r'`[^`]*`', '', body)
  80. # Remove URLs that contain hash symbols
  81. body = re.sub(r'https?://[^\s)]*#\d+[^\s)]*', '', body)
  82. # Now extract issue numbers, making sure they're not part of other text
  83. # The pattern matches #number that:
  84. # 1. Is at the start of text or after whitespace/punctuation
  85. # 2. Is followed by whitespace, punctuation, or end of text
  86. # 3. Is not part of a URL
  87. pattern = r'(?:^|[\s\[({]|[^\w#])#(\d+)(?=[\s,.\])}]|$)'
  88. return [int(match) for match in re.findall(pattern, body)]
  89. def _get_issue_comments(
  90. self, issue_number: int, comment_id: int | None = None
  91. ) -> list[str] | None:
  92. """Retrieve comments for a specific issue from Github.
  93. Args:
  94. issue_number: The ID of the issue to get comments for
  95. comment_id: The ID of a single comment, if provided, otherwise all comments
  96. """
  97. url = f'https://api.github.com/repos/{self.owner}/{self.repo}/issues/{issue_number}/comments'
  98. headers = {
  99. 'Authorization': f'token {self.token}',
  100. 'Accept': 'application/vnd.github.v3+json',
  101. }
  102. params = {'per_page': 100, 'page': 1}
  103. all_comments = []
  104. # Get comments, page by page
  105. while True:
  106. response = requests.get(url, headers=headers, params=params)
  107. response.raise_for_status()
  108. comments = response.json()
  109. if not comments:
  110. break
  111. # If a single comment ID is provided, return only that comment
  112. if comment_id:
  113. matching_comment = next(
  114. (
  115. comment['body']
  116. for comment in comments
  117. if comment['id'] == comment_id
  118. ),
  119. None,
  120. )
  121. if matching_comment:
  122. return [matching_comment]
  123. else:
  124. # Otherwise, return all comments
  125. all_comments.extend([comment['body'] for comment in comments])
  126. params['page'] += 1
  127. return all_comments if all_comments else None
  128. def get_converted_issues(
  129. self, issue_numbers: list[int] | None = None, comment_id: int | None = None
  130. ) -> list[GithubIssue]:
  131. """Download issues from Github.
  132. Args:
  133. issue_numbers: The numbers of the issues to download
  134. comment_id: The ID of a single comment, if provided, otherwise all comments
  135. Returns:
  136. List of Github issues.
  137. """
  138. if not issue_numbers:
  139. raise ValueError('Unspecified issue number')
  140. all_issues = self._download_issues_from_github()
  141. logger.info(f'Limiting resolving to issues {issue_numbers}.')
  142. all_issues = [
  143. issue
  144. for issue in all_issues
  145. if issue['number'] in issue_numbers and 'pull_request' not in issue
  146. ]
  147. if len(issue_numbers) == 1 and not all_issues:
  148. raise ValueError(f'Issue {issue_numbers[0]} not found')
  149. converted_issues = []
  150. for issue in all_issues:
  151. # Check for required fields (number and title)
  152. if any([issue.get(key) is None for key in ['number', 'title']]):
  153. logger.warning(
  154. f'Skipping issue {issue} as it is missing number or title.'
  155. )
  156. continue
  157. # Handle empty body by using empty string
  158. if issue.get('body') is None:
  159. issue['body'] = ''
  160. # Get issue thread comments
  161. thread_comments = self._get_issue_comments(
  162. issue['number'], comment_id=comment_id
  163. )
  164. # Convert empty lists to None for optional fields
  165. issue_details = GithubIssue(
  166. owner=self.owner,
  167. repo=self.repo,
  168. number=issue['number'],
  169. title=issue['title'],
  170. body=issue['body'],
  171. thread_comments=thread_comments,
  172. review_comments=None, # Initialize review comments as None for regular issues
  173. )
  174. converted_issues.append(issue_details)
  175. return converted_issues
  176. def get_instruction(
  177. self,
  178. issue: GithubIssue,
  179. prompt_template: str,
  180. repo_instruction: str | None = None,
  181. ) -> tuple[str, list[str]]:
  182. """Generate instruction for the agent.
  183. Args:
  184. issue: The issue to generate instruction for
  185. prompt_template: The prompt template to use
  186. repo_instruction: The repository instruction if it exists
  187. """
  188. # Format thread comments if they exist
  189. thread_context = ''
  190. if issue.thread_comments:
  191. thread_context = '\n\nIssue Thread Comments:\n' + '\n---\n'.join(
  192. issue.thread_comments
  193. )
  194. # Extract image URLs from the issue body and thread comments
  195. images = []
  196. images.extend(self._extract_image_urls(issue.body))
  197. images.extend(self._extract_image_urls(thread_context))
  198. template = jinja2.Template(prompt_template)
  199. return (
  200. template.render(
  201. body=issue.title + '\n\n' + issue.body + thread_context,
  202. repo_instruction=repo_instruction,
  203. ),
  204. images,
  205. )
  206. def guess_success(
  207. self, issue: GithubIssue, history: list[Event]
  208. ) -> tuple[bool, None | list[bool], str]:
  209. """Guess if the issue is fixed based on the history and the issue description.
  210. Args:
  211. issue: The issue to check
  212. history: The agent's history
  213. """
  214. last_message = history[-1].message
  215. # Include thread comments in the prompt if they exist
  216. issue_context = issue.body
  217. if issue.thread_comments:
  218. issue_context += '\n\nIssue Thread Comments:\n' + '\n---\n'.join(
  219. issue.thread_comments
  220. )
  221. # Prepare the prompt
  222. with open(
  223. os.path.join(
  224. os.path.dirname(__file__),
  225. 'prompts/guess_success/issue-success-check.jinja',
  226. ),
  227. 'r',
  228. ) as f:
  229. template = jinja2.Template(f.read())
  230. prompt = template.render(issue_context=issue_context, last_message=last_message)
  231. # Get the LLM response and check for 'success' and 'explanation' in the answer
  232. response = self.llm.completion(messages=[{'role': 'user', 'content': prompt}])
  233. answer = response.choices[0].message.content.strip()
  234. pattern = r'--- success\n*(true|false)\n*--- explanation*\n((?:.|\n)*)'
  235. match = re.search(pattern, answer)
  236. if match:
  237. return match.group(1).lower() == 'true', None, match.group(2)
  238. return False, None, f'Failed to decode answer from LLM response: {answer}'
  239. class PRHandler(IssueHandler):
  240. issue_type: ClassVar[str] = 'pr'
  241. def __init__(self, owner: str, repo: str, token: str, llm_config: LLMConfig):
  242. super().__init__(owner, repo, token, llm_config)
  243. self.download_url = 'https://api.github.com/repos/{}/{}/pulls'
  244. def __download_pr_metadata(
  245. self, pull_number: int, comment_id: int | None = None
  246. ) -> tuple[list[str], list[int], list[str], list[ReviewThread], list[str]]:
  247. """Run a GraphQL query against the GitHub API for information.
  248. Retrieves information about:
  249. 1. unresolved review comments
  250. 2. referenced issues the pull request would close
  251. Args:
  252. pull_number: The number of the pull request to query.
  253. comment_id: Optional ID of a specific comment to focus on.
  254. query: The GraphQL query as a string.
  255. variables: A dictionary of variables for the query.
  256. token: Your GitHub personal access token.
  257. Returns:
  258. The JSON response from the GitHub API.
  259. """
  260. # Using graphql as REST API doesn't indicate resolved status for review comments
  261. # TODO: grabbing the first 10 issues, 100 review threads, and 100 coments; add pagination to retrieve all
  262. query = """
  263. query($owner: String!, $repo: String!, $pr: Int!) {
  264. repository(owner: $owner, name: $repo) {
  265. pullRequest(number: $pr) {
  266. closingIssuesReferences(first: 10) {
  267. edges {
  268. node {
  269. body
  270. number
  271. }
  272. }
  273. }
  274. url
  275. reviews(first: 100) {
  276. nodes {
  277. body
  278. state
  279. fullDatabaseId
  280. }
  281. }
  282. reviewThreads(first: 100) {
  283. edges{
  284. node{
  285. id
  286. isResolved
  287. comments(first: 100) {
  288. totalCount
  289. nodes {
  290. body
  291. path
  292. fullDatabaseId
  293. }
  294. }
  295. }
  296. }
  297. }
  298. }
  299. }
  300. }
  301. """
  302. variables = {'owner': self.owner, 'repo': self.repo, 'pr': pull_number}
  303. # Run the query
  304. url = 'https://api.github.com/graphql'
  305. headers = {
  306. 'Authorization': f'Bearer {self.token}',
  307. 'Content-Type': 'application/json',
  308. }
  309. response = requests.post(
  310. url, json={'query': query, 'variables': variables}, headers=headers
  311. )
  312. response.raise_for_status()
  313. response_json = response.json()
  314. # Parse the response to get closing issue references and unresolved review comments
  315. pr_data = (
  316. response_json.get('data', {}).get('repository', {}).get('pullRequest', {})
  317. )
  318. # Get closing issues
  319. closing_issues = pr_data.get('closingIssuesReferences', {}).get('edges', [])
  320. closing_issues_bodies = [issue['node']['body'] for issue in closing_issues]
  321. closing_issue_numbers = [
  322. issue['node']['number'] for issue in closing_issues
  323. ] # Extract issue numbers
  324. # Get review comments
  325. reviews = pr_data.get('reviews', {}).get('nodes', [])
  326. if comment_id is not None:
  327. reviews = [
  328. review
  329. for review in reviews
  330. if int(review['fullDatabaseId']) == comment_id
  331. ]
  332. review_bodies = [review['body'] for review in reviews]
  333. # Get unresolved review threads
  334. review_threads = []
  335. thread_ids = [] # Store thread IDs; agent replies to the thread
  336. raw_review_threads = pr_data.get('reviewThreads', {}).get('edges', [])
  337. for thread in raw_review_threads:
  338. node = thread.get('node', {})
  339. if not node.get(
  340. 'isResolved', True
  341. ): # Check if the review thread is unresolved
  342. id = node.get('id')
  343. thread_contains_comment_id = False
  344. my_review_threads = node.get('comments', {}).get('nodes', [])
  345. message = ''
  346. files = []
  347. for i, review_thread in enumerate(my_review_threads):
  348. if (
  349. comment_id is not None
  350. and int(review_thread['fullDatabaseId']) == comment_id
  351. ):
  352. thread_contains_comment_id = True
  353. if (
  354. i == len(my_review_threads) - 1
  355. ): # Check if it's the last thread in the thread
  356. if len(my_review_threads) > 1:
  357. message += '---\n' # Add "---" before the last message if there's more than one thread
  358. message += 'latest feedback:\n' + review_thread['body'] + '\n'
  359. else:
  360. message += (
  361. review_thread['body'] + '\n'
  362. ) # Add each thread in a new line
  363. # Source files on which the comments were made
  364. file = review_thread.get('path')
  365. if file and file not in files:
  366. files.append(file)
  367. # If the comment ID is not provided or the thread contains the comment ID, add the thread to the list
  368. if comment_id is None or thread_contains_comment_id:
  369. unresolved_thread = ReviewThread(comment=message, files=files)
  370. review_threads.append(unresolved_thread)
  371. thread_ids.append(id)
  372. return (
  373. closing_issues_bodies,
  374. closing_issue_numbers,
  375. review_bodies,
  376. review_threads,
  377. thread_ids,
  378. )
  379. # Override processing of downloaded issues
  380. def _get_pr_comments(
  381. self, pr_number: int, comment_id: int | None = None
  382. ) -> list[str] | None:
  383. """Download comments for a specific pull request from Github."""
  384. url = f'https://api.github.com/repos/{self.owner}/{self.repo}/issues/{pr_number}/comments'
  385. headers = {
  386. 'Authorization': f'token {self.token}',
  387. 'Accept': 'application/vnd.github.v3+json',
  388. }
  389. params = {'per_page': 100, 'page': 1}
  390. all_comments = []
  391. while True:
  392. response = requests.get(url, headers=headers, params=params)
  393. response.raise_for_status()
  394. comments = response.json()
  395. if not comments:
  396. break
  397. if comment_id is not None:
  398. matching_comment = next(
  399. (
  400. comment['body']
  401. for comment in comments
  402. if comment['id'] == comment_id
  403. ),
  404. None,
  405. )
  406. if matching_comment:
  407. return [matching_comment]
  408. else:
  409. all_comments.extend([comment['body'] for comment in comments])
  410. params['page'] += 1
  411. return all_comments if all_comments else None
  412. def __get_context_from_external_issues_references(
  413. self,
  414. closing_issues: list[str],
  415. closing_issue_numbers: list[int],
  416. issue_body: str,
  417. review_comments: list[str],
  418. review_threads: list[ReviewThread],
  419. thread_comments: list[str] | None,
  420. ):
  421. new_issue_references = []
  422. if issue_body:
  423. new_issue_references.extend(self._extract_issue_references(issue_body))
  424. if review_comments:
  425. for comment in review_comments:
  426. new_issue_references.extend(self._extract_issue_references(comment))
  427. if review_threads:
  428. for review_thread in review_threads:
  429. new_issue_references.extend(
  430. self._extract_issue_references(review_thread.comment)
  431. )
  432. if thread_comments:
  433. for thread_comment in thread_comments:
  434. new_issue_references.extend(
  435. self._extract_issue_references(thread_comment)
  436. )
  437. non_duplicate_references = set(new_issue_references)
  438. unique_issue_references = non_duplicate_references.difference(
  439. closing_issue_numbers
  440. )
  441. for issue_number in unique_issue_references:
  442. try:
  443. url = f'https://api.github.com/repos/{self.owner}/{self.repo}/issues/{issue_number}'
  444. headers = {
  445. 'Authorization': f'Bearer {self.token}',
  446. 'Accept': 'application/vnd.github.v3+json',
  447. }
  448. response = requests.get(url, headers=headers)
  449. response.raise_for_status()
  450. issue_data = response.json()
  451. issue_body = issue_data.get('body', '')
  452. if issue_body:
  453. closing_issues.append(issue_body)
  454. except requests.exceptions.RequestException as e:
  455. logger.warning(f'Failed to fetch issue {issue_number}: {str(e)}')
  456. return closing_issues
  457. def get_converted_issues(
  458. self, issue_numbers: list[int] | None = None, comment_id: int | None = None
  459. ) -> list[GithubIssue]:
  460. if not issue_numbers:
  461. raise ValueError('Unspecified issue numbers')
  462. all_issues = self._download_issues_from_github()
  463. logger.info(f'Limiting resolving to issues {issue_numbers}.')
  464. all_issues = [issue for issue in all_issues if issue['number'] in issue_numbers]
  465. converted_issues = []
  466. for issue in all_issues:
  467. # For PRs, body can be None
  468. if any([issue.get(key) is None for key in ['number', 'title']]):
  469. logger.warning(f'Skipping #{issue} as it is missing number or title.')
  470. continue
  471. # Handle None body for PRs
  472. body = issue.get('body') if issue.get('body') is not None else ''
  473. (
  474. closing_issues,
  475. closing_issues_numbers,
  476. review_comments,
  477. review_threads,
  478. thread_ids,
  479. ) = self.__download_pr_metadata(issue['number'], comment_id=comment_id)
  480. head_branch = issue['head']['ref']
  481. # Get PR thread comments
  482. thread_comments = self._get_pr_comments(
  483. issue['number'], comment_id=comment_id
  484. )
  485. closing_issues = self.__get_context_from_external_issues_references(
  486. closing_issues,
  487. closing_issues_numbers,
  488. body,
  489. review_comments,
  490. review_threads,
  491. thread_comments,
  492. )
  493. issue_details = GithubIssue(
  494. owner=self.owner,
  495. repo=self.repo,
  496. number=issue['number'],
  497. title=issue['title'],
  498. body=body,
  499. closing_issues=closing_issues,
  500. review_comments=review_comments,
  501. review_threads=review_threads,
  502. thread_ids=thread_ids,
  503. head_branch=head_branch,
  504. thread_comments=thread_comments,
  505. )
  506. converted_issues.append(issue_details)
  507. return converted_issues
  508. def get_instruction(
  509. self,
  510. issue: GithubIssue,
  511. prompt_template: str,
  512. repo_instruction: str | None = None,
  513. ) -> tuple[str, list[str]]:
  514. """Generate instruction for the agent."""
  515. template = jinja2.Template(prompt_template)
  516. images = []
  517. issues_str = None
  518. if issue.closing_issues:
  519. issues_str = json.dumps(issue.closing_issues, indent=4)
  520. images.extend(self._extract_image_urls(issues_str))
  521. # Handle PRs with review comments
  522. review_comments_str = None
  523. if issue.review_comments:
  524. review_comments_str = json.dumps(issue.review_comments, indent=4)
  525. images.extend(self._extract_image_urls(review_comments_str))
  526. # Handle PRs with file-specific review comments
  527. review_thread_str = None
  528. review_thread_file_str = None
  529. if issue.review_threads:
  530. review_threads = [
  531. review_thread.comment for review_thread in issue.review_threads
  532. ]
  533. review_thread_files = []
  534. for review_thread in issue.review_threads:
  535. review_thread_files.extend(review_thread.files)
  536. review_thread_str = json.dumps(review_threads, indent=4)
  537. review_thread_file_str = json.dumps(review_thread_files, indent=4)
  538. images.extend(self._extract_image_urls(review_thread_str))
  539. # Format thread comments if they exist
  540. thread_context = ''
  541. if issue.thread_comments:
  542. thread_context = '\n---\n'.join(issue.thread_comments)
  543. images.extend(self._extract_image_urls(thread_context))
  544. instruction = template.render(
  545. issues=issues_str,
  546. review_comments=review_comments_str,
  547. review_threads=review_thread_str,
  548. files=review_thread_file_str,
  549. thread_context=thread_context,
  550. repo_instruction=repo_instruction,
  551. )
  552. return instruction, images
  553. def _check_feedback_with_llm(self, prompt: str) -> tuple[bool, str]:
  554. """Helper function to check feedback with LLM and parse response."""
  555. response = self.llm.completion(messages=[{'role': 'user', 'content': prompt}])
  556. answer = response.choices[0].message.content.strip()
  557. pattern = r'--- success\n*(true|false)\n*--- explanation*\n((?:.|\n)*)'
  558. match = re.search(pattern, answer)
  559. if match:
  560. return match.group(1).lower() == 'true', match.group(2).strip()
  561. return False, f'Failed to decode answer from LLM response: {answer}'
  562. def _check_review_thread(
  563. self,
  564. review_thread: ReviewThread,
  565. issues_context: str,
  566. last_message: str,
  567. ) -> tuple[bool, str]:
  568. """Check if a review thread's feedback has been addressed."""
  569. files_context = json.dumps(review_thread.files, indent=4)
  570. with open(
  571. os.path.join(
  572. os.path.dirname(__file__),
  573. 'prompts/guess_success/pr-feedback-check.jinja',
  574. ),
  575. 'r',
  576. ) as f:
  577. template = jinja2.Template(f.read())
  578. prompt = template.render(
  579. issue_context=issues_context,
  580. feedback=review_thread.comment,
  581. files_context=files_context,
  582. last_message=last_message,
  583. )
  584. return self._check_feedback_with_llm(prompt)
  585. def _check_thread_comments(
  586. self,
  587. thread_comments: list[str],
  588. issues_context: str,
  589. last_message: str,
  590. ) -> tuple[bool, str]:
  591. """Check if thread comments feedback has been addressed."""
  592. thread_context = '\n---\n'.join(thread_comments)
  593. with open(
  594. os.path.join(
  595. os.path.dirname(__file__), 'prompts/guess_success/pr-thread-check.jinja'
  596. ),
  597. 'r',
  598. ) as f:
  599. template = jinja2.Template(f.read())
  600. prompt = template.render(
  601. issue_context=issues_context,
  602. thread_context=thread_context,
  603. last_message=last_message,
  604. )
  605. return self._check_feedback_with_llm(prompt)
  606. def _check_review_comments(
  607. self,
  608. review_comments: list[str],
  609. issues_context: str,
  610. last_message: str,
  611. ) -> tuple[bool, str]:
  612. """Check if review comments feedback has been addressed."""
  613. review_context = '\n---\n'.join(review_comments)
  614. with open(
  615. os.path.join(
  616. os.path.dirname(__file__), 'prompts/guess_success/pr-review-check.jinja'
  617. ),
  618. 'r',
  619. ) as f:
  620. template = jinja2.Template(f.read())
  621. prompt = template.render(
  622. issue_context=issues_context,
  623. review_context=review_context,
  624. last_message=last_message,
  625. )
  626. return self._check_feedback_with_llm(prompt)
  627. def guess_success(
  628. self, issue: GithubIssue, history: list[Event]
  629. ) -> tuple[bool, None | list[bool], str]:
  630. """Guess if the issue is fixed based on the history and the issue description."""
  631. last_message = history[-1].message
  632. issues_context = json.dumps(issue.closing_issues, indent=4)
  633. success_list = []
  634. explanation_list = []
  635. # Handle PRs with file-specific review comments
  636. if issue.review_threads:
  637. for review_thread in issue.review_threads:
  638. if issues_context and last_message:
  639. success, explanation = self._check_review_thread(
  640. review_thread, issues_context, last_message
  641. )
  642. else:
  643. success, explanation = False, 'Missing context or message'
  644. success_list.append(success)
  645. explanation_list.append(explanation)
  646. # Handle PRs with only thread comments (no file-specific review comments)
  647. elif issue.thread_comments:
  648. if issue.thread_comments and issues_context and last_message:
  649. success, explanation = self._check_thread_comments(
  650. issue.thread_comments, issues_context, last_message
  651. )
  652. else:
  653. success, explanation = (
  654. False,
  655. 'Missing thread comments, context or message',
  656. )
  657. success_list.append(success)
  658. explanation_list.append(explanation)
  659. elif issue.review_comments:
  660. # Handle PRs with only review comments (no file-specific review comments or thread comments)
  661. if issue.review_comments and issues_context and last_message:
  662. success, explanation = self._check_review_comments(
  663. issue.review_comments, issues_context, last_message
  664. )
  665. else:
  666. success, explanation = (
  667. False,
  668. 'Missing review comments, context or message',
  669. )
  670. success_list.append(success)
  671. explanation_list.append(explanation)
  672. else:
  673. # No review comments, thread comments, or file-level review comments found
  674. return False, None, 'No feedback was found to process'
  675. # Return overall success (all must be true) and explanations
  676. if not success_list:
  677. return False, None, 'No feedback was processed'
  678. return all(success_list), success_list, json.dumps(explanation_list)