Skip to content

Commit

Permalink
Merge pull request #26 from Significant-Gravitas/swiftyos/agpt-280
Browse files Browse the repository at this point in the history
Typing fixes
  • Loading branch information
Swiftyos authored Feb 15, 2024
2 parents 8bf62d0 + c61e26b commit 8f4b98c
Show file tree
Hide file tree
Showing 17 changed files with 275 additions and 217 deletions.
37 changes: 1 addition & 36 deletions codex/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,48 +39,13 @@ async def popdb():
asyncio.run(popdb())


@cli.command()
def test() -> None:
def process_app(app_name: str) -> None:
from codex.architect.agent import create_code_graphs
from codex.deploy.agent import compile_application
from codex.deploy.packager import create_zip_file
from codex.developer.agent import write_code_graphs
from codex.requirements.agent import hardcoded_requirements

out_filename = f"{app_name.replace(' ', '_').lower()}.zip"
# Requirements agent develops the requirements for the application
r = hardcoded_requirements(app_name)
# Architect agent creates the code graphs for the requirements
graphs = create_code_graphs(r)
# Developer agent writes the code for the code graphs
completed_graphs = write_code_graphs(graphs)
# Delivery Agent builds the code and delivers it to the user
application = compile_application(r, completed_graphs)
zipfile = create_zip_file(application)
with open(f"workspace/{out_filename}", "wb") as f:
f.write(zipfile)

apps = [
"Availability Checker",
"Invoice Generator",
"Appointment Optimization Tool",
"Distance Calculator",
]

with ThreadPoolExecutor() as executor:
futures = [executor.submit(process_app, app_name) for app_name in apps]
for future in as_completed(futures):
future.result() # Waiting for each future to complete, you can handle exceptions here if needed


@cli.command()
def serve() -> None:
import uvicorn

from codex.app import app

uvicorn.run(app, host="0.0.0.0", port=os.environ.get("PORT", 8000))
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))


if __name__ == "__main__":
Expand Down
8 changes: 5 additions & 3 deletions codex/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging

from fastapi import APIRouter, Path, Query, Response
from prisma.models import CodexUser

import codex.database
from codex.api_model import (
Expand Down Expand Up @@ -76,7 +77,8 @@ async def update_user(user_id: int, user_update: UserUpdate):
Update a user's information by their unique identifier.
"""
try:
user = await codex.database.update_user(user_id, user_update)
user_update.id = user_id
user = await codex.database.update_user(user_update)
return UserResponse(
id=user.id,
discord_id=user.discord_id,
Expand All @@ -96,8 +98,8 @@ async def update_user(user_id: int, user_update: UserUpdate):

@core_routes.get("/user/", response_model=UsersListResponse, tags=["users"])
async def list_users(
page: int | None = Query(1, ge=1),
page_size: int | None = Query(10, ge=1),
page: int = Query(1, ge=1),
page_size: int = Query(10, ge=1),
):
"""
List all users.
Expand Down
22 changes: 10 additions & 12 deletions codex/api_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from enum import Enum
from typing import List, Optional

from prisma.enums import Role
from pydantic import BaseModel, EmailStr, Field


Expand All @@ -15,34 +16,32 @@ class Indentifiers(BaseModel):


class Pagination(BaseModel):
total_items: int = Field(..., description="Total number of items.", example=42)
total_pages: int = Field(..., description="Total number of pages.", example=97)
current_page: int = Field(..., description="Current_page page number.", example=1)
page_size: int = Field(..., description="Number of items per page.", example=25)
total_items: int = Field(..., description="Total number of items.", examples=[42])
total_pages: int = Field(..., description="Total number of pages.", examples=[97])
current_page: int = Field(
..., description="Current_page page number.", examples=[1]
)
page_size: int = Field(..., description="Number of items per page.", examples=[25])


###### USERS ######


class Role(str, Enum):
user = "USER"
admin = "ADMIN"


class UserBase(BaseModel):
discord_id: Optional[str] = Field(
None, description="The unique Discord ID of the user"
)
email: Optional[EmailStr] = Field(None, description="The email address of the user")
name: Optional[str] = Field(None, description="The name of the user")
role: Role = Field(default=Role.user, description="The role of the user")
role: Role = Field(default=Role.USER, description="The role of the user")


class UserCreate(UserBase):
password: str = Field(..., description="The password of the user")


class UserUpdate(BaseModel):
id: int = Field(..., description="The unique identifier of the user")
email: Optional[EmailStr] = Field(
None, description="The new email address of the user"
)
Expand Down Expand Up @@ -205,7 +204,6 @@ class CompiledRouteModel(BaseModel):
createdAt: datetime
description: str
code: str
# codeGraphId: Optional[int] = None # Omitted to simplify, can be included if needed


class DeliverableResponse(BaseModel):
Expand All @@ -216,7 +214,7 @@ class DeliverableResponse(BaseModel):


class DeliverablesListResponse(BaseModel):
completedApps: List[DeliverableResponse]
deliverables: List[DeliverableResponse]
pagination: Optional[Pagination] = None


Expand Down
4 changes: 3 additions & 1 deletion codex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@

app = FastAPI(
title="Codex",
description="Codex is a platform for creating, deploying, and managing web applications.",
description=(
"Codex is a platform for creating, deploying, and managing web applications."
),
summary="Codex API",
version="0.1",
)
Expand Down
9 changes: 1 addition & 8 deletions codex/architect/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ async def create_code_graphs(
Create the code graph for a given api route
"""
code_graphs = []
assert spec.apiRoutes, "No api routes found in the spec"
for api_route in spec.apiRoutes:
logger.info(f"Creating code graph for {api_route.path}")
codegraph = CodeGraphAIBlock(
Expand All @@ -33,11 +34,3 @@ async def create_code_graphs(
)
code_graphs.append(cg)
return ApplicationGraphs(code_graphs=code_graphs)


if __name__ == "__main__":
import codex.requirements.hardcoded

spec = codex.requirements.hardcoded.availability_checker_requirements()
ids = Indentifiers(user_id=1, app_id=1)
create_code_graphs(ids, spec)
67 changes: 36 additions & 31 deletions codex/architect/codegraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging

from prisma.models import CodeGraph as CodeGraphDBModel
from prisma.types import CodeGraphCreateInput

from codex.architect.model import CodeGraph, FunctionDef
from codex.common.ai_block import (
Expand Down Expand Up @@ -117,65 +118,69 @@ async def create_item(
}
)

add_database_data = {
"function_name": validated_response.response.function_name,
"apiPath": validated_response.response.api_route_spec.path,
"code_graph": validated_response.response.code_graph,
"imports": validated_response.response.imports,
"functionDefs": {"create": funciton_defs},
"routeSpec": {
"connect": {"id": validated_response.response.api_route_spec.id}
},
}
create_input = CodeGraphCreateInput(
**{
"function_name": validated_response.response.function_name,
"apiPath": validated_response.response.api_route_spec.path,
"code_graph": validated_response.response.code_graph,
"imports": validated_response.response.imports,
"functionDefs": {"create": funciton_defs},
"routeSpec": {
"connect": {"id": validated_response.response.api_route_spec.id}
},
}
)

if validated_response.response.api_route_spec.schemas:
add_database_data["databaseSchema"] = {
create_input["databaseSchema"] = {
"connect": {
"id": validated_response.response.api_route_spec.schemas.id
}
}

cg = await CodeGraphDBModel.prisma().create(data=add_database_data)
cg = await CodeGraphDBModel.prisma().create(data=create_input)
logger.debug(f"Created CodeGraph: {cg}")
return cg
except Exception as e:
print(f"Error saving code graph: {e}")

async def update_item(self, item: CodeGraph):
async def update_item(self, query_params: CodeGraphDBModel): # type: ignore
funciton_defs = []
for key, value in item.function_defs.items():
funciton_defs.append(
{
"name": value.name,
"doc_string": value.doc_string,
"args": value.args,
"return_type": value.return_type,
"function_template": value.function_template,
}
)
if query_params.functionDefs:
for value in query_params.functionDefs:
funciton_defs.append(
{
"name": value.name,
"doc_string": value.doc_string,
"args": value.args,
"return_type": value.return_type,
"function_template": value.function_template,
}
)

cg = await CodeGraphDBModel.prisma().update(
where={"id": item.id},
where={"id": query_params.id},
data={
"function_name": item.function_name,
"apiPath": item.api_route,
"code_graph": item.code_graph,
"imports": item.imports,
"function_name": query_params.function_name,
"apiPath": query_params.apiPath,
"code_graph": query_params.code_graph,
"imports": query_params.imports,
"functionDefs": {"create": funciton_defs},
},
)

return cg

async def get_item(self, item_id: str):
async def get_item(self, item_id: str): # type: ignore
cg = await CodeGraphDBModel.prisma().find_unique(where={"id": item_id})

return cg

async def delete_item(self, item_id: str):
# type: ignore
async def delete_item(self, item_id: str): # type: ignore
await CodeGraphDBModel.prisma().delete(where={"id": item_id})

async def list_items(self, item_id: str, page: int, page_size: int):
async def list_items(self, item_id: str, page: int, page_size: int): # type: ignore
cg = await CodeGraphDBModel.prisma().find_many(
skip=(page - 1) * page_size, take=page_size
)
Expand Down
11 changes: 3 additions & 8 deletions codex/architect/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

async def get_deliverable(
user_id: int, app_id: int, spec_id: int, deliverable_id: int
) -> DeliverableResponse:
) -> CompletedApp:
completed_app = await CompletedApp.prisma().find_unique_or_raise(
where={"id": deliverable_id},
include={"compiledRoutes": True},
Expand All @@ -33,14 +33,9 @@ async def list_deliverables(
page_size: int = 10,
) -> Tuple[List[CompletedApp], Pagination]:
skip = (page - 1) * page_size
total_items = await CompletedApp.count()
total_items = await CompletedApp.prisma().count(where={"specId": spec_id})
if total_items == 0:
return DeliverablesListResponse(
completedApps=[],
pagination=Pagination(
total_items=0, total_pages=0, current_page=0, page_size=0
),
)
return [], Pagination(total_items=0, total_pages=0, current_page=0, page_size=0)
total_pages = (total_items + page_size - 1) // page_size

completed_apps_data = await CompletedApp.prisma().find_many(
Expand Down
Loading

0 comments on commit 8f4b98c

Please sign in to comment.