|
| 1 | +import json |
| 2 | +from typing import Any, Callable, Dict, Optional |
| 3 | + |
| 4 | +import requests |
| 5 | +from typing_extensions import Literal |
| 6 | + |
| 7 | +from patchwork.common.tools.tool import Tool |
| 8 | + |
| 9 | + |
| 10 | +class APIRequestTool(Tool, tool_name="make_api_request", abc_register=False): |
| 11 | + def __init__( |
| 12 | + self, |
| 13 | + headers: Optional[Dict[str, str]] = dict(), |
| 14 | + username: Optional[str] = None, |
| 15 | + password: Optional[str] = None, |
| 16 | + preprocess_data: Callable[[str], str] = lambda x: x, |
| 17 | + **kwargs, |
| 18 | + ): |
| 19 | + self._headers = headers |
| 20 | + self._auth = (username, password) if username and password else None |
| 21 | + self._preprocess_data = preprocess_data |
| 22 | + |
| 23 | + @property |
| 24 | + def json_schema(self) -> dict: |
| 25 | + return { |
| 26 | + "name": "make_api_request", |
| 27 | + "description": """\ |
| 28 | +A generic tool to make HTTP API requests with flexible configuration. |
| 29 | +
|
| 30 | +Supports various HTTP methods (GET, POST, PUT, DELETE, PATCH) with optional |
| 31 | +authentication, headers, query parameters, and request body. |
| 32 | +
|
| 33 | +Authentication can be configured via: |
| 34 | +- Basic Auth (username/password) |
| 35 | +- Bearer Token |
| 36 | +- API Key (in header or query param) |
| 37 | +""", |
| 38 | + "input_schema": { |
| 39 | + "type": "object", |
| 40 | + "properties": { |
| 41 | + "url": { |
| 42 | + "type": "string", |
| 43 | + "description": "Full URL for the API endpoint", |
| 44 | + }, |
| 45 | + "method": { |
| 46 | + "type": "string", |
| 47 | + "enum": ["GET", "POST", "PUT", "DELETE", "PATCH"], |
| 48 | + "description": "HTTP method for the request", |
| 49 | + }, |
| 50 | + "headers": { |
| 51 | + "type": "object", |
| 52 | + "description": "Optional custom headers", |
| 53 | + }, |
| 54 | + "params": { |
| 55 | + "type": "object", |
| 56 | + "description": "Optional query parameters", |
| 57 | + }, |
| 58 | + "data": { |
| 59 | + "type": "string", |
| 60 | + "description": "data for POST/PUT/PATCH requests. If you need to send json data, it should be converted to a string.", |
| 61 | + }, |
| 62 | + }, |
| 63 | + "required": ["url", "method"], |
| 64 | + }, |
| 65 | + } |
| 66 | + |
| 67 | + def execute( |
| 68 | + self, |
| 69 | + url: str, |
| 70 | + method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"] = "GET", |
| 71 | + headers: Optional[Dict[str, str]] = None, |
| 72 | + params: Optional[Dict[str, Any]] = None, |
| 73 | + data: Optional[str] = None, |
| 74 | + ) -> str: |
| 75 | + # Combine with default headers |
| 76 | + request_headers = headers or {} |
| 77 | + request_headers.update(self._headers) |
| 78 | + |
| 79 | + # Prepare request |
| 80 | + response = requests.request( |
| 81 | + method=method, |
| 82 | + url=url, |
| 83 | + headers=request_headers, |
| 84 | + params=params, |
| 85 | + data=(self._preprocess_data(data) if data else None), |
| 86 | + auth=self._auth, |
| 87 | + ) |
| 88 | + |
| 89 | + if not response.ok: |
| 90 | + response_text = response.text |
| 91 | + status_code = response.status_code |
| 92 | + headers = response.headers |
| 93 | + |
| 94 | + header_string = "\n".join( |
| 95 | + f"{key}: {value}" for key, value in headers.items() |
| 96 | + ) |
| 97 | + |
| 98 | + return ( |
| 99 | + f"HTTP/{response.raw.version / 10:.1f} {status_code} {response.reason}\n" |
| 100 | + f"{header_string}\n" |
| 101 | + f"\n" |
| 102 | + f"{response_text}" |
| 103 | + ) |
| 104 | + |
| 105 | + # Try to parse JSON, fallback to text |
| 106 | + try: |
| 107 | + return json.dumps(response.json()) |
| 108 | + except ValueError: |
| 109 | + return response.text |
0 commit comments