Skip to content

Commit 700b0f4

Browse files
fix: Apply ruff formatting to resolve pre-commit failures
- Remove trailing whitespace from docstrings - Modernize type hints (Union -> |, Optional -> | None) - Fix import ordering and formatting - Ensure consistent code style across all files
1 parent dc879d5 commit 700b0f4

File tree

20 files changed

+217
-268
lines changed

20 files changed

+217
-268
lines changed

examples/sdk_usage.py

Lines changed: 29 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
"""
2-
Example usage of the enhanced Codegen SDK.
1+
"""Example usage of the enhanced Codegen SDK.
32
43
This example demonstrates how to use the new SDK components:
54
- CodegenSDK: Unified entry point for all API functionality
@@ -9,29 +8,31 @@
98
"""
109

1110
import os
11+
1212
from codegen.agents import Agent, CodegenSDK, Organizations, Users
1313

14+
1415
# Example 1: Using the unified SDK
1516
def example_unified_sdk():
1617
"""Example using the unified CodegenSDK."""
1718
print("=== Unified SDK Example ===")
18-
19+
1920
# Initialize the SDK with your API token
2021
sdk = CodegenSDK(token=os.getenv("CODEGEN_API_TOKEN"))
21-
22+
2223
# Use agents
2324
print("Running an agent task...")
2425
task = sdk.agents.run("Analyze the codebase and suggest improvements")
2526
print(f"Task created: {task.id}")
2627
print(f"Status: {task.status}")
2728
print(f"Web URL: {task.web_url}")
28-
29+
2930
# List organizations
3031
print("\nListing organizations...")
3132
orgs = sdk.organizations.list()
3233
for org in orgs:
3334
print(f"- {org.name} (ID: {org.id})")
34-
35+
3536
# Get users in the first organization
3637
if orgs:
3738
print(f"\nListing users in organization '{orgs[0].name}'...")
@@ -44,17 +45,17 @@ def example_unified_sdk():
4445
def example_individual_components():
4546
"""Example using individual SDK components."""
4647
print("\n=== Individual Components Example ===")
47-
48+
4849
token = os.getenv("CODEGEN_API_TOKEN")
49-
50+
5051
# Enhanced Agent with better error handling
5152
print("Using enhanced Agent...")
5253
agent = Agent(token=token)
53-
54+
5455
try:
5556
task = agent.run("Create a simple Python function")
5657
print(f"Agent task: {task.id}")
57-
58+
5859
# Check task status with new helper methods
5960
if task.is_running():
6061
print("Task is currently running...")
@@ -64,55 +65,55 @@ def example_individual_components():
6465
print("Task was successful!")
6566
elif task.is_failed():
6667
print("Task failed.")
67-
68+
6869
# Get task by ID
6970
retrieved_task = agent.get_task(task.id)
7071
print(f"Retrieved task: {retrieved_task.id}")
71-
72+
7273
except Exception as e:
7374
print(f"Error: {e}")
74-
75+
7576
# Organizations management
7677
print("\nUsing Organizations...")
7778
orgs_client = Organizations(token=token)
78-
79+
7980
try:
8081
# List with pagination
8182
page_result = orgs_client.get_page(page=1, page_size=10)
8283
print(f"Organizations page: {page_result['page']}/{page_result['pages']}")
8384
print(f"Total organizations: {page_result['total']}")
84-
85+
8586
# Iterate through all organizations
8687
print("All organizations:")
8788
for org in orgs_client.list_all():
8889
print(f"- {org.name} (ID: {org.id})")
8990
print(f" Settings: {org.settings}")
90-
91+
9192
except Exception as e:
9293
print(f"Error: {e}")
93-
94+
9495
# Users management
9596
print("\nUsing Users...")
9697
if orgs:
9798
users_client = Users(token=token, org_id=orgs[0].id)
98-
99+
99100
try:
100101
# List users with pagination
101102
page_result = users_client.get_page(page=1, page_size=5)
102103
print(f"Users page: {page_result['page']}/{page_result['pages']}")
103104
print(f"Total users: {page_result['total']}")
104-
105+
105106
# Find specific users
106107
user = users_client.find_by_github_username("example-user")
107108
if user:
108109
print(f"Found user: {user.github_username}")
109-
110+
110111
# Get user by ID
111-
if page_result['items']:
112-
first_user = page_result['items'][0]
112+
if page_result["items"]:
113+
first_user = page_result["items"][0]
113114
retrieved_user = users_client.get(first_user.id)
114115
print(f"Retrieved user: {retrieved_user.github_username}")
115-
116+
116117
except Exception as e:
117118
print(f"Error: {e}")
118119

@@ -121,9 +122,9 @@ def example_individual_components():
121122
def example_error_handling():
122123
"""Example demonstrating error handling."""
123124
print("\n=== Error Handling Example ===")
124-
125-
from codegen.exceptions import AuthenticationError, NotFoundError, CodegenError
126-
125+
126+
from codegen.exceptions import AuthenticationError, CodegenError, NotFoundError
127+
127128
# Invalid token example
128129
try:
129130
sdk = CodegenSDK(token="invalid-token")
@@ -133,7 +134,7 @@ def example_error_handling():
133134
print(f"Status code: {e.status_code}")
134135
except CodegenError as e:
135136
print(f"API error: {e.message}")
136-
137+
137138
# Not found example
138139
try:
139140
sdk = CodegenSDK(token=os.getenv("CODEGEN_API_TOKEN"))
@@ -149,7 +150,7 @@ def example_error_handling():
149150
if not os.getenv("CODEGEN_API_TOKEN"):
150151
print("Please set the CODEGEN_API_TOKEN environment variable")
151152
exit(1)
152-
153+
153154
example_unified_sdk()
154155
example_individual_components()
155156
example_error_handling()

src/codegen/agents/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
"""Codegen Agent API module."""
22

33
from codegen.agents.agent import Agent
4+
from codegen.organizations import Organizations
45

56
# Import SDK components for backward compatibility and convenience
67
from codegen.sdk import CodegenSDK
7-
from codegen.organizations import Organizations
88
from codegen.users import Users
99

1010
__all__ = ["Agent", "CodegenSDK", "Organizations", "Users"]

src/codegen/agents/agent.py

Lines changed: 27 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import os
2-
from typing import Any, Dict, Optional, Union
2+
from typing import Any
33

44
from codegen_api_client.api.agents_api import AgentsApi
55
from codegen_api_client.api_client import ApiClient
@@ -26,7 +26,7 @@ def __init__(self, task_data: AgentRunResponse, api_client: ApiClient, org_id: i
2626

2727
def refresh(self) -> None:
2828
"""Refresh the job status from the API.
29-
29+
3030
Raises:
3131
CodegenError: If the API request fails
3232
"""
@@ -48,40 +48,34 @@ def refresh(self) -> None:
4848
self.status = job_dict.get("status")
4949
self.result = job_dict.get("result")
5050
except ApiException as e:
51-
error = handle_api_error(e.status, str(e), getattr(e, 'body', None))
51+
error = handle_api_error(e.status, str(e), getattr(e, "body", None))
5252
raise error from e
53-
53+
5454
def is_completed(self) -> bool:
5555
"""Check if the agent task is completed."""
56-
return self.status in ['completed', 'failed', 'cancelled']
57-
56+
return self.status in ["completed", "failed", "cancelled"]
57+
5858
def is_running(self) -> bool:
5959
"""Check if the agent task is currently running."""
60-
return self.status in ['running', 'pending']
61-
60+
return self.status in ["running", "pending"]
61+
6262
def is_successful(self) -> bool:
6363
"""Check if the agent task completed successfully."""
64-
return self.status == 'completed'
65-
64+
return self.status == "completed"
65+
6666
def is_failed(self) -> bool:
6767
"""Check if the agent task failed."""
68-
return self.status == 'failed'
69-
70-
def to_dict(self) -> Dict[str, Any]:
68+
return self.status == "failed"
69+
70+
def to_dict(self) -> dict[str, Any]:
7171
"""Convert agent task to dictionary."""
72-
return {
73-
'id': self.id,
74-
'org_id': self.org_id,
75-
'status': self.status,
76-
'result': self.result,
77-
'web_url': self.web_url
78-
}
72+
return {"id": self.id, "org_id": self.org_id, "status": self.status, "result": self.result, "web_url": self.web_url}
7973

8074

8175
class Agent:
8276
"""API client for interacting with Codegen AI agents."""
8377

84-
def __init__(self, token: str, org_id: Optional[Union[int, str]] = None, base_url: str = CODEGEN_BASE_API_URL):
78+
def __init__(self, token: str, org_id: int | str | None = None, base_url: str = CODEGEN_BASE_API_URL):
8579
"""Initialize a new Agent client.
8680
8781
Args:
@@ -98,7 +92,7 @@ def __init__(self, token: str, org_id: Optional[Union[int, str]] = None, base_ur
9892
self.agents_api = AgentsApi(self.api_client)
9993

10094
# Current job
101-
self.current_job: Optional[AgentTask] = None
95+
self.current_job: AgentTask | None = None
10296

10397
def run(self, prompt: str) -> AgentTask:
10498
"""Run an agent with the given prompt.
@@ -108,7 +102,7 @@ def run(self, prompt: str) -> AgentTask:
108102
109103
Returns:
110104
AgentTask: A task object representing the agent run
111-
105+
112106
Raises:
113107
CodegenError: If the API request fails
114108
"""
@@ -122,43 +116,39 @@ def run(self, prompt: str) -> AgentTask:
122116
self.current_job = job
123117
return job
124118
except ApiException as e:
125-
error = handle_api_error(e.status, str(e), getattr(e, 'body', None))
119+
error = handle_api_error(e.status, str(e), getattr(e, "body", None))
126120
raise error from e
127121

128-
def get_status(self) -> Optional[Dict[str, Any]]:
122+
def get_status(self) -> dict[str, Any] | None:
129123
"""Get the status of the current job.
130124
131125
Returns:
132126
dict: A dictionary containing job status information,
133127
or None if no job has been run.
134-
128+
135129
Raises:
136130
CodegenError: If the API request fails
137131
"""
138132
if self.current_job:
139133
self.current_job.refresh()
140134
return {"id": self.current_job.id, "status": self.current_job.status, "result": self.current_job.result, "web_url": self.current_job.web_url}
141135
return None
142-
143-
def get_task(self, task_id: Union[int, str]) -> AgentTask:
136+
137+
def get_task(self, task_id: int | str) -> AgentTask:
144138
"""Get a specific agent task by ID.
145-
139+
146140
Args:
147141
task_id: Agent task ID to retrieve
148-
142+
149143
Returns:
150144
AgentTask: The requested agent task
151-
145+
152146
Raises:
153147
CodegenError: If the API request fails or task is not found
154148
"""
155149
try:
156-
response = self.agents_api.get_agent_run_v1_organizations_org_id_agent_run_agent_run_id_get(
157-
org_id=int(self.org_id),
158-
agent_run_id=int(task_id),
159-
authorization=f"Bearer {self.token}"
160-
)
150+
response = self.agents_api.get_agent_run_v1_organizations_org_id_agent_run_agent_run_id_get(org_id=int(self.org_id), agent_run_id=int(task_id), authorization=f"Bearer {self.token}")
161151
return AgentTask(response, self.api_client, self.org_id)
162152
except ApiException as e:
163-
error = handle_api_error(e.status, str(e), getattr(e, 'body', None))
153+
error = handle_api_error(e.status, str(e), getattr(e, "body", None))
164154
raise error from e

src/codegen/cli/auth/decorators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def wrapper(*args, **kwargs):
3939

4040
# Remove the session parameter from the wrapper's signature so Typer doesn't see it
4141
sig = inspect.signature(f)
42-
new_params = [param for name, param in sig.parameters.items() if name != 'session']
42+
new_params = [param for name, param in sig.parameters.items() if name != "session"]
4343
new_sig = sig.replace(parameters=new_params)
4444
wrapper.__signature__ = new_sig # type: ignore[attr-defined]
4545

src/codegen/cli/cli.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import typer
22
from rich.traceback import install
33

4+
from codegen import __version__
5+
46
# Import config command (still a Typer app)
57
from codegen.cli.commands.config.main import config_command
6-
from codegen import __version__
78

89
install(show_locals=True)
910

@@ -14,12 +15,9 @@ def version_callback(value: bool):
1415
print(__version__)
1516
raise typer.Exit()
1617

18+
1719
# Create the main Typer app
18-
main = typer.Typer(
19-
name="codegen",
20-
help="Codegen CLI - Transform your code with AI.",
21-
rich_markup_mode="rich"
22-
)
20+
main = typer.Typer(name="codegen", help="Codegen CLI - Transform your code with AI.", rich_markup_mode="rich")
2321

2422
# Import the actual command functions
2523
from codegen.cli.commands.init.main import init
@@ -42,9 +40,7 @@ def version_callback(value: bool):
4240

4341

4442
@main.callback()
45-
def main_callback(
46-
version: bool = typer.Option(False, "--version", callback=version_callback, is_eager=True, help="Show version and exit")
47-
):
43+
def main_callback(version: bool = typer.Option(False, "--version", callback=version_callback, is_eager=True, help="Show version and exit")):
4844
"""Codegen CLI - Transform your code with AI."""
4945
pass
5046

src/codegen/cli/commands/config/main.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,7 @@ def get_config(key: str = typer.Argument(..., help="Configuration key to get")):
9090

9191

9292
@config_command.command(name="set")
93-
def set_config(
94-
key: str = typer.Argument(..., help="Configuration key to set"),
95-
value: str = typer.Argument(..., help="Configuration value to set")
96-
):
93+
def set_config(key: str = typer.Argument(..., help="Configuration key to set"), value: str = typer.Argument(..., help="Configuration value to set")):
9794
"""Set a configuration value and write to .env"""
9895
config = _get_user_config()
9996
if not config.has_key(key):

0 commit comments

Comments
 (0)