Elffuss BraidHub

kikocis/auto-code-rover public

main · 18.0 KiBRawPermalink
1import json
2import os
3import time
4from os.path import join as pjoin
5from pathlib import Path
6
7from app import utils as app_utils
8from app.log import log_and_print
9from app.raw_tasks import PlainTask, RawTask
10
11
12class RawGithubTask_for_debug(RawTask):
13 """
14 Encapsulate everything required to run ACR on a fresh issue from the internet.
15
16 For debug / dev: github limits the calling times of api. Therefore when
17 debuging, use the hardcode task:
18 self.clone_link = 'https://github.com/langchain-ai/langchain.git'
19 self.commit_hash = 'cb6e5e5'
20 self.issue_link = 'https://github.com/langchain-ai/langchain/issues/20453'
21 self.problem_statement: refer to the implementation of fetch_github_issue function
22 """
23
24 def __init__(
25 self,
26 task_id: str,
27 clone_link: str,
28 commit_hash: str,
29 issue_link: str,
30 setup_dir: str,
31 ):
32 self._task_id = task_id
33 self.clone_link = "https://github.com/langchain-ai/langchain.git"
34 self.commit_hash = "cb6e5e5"
35 self.issue_link = "https://github.com/langchain-ai/langchain/issues/20453"
36 self.setup_dir = setup_dir
37 self.clone_path = pjoin(self.setup_dir, self.task_id)
38 self.problem_statement, self.created_at = self.fetch_issue()
39 self.clone_repo()
40
41 @property
42 def task_id(self) -> str:
43 return self._task_id
44
45 def clone_repo(self):
46 clone_path = Path(self.clone_path)
47 if os.path.exists(clone_path):
48 return # Dev/Debug mode
49 app_utils.clone_repo(self.clone_link, str(clone_path.parent), clone_path.name)
50 log_and_print(f"Cloned source code to {clone_path}.")
51
52 def dump_meta_data(self, output_dir: str):
53 meta = {
54 "task_info": {
55 "base_commit": self.commit_hash,
56 "created_at": self.created_at,
57 "problem_statement": self.problem_statement,
58 "instance_id": self.task_id,
59 },
60 "setup_info": {
61 "repo_path": self.clone_path,
62 },
63 }
64
65 meta_file = pjoin(output_dir, "meta.json")
66
67 with open(meta_file, "w") as f:
68 json.dump(meta, f, indent=4)
69
70 def fetch_issue(self):
71 if "github.com" not in self.issue_link:
72 raise NotImplementedError("Only GitHub issues are supported for now.")
73
74 retrieved_issue = self.fetch_github_issue(self.issue_link)
75
76 if retrieved_issue is None:
77 raise RuntimeError(
78 f"Failed to retrieve issue information from {self.issue_link}"
79 )
80
81 title, body, created_at = retrieved_issue
82
83 problem_statement = f"{title}\n{body}"
84
85 return problem_statement, created_at
86
87 @classmethod
88 def fetch_github_issue(cls, issue_url: str) -> tuple[str, str, str]:
89 """Extract owner, repo, and issue number from the URL"""
90
91 title = """`PaiEasChatEndpoint._call_eas` should return `bytes` type instead of `str` type"""
92 body = """
93### Checked other resources
94
95- [X] I added a very descriptive title to this issue.
96- [X] I searched the LangChain documentation with the integrated search.
97- [X] I used the GitHub search to find a similar question and didn't find it.
98- [X] I am sure that this is a bug in LangChain rather than my code.
99- [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).
100
101### Example Code
102
103```python
104from langchain_community.chat_models import PaiEasChatEndpoint
105from langchain_core.prompts import ChatPromptTemplate
106
107prompt = ChatPromptTemplate.from_template("tell me a short joke about {topic}")
108prompt_value = prompt.invoke("test_message")
109
110eas_chat_endpoint = PaiEasChatEndpoint(
111 eas_service_url="your_service_url",
112 eas_service_token="your_service_token"
113)
114eas_chat_endpoint._call(prompt_value.messages)
115```
116
117It is just example code that has a potential error, so I'll explain why it's a possible type error in the description.
118
119### Error Message and Stack Trace (if applicable)
120
121_No response_
122
123### Description
124
125https://github.com/langchain-ai/langchain/blob/b66a4f48fa5656871c3e849f7e1790dfb5a4c56b/libs/community/langchain_community/chat_models/pai_eas_endpoint.py#L193-L230
126
127In the method `PaiEasChatEndpoint._call` at line 203, `self._call_eas(request_payload)` returns `str` type because it returns response.text at line 230 (https://requests.readthedocs.io/en/latest/api/#requests.Response.text).
128Then, first argument of `_format_response_payload` can be `str` type at line 204, resulting in type mismatch.
129
130https://github.com/langchain-ai/langchain/blob/b66a4f48fa5656871c3e849f7e1790dfb5a4c56b/libs/community/langchain_community/chat_models/pai_eas_endpoint.py#L167-L179
131
132Moreover, if `JSONDecodeError` occurs in this method, then attribute error occurs at line 178 (`AttributeError: 'str' object has no attribute 'decode'`) because `output` variable is str type.
133I think `PaiEasChatEndpoint._call_eas` should be fixed to return bytes type.
134If I'm mistaken, I'd appreciate it if you could let me know.
135
136### System Info
137
138System Information
139------------------
140> OS: Linux
141> OS Version: #190-Ubuntu SMP Fri Feb 2 23:24:22 UTC 2024
142> Python Version: 3.9.18 (main, Feb 13 2024, 14:37:08)
143[GCC 9.4.0]
144
145Package Information
146-------------------
147> langchain_core: 0.1.42
148> langchain: 0.1.16
149> langchain_community: 0.0.32
150> langsmith: 0.1.47
151> langchain_text_splitters: 0.0.1
152
153Packages not installed (Not Necessarily a Problem)
154--------------------------------------------------
155The following packages were not found:
156
157> langgraph
158> langserve
159"""
160 created_at = """2024-04-15T07:47:06Z"""
161
162 return title, body, created_at
163
164 def to_task(self) -> PlainTask:
165 return PlainTask(
166 commit_hash=self.commit_hash,
167 local_path=self.clone_path,
168 problem_statement=self.problem_statement,
169 )
170
171
172test_data = [
173 {
174 "title": "AutoCodeRover (context retrieval round 0)",
175 "category": "auto_code_rover",
176 "message": """Based on the files, classes, methods, and code statements from the issue related to the bug, you can use the following search APIs to get more context of the project.
177- search_class(class_name: str): Search for a class in the codebase
178- search_method_in_file(method_name: str, file_path: str): Search for a method in a given file
179- search_method_in_class(method_name: str, class_name: str): Search for a method in a given class
180- search_method(method_name: str): Search for a method in the entire codebase
181- search_code(code_str: str): Search for a code snippet in the entire codebase
182- search_code_in_file(code_str: str, file_path: str): Search for a code snippet in a given file file
183
184Note that you can use multiple search APIs in one round.
185
186Now analyze the issue and select necessary APIs to get more context of the project. Each API call must have concrete arguments as inputs.""",
187 },
188 {
189 "title": "Context Retrieval Agent (round 0)",
190 "category": "context_retrieval_agent",
191 "message": """I will start by searching for the `PaiEasChatEndpoint` class to understand its structure and methods. Then, I will search for the `_call_eas` method within this class to investigate its implementation.
192
1931. `search_class("PaiEasChatEndpoint")`
1942. `search_method_in_class("_call_eas", "PaiEasChatEndpoint")`""",
195 },
196 {
197 "title": "AutoCodeRover (Agent-selected API calls)",
198 "category": "auto_code_rover",
199 "message": """
200 API calls:
201
202- `search_class('PaiEasChatEndpoint')`
203
204- `search_method_in_class('_call_eas', 'PaiEasChatEndpoint')`
205 """,
206 },
207 {
208 "title": "AutoCodeRover (context retrieval round 0)",
209 "category": "auto_code_rover",
210 "message": '''
211 Result of search_class('PaiEasChatEndpoint'):
212
213Found 1 classes with name PaiEasChatEndpoint in the codebase:
214
215- Search result 1:
216```
217<file>libs/community/langchain_community/chat_models/pai_eas_endpoint.py</file>
218<class>PaiEasChatEndpoint</class>
219<code>
220class PaiEasChatEndpoint(BaseChatModel):
221@root_validator()
222def validate_environment(cls, values: Dict) -> Dict:
223@property
224def _identifying_params(self) -> Dict[str, Any]:
225@property
226def _llm_type(self) -> str:
227@property
228def _default_params(self) -> Dict[str, Any]:
229def _invocation_params(
230self, stop_sequences: Optional[List[str]], **kwargs: Any
231) -> dict:
232def format_request_payload(
233self, messages: List[BaseMessage], **model_kwargs: Any
234) -> dict:
235def _format_response_payload(
236self, output: bytes, stop_sequences: Optional[List[str]]
237) -> str:
238def _generate(
239self,
240messages: List[BaseMessage],
241stop: Optional[List[str]] = None,
242run_manager: Optional[CallbackManagerForLLMRun] = None,
243**kwargs: Any,
244) -> ChatResult:
245def _call(
246self,
247messages: List[BaseMessage],
248stop: Optional[List[str]] = None,
249run_manager: Optional[CallbackManagerForLLMRun] = None,
250**kwargs: Any,
251) -> str:
252def _call_eas(self, query_body: dict) -> Any:
253def _call_eas_stream(self, query_body: dict) -> Any:
254def _convert_chunk_to_message_message(
255self,
256chunk: str,
257) -> AIMessageChunk:
258
259</code>
260```
261
262
263Result of search_method_in_class('_call_eas', 'PaiEasChatEndpoint'):
264
265Found 1 methods with name _call_eas in class PaiEasChatEndpoint:
266
267- Search result 1:
268```
269<file>libs/community/langchain_community/chat_models/pai_eas_endpoint.py</file>
270<class>PaiEasChatEndpoint</class> <func>_call_eas</func>
271<code>
272def _call_eas(self, query_body: dict) -> Any:
273"""Generate text from the eas service."""
274headers = {
275"Content-Type": "application/json",
276"Accept": "application/json",
277"Authorization": f"{self.eas_service_token}",
278}
279
280# make request
281response = requests.post(
282self.eas_service_url, headers=headers, json=query_body, timeout=self.timeout
283)
284
285if response.status_code != 200:
286raise Exception(
287f"Request failed with status code {response.status_code}"
288f" and message {response.text}"
289)
290
291return response.text
292
293</code>
294```
295 ''',
296 },
297 {
298 "title": "Context Retrieval Agent (round 0)",
299 "category": "auto_code_rover",
300 "message": """Let's analyze collected context first""",
301 },
302 {
303 "title": "AutoCodeRover (context retrieval round 0)",
304 "category": "context_retrieval_agent",
305 "message": """Based on the search results, here is the analysis of the `PaiEasChatEndpoint` class and the `_call_eas` method:
306
3071. **PaiEasChatEndpoint Class**:
308- The `PaiEasChatEndpoint` class is defined in the file `libs/community/langchain_community/chat_models/pai_eas_endpoint.py`.
309- It inherits from `BaseChatModel`.
310- The class contains various methods such as `_invocation_params`, `format_request_payload`, `_format_response_payload`, `_generate`, `_call`, `_call_eas`, `_call_eas_stream`, and `_convert_chunk_to_message_message`.
311- The `_call` method is the one that calls the `_call_eas` method and currently returns a `str` type.
312
3132. **_call_eas Method**:
314- The `_call_eas` method is responsible for generating text from the EAS service.
315- It takes a `query_body` parameter of type `dict`.
316- It makes a POST request to the EAS service using the provided URL, headers, and query body.
317- If the request fails (status code other than 200), it raises an exception with the status code and response message.
318- Currently, the method returns the response text as a `str`.
319
320Based on this analysis, the issue is indeed related to the `_call_eas` method returning a `str` type instead of `bytes`, which leads to a type mismatch in the `_call` method. The fix involves modifying the `_call_eas` method to return `bytes` instead of `str`.""",
321 },
322 {
323 "title": "AutoCodeRover (context retrieval round 0)",
324 "category": "auto_code_rover",
325 "message": """Based on your analysis, answer below questions:
326- do we need more context: construct search API calls to get more context of the project. (leave it empty if you don't need more context)
327- where are bug locations: buggy files and methods. (leave it empty if you don't have enough information)""",
328 },
329 {
330 "title": "AutoCodeRover (context retrieval round 0)",
331 "category": "auto_code_rover",
332 "message": """
333 Based on the files, classes, methods, and code statements from the issue related to the bug, you can use the following search APIs to get more context of the project.
334- search_class(class_name: str): Search for a class in the codebase
335- search_method_in_file(method_name: str, file_path: str): Search for a method in a given file
336- search_method_in_class(method_name: str, class_name: str): Search for a method in a given class
337- search_method(method_name: str): Search for a method in the entire codebase
338- search_code(code_str: str): Search for a code snippet in the entire codebase
339- search_code_in_file(code_str: str, file_path: str): Search for a code snippet in a given file file
340
341Note that you can use multiple search APIs in one round.
342
343Now analyze the issue and select necessary APIs to get more context of the project. Each API call must have concrete arguments as inputs.
344 """,
345 },
346 {
347 "title": "Context Retrieval Agent (round 1)",
348 "category": "context_retrieval_agent",
349 "message": """- **More Context**:
350- We have sufficient context to proceed with fixing the bug. No additional search API calls are needed at this point.
351
352- **Bug Locations**:
353- Buggy File: `libs/community/langchain_community/chat_models/pai_eas_endpoint.py`
354- Buggy Method: `_call_eas` in the `PaiEasChatEndpoint` class""",
355 },
356 {
357 "title": "AutoCodeRover (Agent-selected API calls)",
358 "category": "auto_code_rover",
359 "message": """
360
361Bug locations
362
363- file: `libs/community/langchain_community/chat_models/pai_eas_endpoint.py`, class: `PaiEasChatEndpoint`, method: `_call_eas`""",
364 },
365 {
366 "title": "AutoCodeRover (Patch generation round 1)",
367 "category": "auto_code_rover",
368 "message": '''Here is the code in buggy locations:
369
370
371
372Found 1 methods with name _call_eas in class PaiEasChatEndpoint:
373
374- Search result 1:
375```
376<file>libs/community/langchain_community/chat_models/pai_eas_endpoint.py</file>
377<class>PaiEasChatEndpoint</class> <func>_call_eas</func>
378<code>
379def _call_eas(self, query_body: dict) -> Any:
380"""Generate text from the eas service."""
381headers = {
382"Content-Type": "application/json",
383"Accept": "application/json",
384"Authorization": f"{self.eas_service_token}",
385}
386
387# make request
388response = requests.post(
389self.eas_service_url, headers=headers, json=query_body, timeout=self.timeout
390)
391
392if response.status_code != 200:
393raise Exception(
394f"Request failed with status code {response.status_code}"
395f" and message {response.text}"
396)
397
398return response.text
399
400</code>
401```
402''',
403 },
404 {
405 "title": "AutoCodeRover (patch generation)",
406 "category": "auto_code_rover",
407 "message": """
408 Write a patch for the issue, based on the retrieved context.
409
410You can import necessary libraries.
411
412
413Return the patch in the format below.
414
415Within `<file></file>`, replace `...` with actual file path.
416
417Within `<original></original>`, replace `...` with the original code snippet from the program.
418
419Within `<patched></patched>`, replace `...` with the fixed version of the original code. When adding orignal code and updated code, pay attention to indentation, as the code is in Python.
420You can write multiple modifications if needed.
421
422```
423# modification 1
424<file>...</file>
425<original>...</original>
426<patched>...</patched>
427
428# modification 2
429<file>...</file>
430<original>...</original>
431<patched>...</patched>
432
433# modification 3
434...
435```""",
436 },
437 {
438 "category": "patch_generation",
439 "title": "Patch Generation (try 1 / 3)",
440 "message": '''```
441# Patch for changing the return type of _call_eas method to bytes
442
443import requests
444
445# modification 1
446<file>libs/community/langchain_community/chat_models/pai_eas_endpoint.py</file>
447<original>
448def _call_eas(self, query_body: dict) -> Any:
449"""Generate text from the eas service."""
450headers = {
451"Content-Type": "application/json",
452"Accept": "application/json",
453"Authorization": f"{self.eas_service_token}",
454}
455
456# make request
457response = requests.post(
458self.eas_service_url, headers=headers, json=query_body, timeout=self.timeout
459)
460
461if response.status_code != 200:
462raise Exception(
463f"Request failed with status code {response.status_code}"
464f" and message {response.text}"
465)
466
467return response.text
468</original>
469<patched>
470def _call_eas(self, query_body: dict) -> bytes:
471"""Generate text from the eas service."""
472headers = {
473"Content-Type": "application/json",
474"Accept": "application/json",
475"Authorization": f"{self.eas_service_token}",
476}
477
478# make request
479response = requests.post(
480self.eas_service_url, headers=headers, json=query_body, timeout=self.timeout
481)
482
483if response.status_code != 200:
484raise Exception(
485f"Request failed with status code {response.status_code}"
486f" and message {response.text}"
487)
488
489return response.content
490</patched>
491```''',
492 },
493 {
494 "title": "AutoCodeRover (extracted patch)",
495 "category": "auto_code_rover",
496 "message": '''```diff
497diff --git a/libs/community/langchain_community/chat_models/pai_eas_endpoint.py b/libs/community/langchain_community/chat_models/pai_eas_endpoint.py
498index e438ad25e..309c6d287 100644
499--- a/libs/community/langchain_community/chat_models/pai_eas_endpoint.py
500+++ b/libs/community/langchain_community/chat_models/pai_eas_endpoint.py
501@@ -208,7 +208,7 @@ class PaiEasChatEndpoint(BaseChatModel):
502
503return generated_text
504
505- def _call_eas(self, query_body: dict) -> Any:
506+ def _call_eas(self, query_body: dict) -> bytes:
507"""Generate text from the eas service."""
508headers = {
509"Content-Type": "application/json",
510@@ -227,7 +227,7 @@ class PaiEasChatEndpoint(BaseChatModel):
511f" and message {response.text}"
512)
513
514- return response.text
515+ return response.content
516
517def _call_eas_stream(self, query_body: dict) -> Any:
518"""Generate text from the eas service."""
519
520```''',
521 },
522 {
523 "title": "AutoCodeRover (patch generation try 1 / 3)",
524 "category": "auto_code_rover",
525 "message": """Extracted a patch. Since validation is disabled, you should validation the patch later on. Ending the workflow.""",
526 },
527]
528
529
530def test_generate_data(callback):
531 for data in test_data:
532 callback(data)
533 time.sleep(1)