Skip to content

Commit 33a2732

Browse files
Zeeeeparushilpatel0
andcommitted
Apply changes from commit 4d5c560
Original commit by Rushil Patel: feat: api client (codegen-sh#1027) # Motivation <!-- Why is this change necessary? --> # Content <!-- Please include a summary of the change --> # Testing <!-- How was the change tested? --> # Please check the following before marking your PR as ready for review - [ ] I have added tests for my changes - [ ] I have updated the documentation or added new documentation as needed --------- Co-authored-by: rushilpatel0 <[email protected]>
1 parent a797199 commit 33a2732

33 files changed

+7307
-5
lines changed

src/codegen/__init__.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
1-
from codegen.agents.code_agent import CodeAgent
1+
from codegen.agents.agent import Agent
22
from codegen.cli.sdk.decorator import function
33
from codegen.cli.sdk.functions import Function
44
from codegen.extensions.events.codegen_app import CodegenApp
5-
6-
# from codegen.extensions.index.file_index import FileIndex
7-
# from codegen.extensions.langchain.agent import create_agent_with_tools, create_codebase_agent
85
from codegen.sdk.core.codebase import Codebase
96
from codegen.shared.enums.programming_language import ProgrammingLanguage
107

11-
__all__ = ["CodeAgent", "Codebase", "CodegenApp", "Function", "ProgrammingLanguage", "function"]
8+
__all__ = ["Agent", "Codebase", "CodegenApp", "Function", "ProgrammingLanguage", "function"]

src/codegen/agents/README.md

+124
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# Codegen Agents - Python SDK
2+
3+
This module provides a Python client for interacting with the Codegen AI agents API.
4+
5+
## Installation
6+
7+
The Codegen Agent SDK is included as part of the Codegen package. Ensure you have the latest version installed:
8+
9+
```bash
10+
pip install codegen
11+
```
12+
13+
## Usage
14+
15+
### Basic Example
16+
17+
```python
18+
from codegen.agents.agent import Agent
19+
20+
# Initialize the Agent with your organization ID and API token
21+
agent = Agent(
22+
org_id="11", # Your organization ID
23+
token="your_api_token_here", # Your API authentication token
24+
base_url="https://codegen-sh-rest-api.modal.run", # Optional - defaults to this URL
25+
)
26+
27+
# Run an agent with a prompt
28+
task = agent.run(prompt="Which github repos can you currently access?")
29+
30+
# Check the initial status
31+
print(task.status) # Returns the current status of the task (e.g., "queued", "in_progress", etc.)
32+
33+
# Refresh the task to get updated status
34+
task.refresh()
35+
36+
# Check the updated status
37+
print(task.status)
38+
39+
# Once task is complete, you can access the result
40+
if task.status == "completed":
41+
print(task.result)
42+
```
43+
44+
### Agent Class
45+
46+
The `Agent` class is the main entry point for interacting with Codegen AI agents:
47+
48+
```python
49+
Agent(token: str, org_id: Optional[int] = None, base_url: Optional[str] = CODEGEN_BASE_API_URL)
50+
```
51+
52+
Parameters:
53+
54+
- `token` (required): Your API authentication token
55+
- `org_id` (optional): Your organization ID. If not provided, defaults to environment variable `CODEGEN_ORG_ID` or "1"
56+
- `base_url` (optional): API base URL. Defaults to "https://codegen-sh-rest-api.modal.run"
57+
58+
### Methods
59+
60+
#### run()
61+
62+
```python
63+
run(prompt: str) -> AgentTask
64+
```
65+
66+
Runs an agent with the given prompt.
67+
68+
Parameters:
69+
70+
- `prompt` (required): The instruction for the agent to execute
71+
72+
Returns:
73+
74+
- An `AgentTask` object representing the running task
75+
76+
#### get_status()
77+
78+
```python
79+
get_status() -> Optional[Dict[str, Any]]
80+
```
81+
82+
Gets the status of the current task.
83+
84+
Returns:
85+
86+
- A dictionary containing task status information (`id`, `status`, `result`), or `None` if no task has been run
87+
88+
### AgentTask Class
89+
90+
The `AgentTask` class represents a running or completed agent task:
91+
92+
#### Attributes
93+
94+
- `id`: The unique identifier for the task
95+
- `org_id`: The organization ID
96+
- `status`: Current status of the task (e.g., "queued", "in_progress", "completed", "failed")
97+
- `result`: The task result (available when status is "completed")
98+
99+
#### Methods
100+
101+
##### refresh()
102+
103+
```python
104+
refresh() -> None
105+
```
106+
107+
Refreshes the task status from the API.
108+
109+
## Environment Variables
110+
111+
- `CODEGEN_ORG_ID`: Default organization ID (used if `org_id` is not provided)
112+
113+
## Error Handling
114+
115+
Handle potential API errors using standard try/except blocks:
116+
117+
```python
118+
try:
119+
task = agent.run(prompt="Your prompt here")
120+
task.refresh()
121+
print(task.status)
122+
except Exception as e:
123+
print(f"Error: {e}")
124+
```

src/codegen/agents/__init__.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"""Codegen Agent API module."""
2+
3+
from codegen.agents.agent import Agent
4+
5+
__all__ = ["Agent"]

src/codegen/agents/agent.py

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import os
2+
from typing import Any, Optional
3+
4+
from codegen.agents.client.openapi_client.api.agents_api import AgentsApi
5+
from codegen.agents.client.openapi_client.api_client import ApiClient
6+
from codegen.agents.client.openapi_client.configuration import Configuration
7+
from codegen.agents.client.openapi_client.models.agent_run_response import AgentRunResponse
8+
from codegen.agents.client.openapi_client.models.create_agent_run_input import CreateAgentRunInput
9+
from codegen.agents.constants import CODEGEN_BASE_API_URL
10+
11+
12+
class AgentTask:
13+
"""Represents an agent run job."""
14+
15+
def __init__(self, task_data: AgentRunResponse, api_client: ApiClient, org_id: int):
16+
self.id = task_data.id
17+
self.org_id = org_id
18+
self.status = task_data.status
19+
self.result = task_data.result
20+
self.web_url = task_data.web_url
21+
self._api_client = api_client
22+
self._agents_api = AgentsApi(api_client)
23+
24+
def refresh(self) -> None:
25+
"""Refresh the job status from the API."""
26+
if self.id is None:
27+
return
28+
29+
job_data = self._agents_api.get_agent_run_v1_organizations_org_id_agent_run_agent_run_id_get(
30+
agent_run_id=int(self.id), org_id=int(self.org_id), authorization=f"Bearer {self._api_client.configuration.access_token}"
31+
)
32+
33+
# Convert API response to dict for attribute access
34+
job_dict = {}
35+
if hasattr(job_data, "__dict__"):
36+
job_dict = job_data.__dict__
37+
elif isinstance(job_data, dict):
38+
job_dict = job_data
39+
40+
self.status = job_dict.get("status")
41+
self.result = job_dict.get("result")
42+
43+
44+
class Agent:
45+
"""API client for interacting with Codegen AI agents."""
46+
47+
def __init__(self, token: str, org_id: Optional[int] = None, base_url: Optional[str] = CODEGEN_BASE_API_URL):
48+
"""Initialize a new Agent client.
49+
50+
Args:
51+
token: API authentication token
52+
org_id: Optional organization ID. If not provided, default org will be used.
53+
"""
54+
self.token = token
55+
self.org_id = org_id or int(os.environ.get("CODEGEN_ORG_ID", "1")) # Default to org ID 1 if not specified
56+
57+
# Configure API client
58+
config = Configuration(host=base_url, access_token=token)
59+
self.api_client = ApiClient(configuration=config)
60+
self.agents_api = AgentsApi(self.api_client)
61+
62+
# Current job
63+
self.current_job = None
64+
65+
def run(self, prompt: str) -> AgentTask:
66+
"""Run an agent with the given prompt.
67+
68+
Args:
69+
prompt: The instruction for the agent to execute
70+
71+
Returns:
72+
Job: A job object representing the agent run
73+
"""
74+
run_input = CreateAgentRunInput(prompt=prompt)
75+
agent_run_response = self.agents_api.create_agent_run_v1_organizations_org_id_agent_run_post(
76+
org_id=int(self.org_id), create_agent_run_input=run_input, authorization=f"Bearer {self.token}", _headers={"Content-Type": "application/json"}
77+
)
78+
# Convert API response to dict for Job initialization
79+
80+
job = AgentTask(agent_run_response, self.api_client, self.org_id)
81+
self.current_job = job
82+
return job
83+
84+
def get_status(self) -> Optional[dict[str, Any]]:
85+
"""Get the status of the current job.
86+
87+
Returns:
88+
dict: A dictionary containing job status information,
89+
or None if no job has been run.
90+
"""
91+
if self.current_job:
92+
self.current_job.refresh()
93+
return {"id": self.current_job.id, "status": self.current_job.status, "result": self.current_job.result, "web_url": self.current_job.web_url}
94+
return None
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
.github/workflows/python.yml
2+
.gitignore
3+
.gitlab-ci.yml
4+
.openapi-generator-ignore
5+
.travis.yml
6+
README.md
7+
docs/AgentRunResponse.md
8+
docs/AgentsApi.md
9+
docs/CreateAgentRunInput.md
10+
docs/HTTPValidationError.md
11+
docs/OrganizationResponse.md
12+
docs/OrganizationSettings.md
13+
docs/OrganizationsApi.md
14+
docs/PageOrganizationResponse.md
15+
docs/PageUserResponse.md
16+
docs/UserResponse.md
17+
docs/UsersApi.md
18+
docs/ValidationError.md
19+
docs/ValidationErrorLocInner.md
20+
git_push.sh
21+
openapi_client/__init__.py
22+
openapi_client/api/__init__.py
23+
openapi_client/api/agents_api.py
24+
openapi_client/api/organizations_api.py
25+
openapi_client/api/users_api.py
26+
openapi_client/api_client.py
27+
openapi_client/api_response.py
28+
openapi_client/configuration.py
29+
openapi_client/exceptions.py
30+
openapi_client/models/__init__.py
31+
openapi_client/models/agent_run_response.py
32+
openapi_client/models/create_agent_run_input.py
33+
openapi_client/models/http_validation_error.py
34+
openapi_client/models/organization_response.py
35+
openapi_client/models/organization_settings.py
36+
openapi_client/models/page_organization_response.py
37+
openapi_client/models/page_user_response.py
38+
openapi_client/models/user_response.py
39+
openapi_client/models/validation_error.py
40+
openapi_client/models/validation_error_loc_inner.py
41+
openapi_client/py.typed
42+
openapi_client/rest.py
43+
pyproject.toml
44+
requirements.txt
45+
setup.cfg
46+
setup.py
47+
test-requirements.txt
48+
test/__init__.py
49+
test/test_agent_run_response.py
50+
test/test_agents_api.py
51+
test/test_create_agent_run_input.py
52+
test/test_http_validation_error.py
53+
test/test_organization_response.py
54+
test/test_organization_settings.py
55+
test/test_organizations_api.py
56+
test/test_page_organization_response.py
57+
test/test_page_user_response.py
58+
test/test_user_response.py
59+
test/test_users_api.py
60+
test/test_validation_error.py
61+
test/test_validation_error_loc_inner.py
62+
tox.ini
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
7.12.0

src/codegen/agents/client/README.md

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# openapi-client
2+
3+
API for application developers
4+
5+
This Python directory was automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project. However it the generated code was altered to make compatible with the rest of the project.
6+
7+
- API version: 1.0.0
8+
9+
### Steps to update client directory
10+
11+
1. Fetch the api schema from the API endpoint \[https://codegen-sh--rest-api.modal.run/api/openapi.json\](schema file)
12+
1. generate the client code with the following command:
13+
14+
```bash
15+
openapi-generator generate -i openapi.yaml -g python -o ./client
16+
```
17+
18+
3. This command will generate a lot of unused files we just need to include the files in the `openapi_client` directory to the project.
19+
20+
1. May need to fix the imports for `openapi_client` to be fully qualified import paths.
21+
22+
1. TODO: make updates more streamlined. Ideally setup this api client as it's own package so all it takes is to generate the new code, no addtional manual steps are needed.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# coding: utf-8
2+
3+
# flake8: noqa
4+
5+
"""
6+
Developer API
7+
8+
API for application developers
9+
10+
The version of the OpenAPI document: 1.0.0
11+
Generated by OpenAPI Generator (https://openapi-generator.tech)
12+
13+
Do not edit the class manually.
14+
""" # noqa: E501
15+
16+
__version__ = "1.0.0"
17+
18+
# import apis into sdk package
19+
from codegen.agents.client.openapi_client.api.agents_api import AgentsApi
20+
from codegen.agents.client.openapi_client.api.organizations_api import OrganizationsApi
21+
from codegen.agents.client.openapi_client.api.users_api import UsersApi
22+
23+
# import ApiClient
24+
from codegen.agents.client.openapi_client.api_response import ApiResponse
25+
from codegen.agents.client.openapi_client.api_client import ApiClient
26+
from codegen.agents.client.openapi_client.configuration import Configuration
27+
from codegen.agents.client.openapi_client.exceptions import OpenApiException
28+
from codegen.agents.client.openapi_client.exceptions import ApiTypeError
29+
from codegen.agents.client.openapi_client.exceptions import ApiValueError
30+
from codegen.agents.client.openapi_client.exceptions import ApiKeyError
31+
from codegen.agents.client.openapi_client.exceptions import ApiAttributeError
32+
from codegen.agents.client.openapi_client.exceptions import ApiException
33+
34+
# import models into sdk package
35+
from codegen.agents.client.openapi_client.models.agent_run_response import AgentRunResponse
36+
from codegen.agents.client.openapi_client.models.create_agent_run_input import CreateAgentRunInput
37+
from codegen.agents.client.openapi_client.models.http_validation_error import HTTPValidationError
38+
from codegen.agents.client.openapi_client.models.organization_response import OrganizationResponse
39+
from codegen.agents.client.openapi_client.models.organization_settings import OrganizationSettings
40+
from codegen.agents.client.openapi_client.models.page_organization_response import PageOrganizationResponse
41+
from codegen.agents.client.openapi_client.models.page_user_response import PageUserResponse
42+
from codegen.agents.client.openapi_client.models.user_response import UserResponse
43+
from codegen.agents.client.openapi_client.models.validation_error import ValidationError
44+
from codegen.agents.client.openapi_client.models.validation_error_loc_inner import ValidationErrorLocInner
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# flake8: noqa
2+
3+
# import apis into api package
4+
from codegen.agents.client.openapi_client.api.agents_api import AgentsApi
5+
from codegen.agents.client.openapi_client.api.organizations_api import OrganizationsApi
6+
from codegen.agents.client.openapi_client.api.users_api import UsersApi

0 commit comments

Comments
 (0)