Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add error logging #215

Merged
merged 6 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 44 additions & 11 deletions app/api/agent_documents.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from fastapi import APIRouter, Depends
import logging

from fastapi import APIRouter, Depends, HTTPException, status
from starlette.requests import Request

from app.lib.auth.prisma import JWTBearer
from app.lib.models.agent_document import AgentDocument
from app.lib.prisma import prisma

logger = logging.getLogger(__name__)
router = APIRouter()


Expand All @@ -28,11 +31,22 @@ def parse_filter_params(request: Request):
)
async def create_agent_document(body: AgentDocument, token=Depends(JWTBearer())):
"""Create api token endpoint"""
agent_document = prisma.agentdocument.create(
{"agentId": body.agentId, "documentId": body.documentId}
)

return {"success": True, "data": agent_document}
try:
agent_document = prisma.agentdocument.create(
{"agentId": body.agentId, "documentId": body.documentId}
)
return {"success": True, "data": agent_document}
except Exception as e:
logger.error(
"""
Cannot create agent document for agent {body.agentId}
and document {body.documentId}
""",
exc_info=e,
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)


@router.get(
Expand All @@ -46,9 +60,16 @@ async def read_agent_documents(
token=Depends(JWTBearer()),
):
"""List api tokens endpoint"""
agent_documents = prisma.agentdocument.find_many(
where=filters, include={"document": expand}
)

try:
agent_documents = prisma.agentdocument.find_many(
where=filters, include={"document": expand}
)
except Exception as e:
logger.error("Cannot read agent documents", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

return {"success": True, "data": agent_documents}

Expand All @@ -60,7 +81,13 @@ async def read_agent_documents(
)
async def read_agent_document(agentDocumentId: str, token=Depends(JWTBearer())):
"""Get an agent document"""
agent_document = prisma.agentdocument.find_unique(where={"id": agentDocumentId})
try:
agent_document = prisma.agentdocument.find_unique(where={"id": agentDocumentId})
except Exception as e:
logger.error("Cannot read agent document {agentDocumentId}", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

return {"success": True, "data": agent_document}

Expand All @@ -73,6 +100,12 @@ async def read_agent_document(agentDocumentId: str, token=Depends(JWTBearer())):
async def delete_agent_document(agentDocumentId: str, token=Depends(JWTBearer())):
"""Delete agent document endpoint"""

prisma.agentdocument.delete(where={"id": agentDocumentId})
try:
prisma.agentdocument.delete(where={"id": agentDocumentId})
except Exception as e:
logger.error("Cannot delete agent document {agentDocumentId}", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

return {"success": True, "data": None}
50 changes: 43 additions & 7 deletions app/api/agent_tools.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
from fastapi import APIRouter, Depends
import logging

from fastapi import APIRouter, Depends, HTTPException, status
from starlette.requests import Request

from app.lib.auth.prisma import JWTBearer
from app.lib.models.agent_tool import AgentTool
from app.lib.prisma import prisma

logger = logging.getLogger(__name__)

router = APIRouter()


Expand All @@ -28,9 +32,19 @@ def parse_filter_params(request: Request):
)
async def create_agent_tool(body: AgentTool, token=Depends(JWTBearer())):
"""Create agent tool endpoint"""
agent_tool = prisma.agenttool.create(
{"agentId": body.agentId, "toolId": body.toolId}
)

try:
agent_tool = prisma.agenttool.create(
{"agentId": body.agentId, "toolId": body.toolId}
)
except Exception as e:
logger.error(
"Cannot create agent tool for agent {body.agentId} and tool {body.toolId}",
exc_info=e,
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

return {"success": True, "data": agent_tool}

Expand All @@ -46,7 +60,16 @@ async def read_agent_tools(
token=Depends(JWTBearer()),
):
"""List agent tools endpoint"""
agent_tools = prisma.agenttool.find_many(where=filters, include={"tool": expand})

try:
agent_tools = prisma.agenttool.find_many(
where=filters, include={"tool": expand}
)
except Exception as e:
logger.error("Cannot read agent tools", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

return {"success": True, "data": agent_tools}

Expand All @@ -58,7 +81,14 @@ async def read_agent_tools(
)
async def read_agent_tool(agentToolId: str, token=Depends(JWTBearer())):
"""Get an agent tool"""
agent_tool = prisma.agenttool.find_unique(where={"id": agentToolId})

try:
agent_tool = prisma.agenttool.find_unique(where={"id": agentToolId})
except Exception as e:
logger.error("Cannot read agent tool {agentToolId}", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

return {"success": True, "data": agent_tool}

Expand All @@ -71,6 +101,12 @@ async def read_agent_tool(agentToolId: str, token=Depends(JWTBearer())):
async def delete_agent_tool(agentToolId: str, token=Depends(JWTBearer())):
"""Delete agent tool endpoint"""

prisma.agenttool.delete(where={"id": agentToolId})
try:
prisma.agenttool.delete(where={"id": agentToolId})
except Exception as e:
logger.error("Cannot delete agent tool {agentToolId}", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

return {"success": True, "data": None}
40 changes: 27 additions & 13 deletions app/api/agents.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import logging
import threading
from queue import Queue
from typing import Any, Dict
Expand All @@ -15,6 +16,7 @@
from app.lib.models.agent import Agent, PredictAgent
from app.lib.prisma import prisma

logger = logging.getLogger(__name__)
router = APIRouter()


Expand All @@ -39,26 +41,30 @@ async def create_agent(body: Agent, token=Depends(JWTBearer())):
return {"success": True, "data": agent}

except Exception as e:
logger.error(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=e,
)


@router.get("/agents", name="List all agents", description="List all agents")
async def read_agents(token=Depends(JWTBearer())):
"""Agents endpoint"""
decoded = decodeJWT(token)
agents = prisma.agent.find_many(
where={"userId": decoded["userId"]},
include={
"user": True,
},
order={"createdAt": "desc"},
)

if agents:
return {"success": True, "data": agents}
try:
agents = prisma.agent.find_many(
where={"userId": decoded["userId"]},
include={
"user": True,
},
order={"createdAt": "desc"},
)
if agents or agents == []:
return {"success": True, "data": agents}
else:
raise Exception("Couldn't fetch agents from prisma")
except Exception as e:
logger.error(e)

raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
Expand All @@ -74,6 +80,7 @@ async def read_agent(agentId: str, token=Depends(JWTBearer())):
if agent:
return {"success": True, "data": agent}

logger.error(f"Agent with id: {agentId} not found")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Agent with id: {agentId} not found",
Expand All @@ -91,9 +98,9 @@ async def delete_agent(agentId: str, token=Depends(JWTBearer())):

return {"success": True, "data": None}
except Exception as e:
logger.error(f"Couldn't delete agent with id {agentId}", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=e,
)


Expand All @@ -106,7 +113,13 @@ async def patch_agent(agentId: str, body: dict, token=Depends(JWTBearer())):
if tags or tags == []:
body["tags"] = json.dumps(tags)

prisma.agent.update(data=body, where={"id": agentId})
try:
prisma.agent.update(data=body, where={"id": agentId})
except Exception as e:
logger.error(f"Couldn't patch agent with id {agentId}", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
return {"success": True, "data": None}


Expand Down Expand Up @@ -209,6 +222,7 @@ def conversation_run_thread(input: dict) -> None:

return {"success": True, "data": output}

logger.error(f"Cannot run agent with id: {agentId} not found")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Agent with id: {agentId} not found",
Expand Down
38 changes: 25 additions & 13 deletions app/api/api_tokens.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import logging

from fastapi import APIRouter, Depends, HTTPException, status

from app.lib.api_tokens import generate_api_token
from app.lib.auth.prisma import JWTBearer, decodeJWT
from app.lib.models.api_token import ApiToken
from app.lib.prisma import prisma

logger = logging.getLogger(__name__)

router = APIRouter()


Expand All @@ -29,23 +33,27 @@ async def create_api_token(body: ApiToken, token=Depends(JWTBearer())):
return {"success": True, "data": agent}

except Exception as e:
logger.error("Cannot create api token", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=e,
)


@router.get("/api-tokens", name="List API tokens", description="List all API tokens")
async def read_api_tokens(token=Depends(JWTBearer())):
"""List api tokens endpoint"""
decoded = decodeJWT(token)
api_tokens = prisma.apitoken.find_many(
where={"userId": decoded["userId"]}, include={"user": True}
)
try:
decoded = decodeJWT(token)
api_tokens = prisma.apitoken.find_many(
where={"userId": decoded["userId"]}, include={"user": True}
)

if api_tokens:
return {"success": True, "data": api_tokens}
if api_tokens or api_tokens == []:
return {"success": True, "data": api_tokens}
except Exception as e:
logger.error("Error finding api tokens for user {userId}", exc_info=e)

logger.error("Couldn't find api tokens")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="No agents found",
Expand All @@ -59,13 +67,17 @@ async def read_api_tokens(token=Depends(JWTBearer())):
)
async def read_api_token(tokenId: str, token=Depends(JWTBearer())):
"""Get an api token endpoint"""
api_token = prisma.apitoken.find_unique(
where={"id": tokenId}, include={"user": True}
)

if api_token:
return {"success": True, "data": api_token}
try:
api_token = prisma.apitoken.find_unique(
where={"id": tokenId}, include={"user": True}
)
if api_token:
return {"success": True, "data": api_token}
except Exception as e:
logger.error("Cannot find api token {tokenId}", exc_info=e)

logger.error("Cannot find api token {tokenId}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"API token with id: {tokenId} not found",
Expand All @@ -84,7 +96,7 @@ async def delete_api_token(tokenId: str, token=Depends(JWTBearer())):

return {"success": True, "data": None}
except Exception as e:
logger.error(f"Couldn't delete api token with id {tokenId}", exc_info=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=e,
)
Loading