Skip to content

Commit 04c2c04

Browse files
committed
update
1 parent 794606a commit 04c2c04

1 file changed

Lines changed: 37 additions & 27 deletions

File tree

tools/azure-sdk-tools/linting_tools/lint_test_bench/pylint_agent.py

Lines changed: 37 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
from azure.identity import get_bearer_token_provider
88
from pathlib import Path
99
from datetime import datetime
10-
from azure.ai.evaluation import evaluate, SimilarityEvaluator, ContentSafetyEvaluator, GroundednessEvaluator
11-
import json
10+
from azure.ai.evaluation import GroundednessEvaluator
11+
from pylint.lint import Run
1212

1313
token_provider = get_bearer_token_provider(
1414
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
@@ -20,9 +20,10 @@
2020
azure_ad_token_provider=token_provider,
2121
)
2222

23-
pylint_scores = {}
23+
EVAL_RESULTS = {}
24+
PYLINT_SCORES = {}
2425

25-
fix_file_prompt = """
26+
FILE_PROMPT = """
2627
DO prompt the user to create a virtual environment with `<path_to_python_installation>/python.exe -m venv <environment_name>` and activate it, before running any commands.
2728
2829
# General Repository Guidelines
@@ -127,15 +128,14 @@ def fix_file(file_path: str, logger) -> dict:
127128
with open(file_path, 'r', encoding='utf-8') as f:
128129
original_content = f.read()
129130

130-
# logger.debug(f"PROMPT FOR FIXING FILE: {fix_file_prompt}")
131131
logger.debug(f"MODEL: {os.environ['AZURE_OPENAI_MODEL']}")
132132

133133

134134
# Get fixed content from Azure OpenAI
135135
response = client.chat.completions.create(
136136
model=os.environ["AZURE_OPENAI_MODEL"],
137137
messages=[
138-
{"role": "system", "content": fix_file_prompt},
138+
{"role": "system", "content": FILE_PROMPT},
139139
{"role": "user", "content": f"Fix pylint issues in this code:\n\n{original_content}"}
140140
],
141141
)
@@ -177,9 +177,7 @@ def run_pylint(file_path: str, logger) -> dict:
177177
dict: Pylint analysis results including score and messages
178178
"""
179179
try:
180-
from pylint.lint import Run
181-
from pylint.reporters import JSONReporter
182-
from io import StringIO
180+
183181

184182
# Get path to pylintrc
185183
pylintrc_path = Path(__file__).parent / '.pylintrc'
@@ -203,9 +201,9 @@ def run_pylint(file_path: str, logger) -> dict:
203201
logger.debug(f"PYLINT SCORE: {results.linter.stats.global_note}")
204202
pylint_name = file_path.split("/")[-1].split(".py")[0]
205203
try:
206-
pylint_scores[pylint_name].append(results.linter.stats.global_note)
204+
PYLINT_SCORES[pylint_name].append(results.linter.stats.global_note)
207205
except:
208-
pylint_scores[pylint_name] = [results.linter.stats.global_note]
206+
PYLINT_SCORES[pylint_name] = [results.linter.stats.global_note]
209207

210208
return results.linter.stats.global_note
211209

@@ -216,10 +214,11 @@ def run_pylint(file_path: str, logger) -> dict:
216214
'file': file_path
217215
}
218216

219-
def evaluate_fixes(original_content, fixed_content):
217+
def evaluate_fixes(file_path, original_content, fixed_content):
220218
"""
221219
Use azure-ai-evaluation to compare the original and fixed content.
222220
Args:
221+
file_path (str): The path of the file being evaluated.
223222
original_content (str): The original file content.
224223
fixed_content (str): The fixed file content.
225224
Returns:
@@ -231,14 +230,15 @@ def evaluate_fixes(original_content, fixed_content):
231230
"azure_deployment": os.environ['AZURE_OPENAI_MODEL'],
232231
"api_version": os.environ["AZURE_OPENAI_VERSION"],
233232
"api_key": os.environ.get("AZURE_OPENAI_KEY"),
234-
}
233+
}
234+
235+
pylint_name = file_path.split("/")[-1].split(".py")[0]
235236

236237
# Use the evaluate function with the JSONL file
237238
eval = GroundednessEvaluator(model_config=model_config)
238239

239-
evaluation_result = eval(context=fix_file_prompt + f"Fix pylint issues in this code:\n\n{original_content}", response=fixed_content)
240-
241-
return evaluation_result
240+
evaluation_result = eval(context=FILE_PROMPT + f"Fix pylint issues in this code:\n\n{original_content}", response=fixed_content)
241+
EVAL_RESULTS[pylint_name] = evaluation_result
242242

243243
# Example usage
244244
if __name__ == "__main__":
@@ -268,22 +268,32 @@ def evaluate_fixes(original_content, fixed_content):
268268
fixed_pylint = run_pylint(str(result['fixed_file']), logger)
269269

270270
# Evaluate the fixes
271-
evaluation_result = evaluate_fixes(result['original_content'], result['fixed_content'])
272-
logger.debug(f"Evaluation Result: {evaluation_result}")
273-
271+
evaluate_fixes(str(result['fixed_file']), result['original_content'], result['fixed_content'])
272+
274273
# Update file_path for next iteration
275274
logger.debug("-----"*80)
276275
file_path = str(result['fixed_file'])
277276
counter += 1
278277
logger.debug("-----"*80)
279-
logger.debug("\n\n\n")
278+
logger.debug("\n\n\n")
279+
base_dir = Path(__file__).parent
280+
with open(f"{base_dir}/output_logs/final_{next}", 'w', encoding='utf-8') as f:
281+
for key, value in PYLINT_SCORES.items():
282+
f.write(f"{key}: {value}")
283+
f.write("\n")
284+
# Add corresponding evaluation scores if available
285+
if key in EVAL_RESULTS:
286+
f.write(f"Evaluation Results for {key}:")
287+
f.write("\n")
288+
f.write(f"Groundedness Score: {EVAL_RESULTS[key].score}")
289+
f.write("\n")
290+
f.write(f"Groundedness Result: {EVAL_RESULTS[key].result}")
291+
if EVAL_RESULTS[key].explanation:
292+
f.write("\n")
293+
f.write(f"Explanation: {EVAL_RESULTS[key].explanation}")
294+
f.write("\n")
295+
f.write("-----"*80)
296+
f.write("\n")
280297
except Exception as e:
281298
raise e
282299
print(f"Error in processing test cases: {str(e)}")
283-
base_dir = Path(__file__).parent
284-
with open(f"{base_dir}/output_logs/final_{next}", 'w', encoding='utf-8') as f:
285-
for key, value in pylint_scores.items():
286-
f.write(f"{key}: {value}")
287-
f.write("\n")
288-
f.write("-----"*80)
289-
f.write("\n")

0 commit comments

Comments
 (0)