REA:讓 AI 智能體逆向工程,實現應用程式欠缺的功能
REA: Let Your AI Agent Reverse Engineer the App Features You Wish You Had
REA(Reverse Engineering Agent)是一種建構 AI 智能體的模式,可分析網絡流量以推斷應用程式的 API,並產生程式碼實現所需功能。文中以 Python、mitmproxy 和 OpenAI API 示範從擷取流量到驗證程式碼的流程,並提醒要設定迴圈終止條件及在沙盒環境執行生成的程式碼。
Introduction
You've been there: you're using an app, and you think, "If only it had feature X." But instead of waiting for the product team, you can build an AI agent that reverse engineers the app's API and implements that feature yourself. This post introduces REA (Reverse Engineering Agent), a pattern for building such agents. We'll walk through a concrete implementation in Python that inspects a web app's network traffic, infers API endpoints, and generates code to replicate missing functionality.
The Problem
Modern web apps are complex. Their features are often powered by undocumented internal APIs. When you want to extend or automate them, you're left guessing endpoints, parameters, and authentication. Manually reverse engineering is tedious and error-prone.
The Solution: REA
REA is an agent that:
- Captures HTTP traffic from a target app (using a proxy like mitmproxy).
- Analyzes requests/responses to identify API patterns.
- Generates Python code that replicates desired features.
- Validates the generated code against the live API.
The agent operates in a loop with explicit termination conditions: either it successfully generates and validates the code, or it exhausts a maximum number of iterations.
Implementation
We'll build a simplified REA using Python, mitmproxy, and OpenAI's API. The agent will reverse engineer a hypothetical "todo" feature from a demo app.
Prerequisites
pip install mitmproxy openai requests
Step 1: Capture Traffic
We'll use mitmproxy's scripting to log requests to a file. Save this as capture.py:
from mitmproxy import http
import json
class Capture:
def response(self, flow: http.HTTPFlow):
if "api" in flow.request.pretty_url:
entry = {
"method": flow.request.method,
"url": flow.request.pretty_url,
"headers": dict(flow.request.headers),
"body": flow.request.get_text(),
"response": flow.response.get_text()
}
with open("traffic.jsonl", "a") as f:
f.write(json.dumps(entry) + "\n")
addons = [Capture()]
Run mitmproxy with this script:
mitmproxy -s capture.py
Configure your browser to use mitmproxy as a proxy, then use the app to trigger the feature you want to replicate. The traffic will be logged to traffic.jsonl.
Step 2: Analyze Traffic and Generate Code
Now, we'll write the REA agent. It reads the captured traffic, asks an LLM to infer the API, and generates Python code. We'll use OpenAI's function calling to structure the output.
import json
import openai
openai.api_key = "YOUR_API_KEY"
# Load captured traffic
traffic = []
with open("traffic.jsonl") as f:
for line in f:
traffic.append(json.loads(line))
# Prepare a summary for the LLM
summary = []
for entry in traffic:
summary.append({
"method": entry["method"],
"url": entry["url"],
"request_body": entry["body"],
"response_snippet": entry["response"][:200]
})
prompt = f"""
Given these HTTP requests and responses from a web app, infer the API endpoints and generate Python code using the `requests` library to perform the following feature: "Create a new todo item".
Traffic summary:
{json.dumps(summary, indent=2)}
Return a JSON object with keys: `endpoint`, `method`, `headers`, `payload_template`, and `code`. The `code` should be a complete Python function that takes necessary parameters and returns the response.
"""
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
temperature=0
)
result = json.loads(response.choices[0].message.content)
print("Generated code:\n", result["code"])
Step 3: Validate Generated Code
The agent should test the generated code against the live API. We'll extract the function and run it with sample data.
import requests
# Extract the function from generated code (simplified)
# In production, use a sandboxed environment!
exec(result["code"], globals()) # SECURITY WARNING: Never exec untrusted code in production.
# Assuming the function is named `create_todo`
try:
response = create_todo("Test todo")
if response.status_code == 200:
print("Validation successful!")
else:
print("Validation failed:", response.status_code)
except Exception as e:
print("Error during validation:", e)
The Agent Loop
A full REA agent would iterate: if validation fails, it feeds the error back to the LLM to refine the code. The loop terminates when validation succeeds or after max_iterations (e.g., 5).
max_iterations = 5
for i in range(max_iterations):
# Generate code (as above)
# Validate
if validation_success:
break
else:
# Add error to prompt for next iteration
prompt += f"\nPrevious attempt failed with error: {error}"
Key Takeaways
- REA agents can automate reverse engineering of web APIs by combining traffic capture with LLM-powered code generation.
- Always include explicit termination conditions in agent loops to avoid infinite execution.
- Security: Never execute generated code without sandboxing. Use containers or restricted environments.
- This approach is for educational purposes; respect terms of service and privacy laws.
By building your own REA, you can unlock features that apps don't provide, tailored to your workflow.
Note: This implementation is inspired by agentic patterns but is not a formal protocol. The term "REA" is used descriptively.
來源:DEV Community · dev.to