fixing-loop-agent 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,190 @@
1
+ import os
2
+ import subprocess
3
+ import tempfile
4
+ import typer
5
+ from dotenv import load_dotenv
6
+ from openai import OpenAI
7
+ from yaspin import yaspin
8
+ from yaspin.spinners import Spinners
9
+
10
+ # 1. Load Environment Variables
11
+ load_dotenv()
12
+
13
+ provider = os.getenv("AI_PROVIDER", "groq")
14
+ api_key = os.getenv("AI_API_KEY")
15
+ model_name = os.getenv("AI_MODEL", "qwen/qwen3.8-27b")
16
+
17
+ if provider.lower() == "groq":
18
+ base_url = "https://api.groq.com/openai/v1"
19
+ elif provider.lower() == "openai":
20
+ base_url = "https://api.openai.com/v1"
21
+ else:
22
+ base_url = "https://api.groq.com/openai/v1"
23
+
24
+ client = OpenAI(api_key=api_key, base_url=base_url)
25
+
26
+ # 2. The Agent's Brain (Prompts)
27
+ CRITIC_PROMPT = """
28
+ You are an expert Code Reviewer. Analyze the following {language} code.
29
+ Identify missing preconditions (input validation), postconditions (output validation), and potential edge cases.
30
+ Output a brief list of the flaws you found.
31
+ """
32
+
33
+ BUILDER_PROMPT = """
34
+ You are an expert Software Engineer practicing "Design by Contract".
35
+ Based on the flaws identified, rewrite the {language} code.
36
+ RULES:
37
+ 1. Add assert/exception checks at the start of functions for PRECONDITIONS.
38
+ 2. Add checks before returns for POSTCONDITIONS.
39
+ 3. Add a test harness at the bottom with 3 test cases.
40
+ Output ONLY the valid, executable {language} code. No markdown formatting.
41
+ """
42
+
43
+ # 3. Local Execution Engine (Multi-Language Support)
44
+ def execute_locally(code, extension):
45
+ # Create a temporary file with the correct extension
46
+ with tempfile.NamedTemporaryFile(mode='w', suffix=extension, delete=False, encoding='utf-8') as f:
47
+ f.write(code)
48
+ temp_file = f.name
49
+
50
+ env = os.environ.copy()
51
+ env["PYTHONIOENCODING"] = "utf-8"
52
+ exe_file = None
53
+
54
+ try:
55
+ # 1. Directly Interpreted Languages (No compilation needed)
56
+ if extension == ".py":
57
+ cmd = ["python", temp_file]
58
+ elif extension in [".js", ".mjs"]:
59
+ cmd = ["node", temp_file]
60
+ elif extension == ".rb":
61
+ cmd = ["ruby", temp_file]
62
+ elif extension == ".go":
63
+ cmd = ["go", "run", temp_file]
64
+
65
+ # 2. Compiled Languages (C, C++)
66
+ elif extension in [".c", ".cpp", ".cc"]:
67
+ exe_file = temp_file + ".exe"
68
+ compiler = "gcc" if extension == ".c" else "g++"
69
+
70
+ # First: Compile the code
71
+ compile_cmd = [compiler, temp_file, "-o", exe_file]
72
+ compile_result = subprocess.run(compile_cmd, capture_output=True, text=True, env=env, timeout=15)
73
+ if compile_result.returncode != 0:
74
+ return False, f"Compilation Error: {compile_result.stderr.strip()}"
75
+
76
+ # Second: Run the compiled code
77
+ cmd = [exe_file]
78
+
79
+ else:
80
+ return False, f"Local execution not supported for {extension} yet."
81
+
82
+ # Execute the final command
83
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=10, env=env)
84
+
85
+ if result.returncode == 0:
86
+ return True, ""
87
+ else:
88
+ return False, result.stderr.strip() or result.stdout.strip()
89
+
90
+ except FileNotFoundError:
91
+ return False, f"Error: Runtime/Compiler for '{extension}' not found. Please install it on your system."
92
+ except subprocess.TimeoutExpired:
93
+ return False, "Execution timed out (infinite loop?)."
94
+ except Exception as e:
95
+ return False, str(e)
96
+ finally:
97
+ # Cleanup temp files so we don't clutter the computer
98
+ try:
99
+ os.remove(temp_file)
100
+ if exe_file and os.path.exists(exe_file):
101
+ os.remove(exe_file)
102
+ except:
103
+ pass
104
+
105
+ # 4. The Agent Logic (The Agentic Loop)
106
+ def run_agent(file_path, language):
107
+ with open(file_path, "r", encoding="utf-8") as f:
108
+ original_code = f.read()
109
+
110
+ _, extension = os.path.splitext(file_path)
111
+
112
+ # 1. The Initial Critique with Spinner
113
+ with yaspin(Spinners.dots, text=f"🔍 Analyzing {language} code...") as sp:
114
+ critique_response = client.chat.completions.create(
115
+ model=model_name,
116
+ messages=[
117
+ {"role": "system", "content": CRITIC_PROMPT.format(language=language)},
118
+ {"role": "user", "content": original_code}
119
+ ],
120
+ temperature=0.2, timeout=30
121
+ )
122
+ critique = critique_response.choices[0].message.content
123
+ sp.ok("✅") # Turn spinner into a green checkmark
124
+
125
+ typer.secho("--- CRITIQUE ---", fg=typer.colors.YELLOW)
126
+ typer.echo(critique)
127
+
128
+ # 2. The Agentic Loop
129
+ max_retries = 3
130
+ error_feedback = ""
131
+
132
+ for attempt in range(1, max_retries + 1):
133
+ typer.echo(f"\n🛠️ Builder Attempt {attempt}/{max_retries}...")
134
+
135
+ prompt_content = f"Original Code:\n{original_code}\n\nCritique:\n{critique}"
136
+ if error_feedback:
137
+ prompt_content += f"\n\nPREVIOUS ERROR: {error_feedback}\nPlease fix this specific error."
138
+
139
+ with yaspin(Spinners.line, text="🤖 Generating fix...") as sp:
140
+ refactor_response = client.chat.completions.create(
141
+ model=model_name,
142
+ messages=[
143
+ {"role": "system", "content": BUILDER_PROMPT.format(language=language)},
144
+ {"role": "user", "content": prompt_content}
145
+ ],
146
+ temperature=0.2, timeout=30
147
+ )
148
+ refactored_code = refactor_response.choices[0].message.content
149
+ sp.ok("✅")
150
+
151
+ # Clean markdown
152
+ if f"```{language}" in refactored_code:
153
+ refactored_code = refactored_code.split(f"```{language}")[1].split("```")[0]
154
+ elif "```" in refactored_code:
155
+ refactored_code = refactored_code.split("```")[1].split("```")[0]
156
+
157
+ typer.echo("🧪 Running local tests...")
158
+ success, error = execute_locally(refactored_code, extension)
159
+
160
+ if success:
161
+ typer.secho("\n[SUCCESS] Agent successfully fixed the code!", fg=typer.colors.GREEN, bold=True)
162
+ with open(f"fixed_{file_path}", "w", encoding="utf-8") as f:
163
+ f.write(refactored_code)
164
+ typer.secho(f"💾 Saved fixed code to 'fixed_{file_path}'", fg=typer.colors.GREEN)
165
+ return
166
+ else:
167
+ typer.secho(f"[FAILED] {error}", fg=typer.colors.RED)
168
+ error_feedback = error
169
+
170
+ typer.secho("\n⚠️ Agent reached maximum retries without success.", fg=typer.colors.RED, bold=True)
171
+
172
+ # 5. The CLI Interface
173
+ app = typer.Typer(help="Fixing Loop Agent: Contract-First AI Code Revision")
174
+
175
+ @app.command()
176
+ def review(
177
+ file_path: str = typer.Argument(..., help="The path to the code file you want to review."),
178
+ language: str = typer.Option("python", "--lang", "-l", help="The programming language (e.g., python, javascript, cpp, c, go, ruby).")
179
+ ):
180
+ """
181
+ Review and fix code using Design by Contract principles.
182
+ """
183
+ if not os.path.exists(file_path):
184
+ typer.secho(f"Error: File '{file_path}' not found.", fg=typer.colors.RED)
185
+ raise typer.Exit(code=1)
186
+
187
+ run_agent(file_path, language)
188
+
189
+ if __name__ == "__main__":
190
+ app()
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: fixing-loop-agent
3
+ Version: 0.1.0
4
+ Summary: An autonomous AI agent that reviews and fixes code using a self-correcting loop.
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: typer
7
+ Requires-Dist: openai
8
+ Requires-Dist: python-dotenv
9
+ Requires-Dist: yaspin
@@ -0,0 +1,7 @@
1
+ fixing_loop_agent/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ fixing_loop_agent/cli.py,sha256=O3o0ouwC6AybYDOHJQMtI4GdQD7NYygy4odXOjG6kC4,7221
3
+ fixing_loop_agent-0.1.0.dist-info/METADATA,sha256=OBMu-BRnXgGq3SRxTInZ8HCiSl7ZjsYdc9_NOkrf4qU,278
4
+ fixing_loop_agent-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ fixing_loop_agent-0.1.0.dist-info/entry_points.txt,sha256=yaXgjQvLcK2_aiEEX5SfQqLI4xDc9KQiWKtGwDWC_NQ,64
6
+ fixing_loop_agent-0.1.0.dist-info/top_level.txt,sha256=orWwcd8v-sG_Zts6jsY73m_YnHIeCA0D1KRePsoxEOc,18
7
+ fixing_loop_agent-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fixing-loop-agent = fixing_loop_agent.cli:app
@@ -0,0 +1 @@
1
+ fixing_loop_agent