| 2 | import json |
| 3 | |
| 4 | class Request: |
| 5 | def __init__(self, method: str, url: str, headers: Dict[str, str], |
| 6 | query_params: Optional[Dict[str, str]] = None, body: Optional[Any] = None): |
| 7 | self.method = method |
| 8 | self.url = url |
| 9 | self.headers = headers |
| 10 | self.query_params = query_params |
| 11 | self.body = body |
| 12 | |
| 13 | def to_curl_command(self) -> str: |
| 14 | curl_parts = [f"curl -X {self.method}"] |
| 15 | |
| 16 | for name, value in self.headers.items(): |
| 17 | curl_parts.append(f"-H '{name}: {value}'") |
| 18 | |
| 19 | if self.query_params: |
| 20 | query_string = "&".join([f"{k}={v}" for k, v in self.query_params.items()]) |
| 21 | self.url += f"?{query_string}" |
| 22 | |
| 23 | if self.body: |
| 24 | content_type = None |
| 25 | for k in self.headers: |
| 26 | if k.lower() == 'content-type': |
| 27 | content_type = self.headers[k] |
| 28 | break |
| 29 | |
| 30 | if isinstance(self.body, dict): |
| 31 | # Add Content-Type header if not present |
| 32 | if not content_type: |
| 33 | curl_parts.append(f"-H 'Content-Type: application/json'") |
| 34 | curl_parts.append(f"--data '{json.dumps(self.body)}'") |
| 35 | elif isinstance(self.body, str): |
| 36 | curl_parts.append(f"--data '{self.body}'") |
| 37 | |
| 38 | curl_parts.append(f"'{self.url}'") |
| 39 | |
| 40 | return " ".join(curl_parts) |
| 41 | |
| 42 | def to_minified_curl_command(self) -> str: |
| 43 | """ |
| 44 | Minifies the curl command by removing referer and cookie headers. |
| 45 | This is done to reduce LLM hallucinations. |
| 46 | """ |
| 47 | curl_parts = [f"curl -X {self.method}"] |
| 48 | |
| 49 | for name, value in self.headers.items(): |
| 50 | if name.lower() not in ['referer', 'cookie']: |
| 51 | curl_parts.append(f"-H '{name}: {value}'") |
| 52 | |
| 53 | if self.query_params: |
| 54 | query_string = "&".join([f"{k}={v}" for k, v in self.query_params.items()]) |
| 55 | self.url += f"?{query_string}" |
| 56 | |
| 57 | if self.body: |
| 58 | content_type = None |
| 59 | for k in self.headers: |
| 60 | if k.lower() == 'content-type': |
| 61 | content_type = self.headers[k] |