Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ Released under the Universal Permissive License v1.0 as shown at
<https://oss.oracle.com/licenses/upl/>.

[contributing]: https://github.com/oracle/python-select-ai/blob/main/CONTRIBUTING.md
[documentation]: https://docs.oracle.com/en/cloud/paas/autonomous-database/serverless/pysai/
[documentation]: https://oracle.github.io/python-select-ai/
[ghdiscussions]: https://github.com/oracle/python-select-ai/discussions
[ghissues]: https://github.com/oracle/python-select-ai/issues
[samples]: https://github.com/oracle/python-select-ai/tree/main/samples
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ test = [
Homepage = "https://github.com/oracle/python-select-ai"
Repository = "https://github.com/oracle/python-select-ai"
Issues = "https://github.com/oracle/python-select-ai/issues"
Documentation = "https://docs.oracle.com/en/cloud/paas/autonomous-database/serverless/pysai/"
Documentation = "https://oracle.github.io/python-select-ai/"

[tool.setuptools.packages.find]
where = ["src"]
Expand Down
2 changes: 1 addition & 1 deletion samples/agent/task_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

task = Task(
task_name="ANALYZE_MOVIE_TASK",
description="Movie task involving a human",
description="Search for movies in the database",
attributes=TaskAttributes(
instruction="Help the user with their request about movies. "
"User question: {query}. "
Expand Down
19 changes: 12 additions & 7 deletions src/select_ai/_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ def _bool(value: Any) -> bool:
raise ValueError(f"Invalid boolean value: {value}")


def _is_json(field, value) -> bool:
if field.type in (
typing.List[Mapping],
typing.Optional[Mapping],
typing.Optional[List[str]],
typing.Optional[List[typing.Mapping]],
) and isinstance(value, (str, bytes, bytearray)):
return True
return False


@dataclass
class SelectAIDataClass(ABC):
"""SelectAIDataClass is an abstract container for all data
Expand Down Expand Up @@ -65,13 +76,7 @@ def __post_init__(self):
setattr(self, field.name, _bool(value))
elif field.type is typing.Optional[float]:
setattr(self, field.name, float(value))
elif field.type is typing.Optional[Mapping] and isinstance(
value, (str, bytes, bytearray)
):
setattr(self, field.name, json.loads(value))
elif field.type is typing.Optional[
List[typing.Mapping]
] and isinstance(value, (str, bytes, bytearray)):
elif _is_json(field, value):
setattr(self, field.name, json.loads(value))
else:
setattr(self, field.name, value)
7 changes: 4 additions & 3 deletions src/select_ai/agent/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
# -----------------------------------------------------------------------------


from .core import Agent, AgentAttributes
from .task import Task, TaskAttributes
from .team import Team, TeamAttributes
from .core import Agent, AgentAttributes, AsyncAgent
from .task import AsyncTask, Task, TaskAttributes
from .team import AsyncTeam, Team, TeamAttributes
from .tool import (
AsyncTool,
EmailNotificationToolParams,
HTTPToolParams,
HumanToolParams,
Expand Down
231 changes: 224 additions & 7 deletions src/select_ai/agent/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,26 @@
# http://oss.oracle.com/licenses/upl.
# -----------------------------------------------------------------------------

import json
from abc import ABC
from dataclasses import dataclass
from typing import (
Any,
AsyncGenerator,
Iterator,
List,
Mapping,
Optional,
Union,
)

import oracledb

from select_ai import BaseProfile
from select_ai._abc import SelectAIDataClass
from select_ai._enums import StrEnum
from select_ai.agent.sql import (
GET_USER_AI_AGENT,
GET_USER_AI_AGENT_ATTRIBUTES,
LIST_USER_AI_AGENTS,
)
from select_ai.async_profile import AsyncProfile
from select_ai.db import async_cursor, cursor
from select_ai.errors import AgentNotFoundError
from select_ai.profile import Profile


@dataclass
Expand Down Expand Up @@ -292,3 +285,227 @@ def set_attribute(self, attribute_name: str, attribute_value: Any) -> None:
keyword_parameters=parameters,
)
self.attributes = self._get_attributes(agent_name=self.agent_name)


class AsyncAgent(BaseAgent):
"""
select_ai.agent.AsyncAgent class lets you create, delete, enable, disable
and list AI agents asynchronously

:param str agent_name: The name of the AI Agent
:param str description: Optional description of the AI agent
:param select_ai.agent.AgentAttributes attributes: AI agent attributes

"""

@staticmethod
async def _get_attributes(agent_name: str) -> AgentAttributes:
async with async_cursor() as cr:
await cr.execute(
GET_USER_AI_AGENT_ATTRIBUTES, agent_name=agent_name.upper()
)
attributes = await cr.fetchall()
if attributes:
post_processed_attributes = {}
for k, v in attributes:
if isinstance(v, oracledb.AsyncLOB):
post_processed_attributes[k] = await v.read()
else:
post_processed_attributes[k] = v
return AgentAttributes(**post_processed_attributes)
else:
raise AgentNotFoundError(agent_name=agent_name)

@staticmethod
async def _get_description(agent_name: str) -> Union[str, None]:
async with async_cursor() as cr:
await cr.execute(GET_USER_AI_AGENT, agent_name=agent_name.upper())
agent = await cr.fetchone()
if agent:
if agent[1] is not None:
return await agent[1].read()
else:
return None
else:
raise AgentNotFoundError(agent_name)

async def create(
self, enabled: Optional[bool] = True, replace: Optional[bool] = False
):
"""
Register a new AI Agent within the Select AI framework

:param bool enabled: Whether the AI Agent should be enabled.
Default value is True.

:param bool replace: Whether the AI Agent should be replaced.
Default value is False.

"""
if self.agent_name is None:
raise AttributeError("Agent must have a name")
if self.attributes is None:
raise AttributeError("Agent must have attributes")

parameters = {
"agent_name": self.agent_name,
"attributes": self.attributes.json(),
}
if self.description:
parameters["description"] = self.description

if not enabled:
parameters["status"] = "disabled"

async with async_cursor() as cr:
try:
await cr.callproc(
"DBMS_CLOUD_AI_AGENT.CREATE_AGENT",
keyword_parameters=parameters,
)
except oracledb.Error as err:
(err_obj,) = err.args
if err_obj.code in (20050, 20052) and replace:
await self.delete(force=True)
await cr.callproc(
"DBMS_CLOUD_AI_AGENT.CREATE_AGENT",
keyword_parameters=parameters,
)
else:
raise

async def delete(self, force: Optional[bool] = False):
"""
Delete AI Agent from the database

:param bool force: Force the deletion. Default value is False.

"""
async with async_cursor() as cr:
await cr.callproc(
"DBMS_CLOUD_AI_AGENT.DROP_AGENT",
keyword_parameters={
"agent_name": self.agent_name,
"force": force,
},
)

async def disable(self):
"""
Disable AI Agent
"""
async with async_cursor as cr:
await cr.callproc(
"DBMS_CLOUD_AI_AGENT.DISABLE_AGENT",
keyword_parameters={
"agent_name": self.agent_name,
},
)

async def enable(self):
"""
Enable AI Agent
"""
async with async_cursor as cr:
await cr.callproc(
"DBMS_CLOUD_AI_AGENT.ENABLE_AGENT",
keyword_parameters={
"agent_name": self.agent_name,
},
)

@classmethod
async def fetch(cls, agent_name: str) -> "AsyncAgent":
"""
Fetch AI Agent attributes from the Database and build a proxy object in
the Python layer

:param str agent_name: The name of the AI Agent

:return: select_ai.agent.Agent

:raises select_ai.errors.AgentNotFoundError:
If the AI Agent is not found

"""
attributes = await cls._get_attributes(agent_name=agent_name)
description = await cls._get_description(agent_name=agent_name)
return cls(
agent_name=agent_name,
attributes=attributes,
description=description,
)

@classmethod
async def list(
cls, agent_name_pattern: Optional[str] = ".*"
) -> AsyncGenerator["AsyncAgent", None]:
"""
List AI agents matching a pattern

:param str agent_name_pattern: Regular expressions can be used
to specify a pattern. Function REGEXP_LIKE is used to perform the
match. Default value is ".*" i.e. match all agent names.

:return: AsyncGenerator[AsyncAgent]
"""
async with async_cursor() as cr:
await cr.execute(
LIST_USER_AI_AGENTS,
agent_name_pattern=agent_name_pattern,
)
rows = await cr.fetchall()
for row in rows:
agent_name = row[0]
if row[1]:
description = await row[1].read() # Oracle.AsyncLOB
else:
description = None
attributes = await cls._get_attributes(agent_name=agent_name)
yield cls(
agent_name=agent_name,
description=description,
attributes=attributes,
)

async def set_attributes(self, attributes: AgentAttributes) -> None:
"""
Set AI Agent attributes

:param select_ai.agent.AgentAttributes attributes: Multiple attributes
can be specified by passing an AgentAttributes object
"""
parameters = {
"object_name": self.agent_name,
"object_type": "agent",
"attributes": attributes.json(),
}
async with async_cursor() as cr:
await cr.callproc(
"DBMS_CLOUD_AI_AGENT.SET_ATTRIBUTES",
keyword_parameters=parameters,
)
self.attributes = await self._get_attributes(
agent_name=self.agent_name
)

async def set_attribute(
self, attribute_name: str, attribute_value: Any
) -> None:
"""
Set a single AI Agent attribute specified using name and value
"""
parameters = {
"object_name": self.agent_name,
"object_type": "agent",
"attribute_name": attribute_name,
"attribute_value": attribute_value,
}
async with async_cursor() as cr:
await cr.callproc(
"DBMS_CLOUD_AI_AGENT.SET_ATTRIBUTE",
keyword_parameters=parameters,
)
self.attributes = await self._get_attributes(
agent_name=self.agent_name
)
12 changes: 7 additions & 5 deletions src/select_ai/agent/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,19 +62,21 @@


GET_USER_AI_AGENT_TEAM = """
SELECT t.tool_name, t.description
SELECT t.agent_team_name as team_name, t.description
FROM USER_AI_AGENT_TEAMS t
WHERE t.team_name = :team_name
WHERE t.agent_team_name = :team_name
"""


GET_USER_AI_AGENT_TEAM_ATTRIBUTES = """
SELECT attribute_name, attribute_value
FROM USER_AI_AGENT_TEAM_ATTRIBUTES
WHERE team_name = :team_name
WHERE agent_team_name = :team_name
"""


LIST_USER_AI_AGENT_TEAMS = """
SELECT t.tool_name, t.description
SELECT t.AGENT_TEAM_NAME as team_name, description
FROM USER_AI_AGENT_TEAMS t
WHERE REGEXP_LIKE(t.team_name, :team_name_pattern, 'i')
WHERE REGEXP_LIKE(t.AGENT_TEAM_NAME, :team_name_pattern, 'i')
"""
Loading