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

entity details #1109

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
104 changes: 104 additions & 0 deletions superagi/apm/knowledge_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
from sqlalchemy.orm import Session
from collections import defaultdict
from superagi.models.events import Event
from superagi.models.knowledges import Knowledges
from superagi.models.agent_execution_config import AgentExecutionConfiguration
from sqlalchemy import Integer
from fastapi import HTTPException
from typing import List, Dict


class KnowledgeHandler:
def __init__(self, session: Session, organisation_id: int):
self.session = session
self.organisation_id = organisation_id

Check warning on line 14 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L13-L14

Added lines #L13 - L14 were not covered by tests

def get_knowledge_usage(self) -> Dict[str, Dict[str, int]]:

knowledge_dict = {}

Check warning on line 18 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L18

Added line #L18 was not covered by tests

knowledge_data = self.session.query(Knowledges.id, Knowledges.name, Event.org_id == self.organisation_id).all()

Check warning on line 20 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L20

Added line #L20 was not covered by tests
for data in knowledge_data:
knowledge_dict[str(data.id)] = data.name

Check warning on line 22 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L22

Added line #L22 was not covered by tests

knowledge_calls = defaultdict(int)
knowledge_agents = defaultdict(set)
agent_tool_map = defaultdict(list)

Check warning on line 26 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L24-L26

Added lines #L24 - L26 were not covered by tests

tool_used_events = self.session.query(

Check warning on line 28 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L28

Added line #L28 was not covered by tests
Event.agent_id,
Event.event_property['tool_name'].label('tool_name')
).filter(Event.event_name == 'tool_used', Event.org_id == self.organisation_id)

for event in tool_used_events:
agent_tool_map[event.agent_id].append(event.tool_name)

Check warning on line 34 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L34

Added line #L34 was not covered by tests

agent_knowledge_map = {}

Check warning on line 36 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L36

Added line #L36 was not covered by tests

knowledge_configurations = self.session.query(

Check warning on line 38 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L38

Added line #L38 was not covered by tests
AgentExecutionConfiguration.agent_execution_id,
AgentExecutionConfiguration.value.label('knowledge_id')
).filter(AgentExecutionConfiguration.key == 'knowledge',
AgentExecutionConfiguration.value.isnot(None))

for config in knowledge_configurations:
agent_knowledge_map[config.agent_execution_id] = config.knowledge_id

Check warning on line 45 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L45

Added line #L45 was not covered by tests

run_completed_events = self.session.query(

Check warning on line 47 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L47

Added line #L47 was not covered by tests
Event.agent_id,
Event.event_property['calls'].cast(Integer).label('calls'),
Event.event_property['agent_execution_id'].cast(Integer).label('execution_id')
).filter(Event.event_name.in_(['run_completed', 'run_iteration_limit_crossed']), Event.org_id == self.organisation_id)

for event in run_completed_events:
if event.execution_id in agent_knowledge_map:
knowledge_id = agent_knowledge_map[event.execution_id]
knowledge_name = knowledge_dict.get(knowledge_id, knowledge_id)

Check warning on line 56 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L55-L56

Added lines #L55 - L56 were not covered by tests
if knowledge_name != 'None':
knowledge_calls[knowledge_name] += 1
knowledge_agents[knowledge_name].add(event.agent_id)

Check warning on line 59 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L58-L59

Added lines #L58 - L59 were not covered by tests

knowledge_agents_count = {k: len(v) for k, v in knowledge_agents.items()}

return {

Check warning on line 63 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L63

Added line #L63 was not covered by tests
'knowledge_calls': dict(knowledge_calls),
'knowledge_unique_agents': knowledge_agents_count
}


def get_knowledge_logs_by_name(self, knowledge_name: str):
knowledge_ids = self.session.query(Knowledges.id).filter_by(name=knowledge_name).filter(Knowledges.organisation_id==self.organisation_id).all()

Check warning on line 70 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L70

Added line #L70 was not covered by tests

if not knowledge_ids:
raise HTTPException(status_code=404, detail="Knowledge not found")

Check warning on line 73 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L73

Added line #L73 was not covered by tests

knowledge_ids = [id_[0] for id_ in knowledge_ids]
agent_execution_configuration = self.session.query(AgentExecutionConfiguration).filter(AgentExecutionConfiguration.key=='knowledge', AgentExecutionConfiguration.value.in_(map(str, knowledge_ids))).all()

Check warning on line 76 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L76

Added line #L76 was not covered by tests
agent_execution_ids = {config.agent_execution_id for config in agent_execution_configuration}

all_events = self.session.query(Event).filter(Event.org_id == self.organisation_id).all()

Check warning on line 79 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L79

Added line #L79 was not covered by tests
unique_agent_ids = {event.agent_id for event in all_events if event.event_property.get('agent_execution_id', None) in agent_execution_ids}

result_list = []

Check warning on line 82 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L82

Added line #L82 was not covered by tests
for agent_id in unique_agent_ids:
agent_specific_events = [event for event in all_events if event.agent_id == agent_id]
agent_dict = {}

Check warning on line 85 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L85

Added line #L85 was not covered by tests
for event in agent_specific_events:
event_property = event.event_property

Check warning on line 87 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L87

Added line #L87 was not covered by tests
if event.event_name in ('run_completed', 'run_iteration_limit_crossed') and event_property.get('agent_execution_id', None) in agent_execution_ids:
agent_dict['tokens_consumed'] = agent_dict.get('tokens_consumed', 0) + event_property.get('tokens_consumed', 0)
agent_dict['calls'] = agent_dict.get('calls', 0) + event_property.get('calls', 0)
agent_dict['created_at'] = event.created_at
agent_dict['event_name'] = event.event_name

Check warning on line 92 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L89-L92

Added lines #L89 - L92 were not covered by tests

elif event.event_name == 'run_created':
agent_dict['agent_execution_name'] = event_property.get('agent_execution_name', '')

Check warning on line 95 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L95

Added line #L95 was not covered by tests

elif event.event_name == 'agent_created':
agent_dict['agent_name'] = event_property.get('agent_name', '')
agent_dict['model'] = event_property.get('model', '')

Check warning on line 99 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L98-L99

Added lines #L98 - L99 were not covered by tests

if 'created_at' in agent_dict:
result_list.append(agent_dict)

Check warning on line 102 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L102

Added line #L102 was not covered by tests

return result_list

Check warning on line 104 in superagi/apm/knowledge_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/knowledge_handler.py#L104

Added line #L104 was not covered by tests
78 changes: 75 additions & 3 deletions superagi/apm/tools_handler.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from typing import List, Dict

from sqlalchemy import func
from sqlalchemy.orm import Session

from sqlalchemy import Integer
from collections import defaultdict
from fastapi import HTTPException
from superagi.models.events import Event
from superagi.models.tool import Tool
from superagi.models.toolkit import Toolkit
Expand Down Expand Up @@ -54,4 +55,75 @@
'toolkit': tool_and_toolkit.get(row.tool_name, None)
} for row in result]

return tool_usage
return tool_usage


def get_tool_wise_usage(self) -> Dict[str, Dict[str, int]]:

tool_agents = defaultdict(set)

Check warning on line 63 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L63

Added line #L63 was not covered by tests

tool_used_events = self.session.query(

Check warning on line 65 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L65

Added line #L65 was not covered by tests
Event.agent_id,
Event.event_property['tool_name'].label('tool_name')
).filter(Event.event_name == 'tool_used', Event.org_id == self.organisation_id)

agent_tool_map = defaultdict(list)
tool_calls = defaultdict(int)

Check warning on line 71 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L70-L71

Added lines #L70 - L71 were not covered by tests

for event in tool_used_events:
agent_tool_map[event.agent_id].append(event.tool_name)
tool_agents[event.tool_name].add(event.agent_id)
tool_calls[event.tool_name] += 1

Check warning on line 76 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L74-L76

Added lines #L74 - L76 were not covered by tests

tool_agents_count = {tool: len(agents) for tool, agents in tool_agents.items()}

return {

Check warning on line 80 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L80

Added line #L80 was not covered by tests
'tool_calls': dict(tool_calls),
'tool_unique_agents': tool_agents_count
}


def get_tool_logs_by_tool_name(self, tool_name: str):

is_tool_name_valid = self.session.query(Tool).filter_by(name=tool_name).first()

Check warning on line 88 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L88

Added line #L88 was not covered by tests

if not is_tool_name_valid:
raise HTTPException(status_code=404, detail="Tool not found")

Check warning on line 91 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L91

Added line #L91 was not covered by tests

formatted_tool_name = tool_name.lower().replace(" ", "")

Check warning on line 93 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L93

Added line #L93 was not covered by tests

all_events = self.session.query(Event).filter(Event.org_id == self.organisation_id).all()

Check warning on line 95 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L95

Added line #L95 was not covered by tests
unique_agent_ids = {event.agent_id for event in all_events if 'tool_name' in event.event_property and event.event_property['tool_name'] == formatted_tool_name}

result_list = []

Check warning on line 98 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L98

Added line #L98 was not covered by tests

for agent_id in unique_agent_ids:
agent_specific_events = [event for event in all_events if event.agent_id == agent_id]
agent_dict = {}

Check warning on line 102 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L102

Added line #L102 was not covered by tests

for event in agent_specific_events:
event_property = event.event_property

Check warning on line 105 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L105

Added line #L105 was not covered by tests

if event.event_name == 'tool_used':
if 'tool_name' in event_property and event_property['tool_name'] != formatted_tool_name:
other_tools = agent_dict.get('other_tools', [])
other_tools.append(event_property['tool_name'])
agent_dict['other_tools'] = other_tools

Check warning on line 111 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L109-L111

Added lines #L109 - L111 were not covered by tests
elif event_property['tool_name'] == formatted_tool_name:
agent_dict['created_at'] = event.created_at
agent_dict['event_name'] = event.event_name

Check warning on line 114 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L113-L114

Added lines #L113 - L114 were not covered by tests

elif event.event_name == 'run_completed' or event.event_name == 'run_iteration_limit_crossed':
agent_dict['tokens_consumed'] = agent_dict.get('tokens_consumed', 0) + event_property.get('tokens_consumed', 0)
agent_dict['calls'] = agent_dict.get('calls', 0) + event_property.get('calls', 0)

Check warning on line 118 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L117-L118

Added lines #L117 - L118 were not covered by tests

elif event.event_name == 'run_created':
agent_dict['agent_execution_name'] = event_property.get('agent_execution_name', '')

Check warning on line 121 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L121

Added line #L121 was not covered by tests

elif event.event_name == 'agent_created':
agent_dict['agent_name'] = event_property.get('agent_name', '')
agent_dict['model'] = event_property.get('model', '')

Check warning on line 125 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L124-L125

Added lines #L124 - L125 were not covered by tests

result_list.append(agent_dict)

Check warning on line 127 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L127

Added line #L127 was not covered by tests

return result_list

Check warning on line 129 in superagi/apm/tools_handler.py

View check run for this annotation

Codecov / codecov/patch

superagi/apm/tools_handler.py#L129

Added line #L129 was not covered by tests
37 changes: 37 additions & 0 deletions superagi/controllers/analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from superagi.apm.analytics_helper import AnalyticsHelper
from superagi.apm.event_handler import EventHandler
from superagi.apm.tools_handler import ToolsHandler
from superagi.apm.knowledge_handler import KnowledgeHandler
from fastapi_jwt_auth import AuthJWT
from fastapi_sqlalchemy import db
import logging
Expand Down Expand Up @@ -59,3 +60,39 @@
except Exception as e:
logging.error(f"Error while calculating tool usage: {str(e)}")
raise HTTPException(status_code=500, detail="Internal Server Error")


@router.get("/tools/usage", status_code=200)
def get_tool_usage(organisation=Depends(get_user_organisation)):
try:
return ToolsHandler(session=db.session, organisation_id=organisation.id).get_tool_wise_usage()
except Exception as e:
logging.error(f"Error while getting the tools' usage details: {str(e)}")
raise HTTPException(status_code=500, detail="Internal Server Error")

Check warning on line 71 in superagi/controllers/analytics.py

View check run for this annotation

Codecov / codecov/patch

superagi/controllers/analytics.py#L67-L71

Added lines #L67 - L71 were not covered by tests


@router.get("/knowledge/usage", status_code=200)
def get_knowledge_usage(organisation=Depends(get_user_organisation)):
try:
return KnowledgeHandler(session=db.session, organisation_id=organisation.id).get_knowledge_usage()
except Exception as e:
logging.error(f"Error while getting the knowledge usage details: {str(e)}")
raise HTTPException(status_code=500, detail="Internal Server Error")

Check warning on line 80 in superagi/controllers/analytics.py

View check run for this annotation

Codecov / codecov/patch

superagi/controllers/analytics.py#L76-L80

Added lines #L76 - L80 were not covered by tests


@router.get("/tools/{tool_name}/logs", status_code=200)
def get_tool_logs(tool_name: str, organisation=Depends(get_user_organisation)):
try:
return ToolsHandler(session=db.session, organisation_id=organisation.id).get_tool_logs_by_tool_name(tool_name)
except Exception as e:
logging.error(f"Error while getting tool log details: {str(e)}")
raise HTTPException(status_code=e.status_code, detail=e.detail)

Check warning on line 89 in superagi/controllers/analytics.py

View check run for this annotation

Codecov / codecov/patch

superagi/controllers/analytics.py#L85-L89

Added lines #L85 - L89 were not covered by tests


@router.get("/knowledge/{knowledge_name}/logs", status_code=200)
def get_knowledge_logs(knowledge_name: str, organisation=Depends(get_user_organisation)):
try:
return KnowledgeHandler(session=db.session, organisation_id=organisation.id).get_knowledge_logs_by_name(knowledge_name)
except Exception as e:
logging.error(f"Error while getting tool log details: {str(e)}")
raise HTTPException(status_code=e.status_code, detail=e.detail)

Check warning on line 98 in superagi/controllers/analytics.py

View check run for this annotation

Codecov / codecov/patch

superagi/controllers/analytics.py#L94-L98

Added lines #L94 - L98 were not covered by tests