Skip to content

Commit 78130e9

Browse files
committed
Refactor SDK generation process and enhance Cypher query response handling
This commit simplifies the SDK generation process by delegating the task to a dedicated script, improving maintainability. Additionally, it enhances the response handling in `execute_cypher_query.py` to include a new response model, `ExecuteCypherQueryResponse200`, ensuring better type safety and clarity in response parsing. Key Changes: - **SDK Generation**: Replaced inline SDK generation commands with a call to `bin/generate-sdk`. - **Response Handling**: Updated `_parse_response` and related functions to accommodate the new response model, improving robustness against different content types. Testing Notes: - Verify that the SDK generation works as expected with the new script. - Ensure that the updated response handling correctly processes various response formats, including NDJSON.
1 parent 8c71efc commit 78130e9

6 files changed

Lines changed: 364 additions & 27 deletions

File tree

‎bin/generate-sdk‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Generate Python SDK from OpenAPI specification with post-generation patches.
4+
5+
This script handles the complete SDK generation workflow:
6+
1. Generate SDK using openapi-python-client
7+
2. Copy generated files to robosystems_client/
8+
3. Apply post-generation patches (NDJSON handling, etc.)
9+
4. Format and lint the generated code
10+
"""
11+
12+
import sys
13+
import subprocess
14+
import shutil
15+
from pathlib import Path
16+
17+
18+
def run_command(cmd: str, description: str) -> bool:
19+
"""Run a shell command and return success status."""
20+
print(f"📦 {description}...")
21+
result = subprocess.run(cmd, shell=True, cwd=Path(__file__).parent.parent)
22+
return result.returncode == 0
23+
24+
25+
def patch_ndjson_handling() -> bool:
26+
"""Add NDJSON handling to execute_cypher_query._parse_response."""
27+
28+
file_path = (
29+
Path(__file__).parent.parent
30+
/ "robosystems_client"
31+
/ "api"
32+
/ "query"
33+
/ "execute_cypher_query.py"
34+
)
35+
36+
if not file_path.exists():
37+
print(f"❌ File not found: {file_path}")
38+
return False
39+
40+
# Read the current file content
41+
content = file_path.read_text()
42+
43+
# Check if patch is already applied
44+
if "application/x-ndjson" in content:
45+
print("✅ NDJSON patch already applied")
46+
return True
47+
48+
# Define the patch to insert (note: using 4-space indentation to match generated code)
49+
ndjson_check = """ content_type = response.headers.get("content-type", "")
50+
if (
51+
"application/x-ndjson" in content_type
52+
or response.headers.get("x-stream-format") == "ndjson"
53+
):
54+
return None
55+
"""
56+
57+
# Find the location to insert the patch (raw generated code uses 4 spaces)
58+
search_pattern = " if response.status_code == 200:\n response_200 = ExecuteCypherQueryResponse200.from_dict(response.json())\n\n return response_200"
59+
60+
if search_pattern not in content:
61+
print(f"❌ Could not find expected pattern in {file_path}")
62+
print("The generated code structure may have changed.")
63+
return False
64+
65+
# Replace the pattern with the patched version
66+
replacement = f" if response.status_code == 200:\n{ndjson_check} response_200 = ExecuteCypherQueryResponse200.from_dict(response.json())\n\n return response_200"
67+
patched_content = content.replace(search_pattern, replacement)
68+
69+
# Write the patched content back
70+
_ = file_path.write_text(patched_content)
71+
72+
print(f"✅ Applied NDJSON patch to {file_path.name}")
73+
return True
74+
75+
76+
def main():
77+
"""Main SDK generation workflow."""
78+
79+
# Get OpenAPI URL from command line or use default
80+
url = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8000/openapi.json"
81+
82+
print(f"🚀 Generating Python SDK from {url}...")
83+
print()
84+
85+
# Step 1: Generate SDK
86+
if not run_command("rm -rf generated", "Cleaning previous generation"):
87+
return 1
88+
89+
if not run_command(
90+
f"uv run openapi-python-client generate --url {url} --output-path generated --config robosystems_client/sdk-config.yaml",
91+
f"Generating SDK from {url}",
92+
):
93+
return 1
94+
95+
# Step 2: Copy generated files
96+
print("📦 Copying generated code to robosystems_client/...")
97+
98+
base_path = Path(__file__).parent.parent
99+
generated_path = base_path / "generated" / "robo_systems_api_client"
100+
target_path = base_path / "robosystems_client"
101+
102+
# Remove old generated files
103+
for item in ["api", "models", "client.py", "errors.py", "types.py", "py.typed"]:
104+
item_path = target_path / item
105+
if item_path.exists():
106+
if item_path.is_dir():
107+
shutil.rmtree(item_path)
108+
else:
109+
item_path.unlink()
110+
111+
# Copy new generated files
112+
for item in ["api", "models", "client.py", "errors.py", "types.py", "py.typed"]:
113+
src = generated_path / item
114+
dst = target_path / item
115+
if src.exists():
116+
if src.is_dir():
117+
shutil.copytree(src, dst)
118+
else:
119+
shutil.copy2(src, dst)
120+
121+
# Clean up generated folder
122+
shutil.rmtree(base_path / "generated")
123+
124+
print()
125+
126+
# Step 3: Apply patches
127+
print("🔧 Applying post-generation patches...")
128+
if not patch_ndjson_handling():
129+
print("⚠️ Warning: NDJSON patch failed, but continuing...")
130+
131+
print()
132+
133+
# Step 4: Format and lint
134+
if not run_command("uv run ruff format .", "Formatting code"):
135+
return 1
136+
137+
if not run_command("uv run ruff check . --fix", "Fixing linting issues"):
138+
return 1
139+
140+
if not run_command("uv run ruff check .", "Running final linting check"):
141+
return 1
142+
143+
if not run_command("uv run ruff format --check .", "Verifying formatting"):
144+
return 1
145+
146+
print()
147+
print("✅ SDK generation complete!")
148+
print()
149+
print("Changes applied:")
150+
print(" - Generated fresh SDK from OpenAPI spec")
151+
print(" - Applied NDJSON streaming support patch")
152+
print(" - Formatted and linted all code")
153+
print()
154+
155+
return 0
156+
157+
158+
if __name__ == "__main__":
159+
sys.exit(main())

‎justfile‎

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -45,22 +45,7 @@ typecheck:
4545

4646
# Generate SDK from localhost API
4747
generate-sdk url="http://localhost:8000/openapi.json":
48-
@echo "🚀 Generating Client from {{url}}..."
49-
rm -rf generated
50-
uv run openapi-python-client generate --url {{url}} --output-path generated --config robosystems_client/sdk-config.yaml
51-
@echo "📦 Copying generated code to robosystems_client..."
52-
rm -rf robosystems_client/api robosystems_client/models robosystems_client/client.py robosystems_client/errors.py robosystems_client/types.py robosystems_client/py.typed
53-
cp -r generated/robo_systems_api_client/api robosystems_client/
54-
cp -r generated/robo_systems_api_client/models robosystems_client/
55-
cp generated/robo_systems_api_client/client.py robosystems_client/
56-
cp generated/robo_systems_api_client/errors.py robosystems_client/
57-
cp generated/robo_systems_api_client/types.py robosystems_client/
58-
cp generated/robo_systems_api_client/py.typed robosystems_client/
59-
rm -rf generated
60-
@just format
61-
uv run ruff check . --fix
62-
@just lint
63-
@echo "✅ Client generation complete!"
48+
bin/generate-sdk {{url}}
6449

6550
# Build python package locally (for testing)
6651
build-package:

‎robosystems_client/api/query/execute_cypher_query.py‎

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from ... import errors
77
from ...client import AuthenticatedClient, Client
88
from ...models.cypher_query_request import CypherQueryRequest
9+
from ...models.execute_cypher_query_response_200 import ExecuteCypherQueryResponse200
910
from ...models.http_validation_error import HTTPValidationError
1011
from ...models.response_mode import ResponseMode
1112
from ...types import UNSET, Response, Unset
@@ -59,9 +60,16 @@ def _get_kwargs(
5960

6061
def _parse_response(
6162
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
62-
) -> Optional[Union[Any, HTTPValidationError]]:
63+
) -> Optional[Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]]:
6364
if response.status_code == 200:
64-
response_200 = response.json()
65+
content_type = response.headers.get("content-type", "")
66+
if (
67+
"application/x-ndjson" in content_type
68+
or response.headers.get("x-stream-format") == "ndjson"
69+
):
70+
return None
71+
response_200 = ExecuteCypherQueryResponse200.from_dict(response.json())
72+
6573
return response_200
6674

6775
if response.status_code == 202:
@@ -105,7 +113,7 @@ def _parse_response(
105113

106114
def _build_response(
107115
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
108-
) -> Response[Union[Any, HTTPValidationError]]:
116+
) -> Response[Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]]:
109117
return Response(
110118
status_code=HTTPStatus(response.status_code),
111119
content=response.content,
@@ -122,7 +130,7 @@ def sync_detailed(
122130
mode: Union[None, ResponseMode, Unset] = UNSET,
123131
chunk_size: Union[None, Unset, int] = UNSET,
124132
test_mode: Union[Unset, bool] = False,
125-
) -> Response[Union[Any, HTTPValidationError]]:
133+
) -> Response[Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]]:
126134
r"""Execute Cypher Query (Read-Only)
127135
128136
Execute a read-only Cypher query with intelligent response optimization.
@@ -201,7 +209,7 @@ def sync_detailed(
201209
httpx.TimeoutException: If the request takes longer than Client.timeout.
202210
203211
Returns:
204-
Response[Union[Any, HTTPValidationError]]
212+
Response[Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]]
205213
"""
206214

207215
kwargs = _get_kwargs(
@@ -227,7 +235,7 @@ def sync(
227235
mode: Union[None, ResponseMode, Unset] = UNSET,
228236
chunk_size: Union[None, Unset, int] = UNSET,
229237
test_mode: Union[Unset, bool] = False,
230-
) -> Optional[Union[Any, HTTPValidationError]]:
238+
) -> Optional[Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]]:
231239
r"""Execute Cypher Query (Read-Only)
232240
233241
Execute a read-only Cypher query with intelligent response optimization.
@@ -306,7 +314,7 @@ def sync(
306314
httpx.TimeoutException: If the request takes longer than Client.timeout.
307315
308316
Returns:
309-
Union[Any, HTTPValidationError]
317+
Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]
310318
"""
311319

312320
return sync_detailed(
@@ -327,7 +335,7 @@ async def asyncio_detailed(
327335
mode: Union[None, ResponseMode, Unset] = UNSET,
328336
chunk_size: Union[None, Unset, int] = UNSET,
329337
test_mode: Union[Unset, bool] = False,
330-
) -> Response[Union[Any, HTTPValidationError]]:
338+
) -> Response[Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]]:
331339
r"""Execute Cypher Query (Read-Only)
332340
333341
Execute a read-only Cypher query with intelligent response optimization.
@@ -406,7 +414,7 @@ async def asyncio_detailed(
406414
httpx.TimeoutException: If the request takes longer than Client.timeout.
407415
408416
Returns:
409-
Response[Union[Any, HTTPValidationError]]
417+
Response[Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]]
410418
"""
411419

412420
kwargs = _get_kwargs(
@@ -430,7 +438,7 @@ async def asyncio(
430438
mode: Union[None, ResponseMode, Unset] = UNSET,
431439
chunk_size: Union[None, Unset, int] = UNSET,
432440
test_mode: Union[Unset, bool] = False,
433-
) -> Optional[Union[Any, HTTPValidationError]]:
441+
) -> Optional[Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]]:
434442
r"""Execute Cypher Query (Read-Only)
435443
436444
Execute a read-only Cypher query with intelligent response optimization.
@@ -509,7 +517,7 @@ async def asyncio(
509517
httpx.TimeoutException: If the request takes longer than Client.timeout.
510518
511519
Returns:
512-
Union[Any, HTTPValidationError]
520+
Union[Any, ExecuteCypherQueryResponse200, HTTPValidationError]
513521
"""
514522

515523
return (

‎robosystems_client/models/__init__.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,10 @@
9595
from .error_response import ErrorResponse
9696
from .exchange_token_request import ExchangeTokenRequest
9797
from .exchange_token_request_metadata_type_0 import ExchangeTokenRequestMetadataType0
98+
from .execute_cypher_query_response_200 import ExecuteCypherQueryResponse200
99+
from .execute_cypher_query_response_200_data_item import (
100+
ExecuteCypherQueryResponse200DataItem,
101+
)
98102
from .file_info import FileInfo
99103
from .file_status_update import FileStatusUpdate
100104
from .file_upload_request import FileUploadRequest
@@ -351,6 +355,8 @@
351355
"ErrorResponse",
352356
"ExchangeTokenRequest",
353357
"ExchangeTokenRequestMetadataType0",
358+
"ExecuteCypherQueryResponse200",
359+
"ExecuteCypherQueryResponse200DataItem",
354360
"FileInfo",
355361
"FileStatusUpdate",
356362
"FileUploadRequest",

0 commit comments

Comments
 (0)