Skip to content

List models using open ai api #1234

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

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions ads/aqua/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,19 @@ def embeddings(
payload = {**(payload or {}), "input": input}
return self._request(payload=payload, headers=headers)

def list_models(self) -> Union[Dict[str, Any], Iterator[Mapping[str, Any]]]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the logic in this method here seems generic, should we call it fetch_data or get_json_response instead oflist_models? Also, docstrings need to be changed here.

"""Generate embeddings by sending a request to the endpoint.

Args:

Returns:
Union[Dict[str, Any], Iterator[Mapping[str, Any]]]: The server's response, typically including the generated embeddings.
"""
# headers = {"Content-Type", "application/json"}
response = self._client.get(self.endpoint)
json_response = response.json()
return json_response


class AsyncClient(BaseClient):
"""
Expand Down
35 changes: 35 additions & 0 deletions ads/aqua/extension/deployment_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,40 @@ def post(self, *args, **kwargs): # noqa: ARG002
)


class AquaModelListHandler(AquaAPIhandler):
"""Handler for Aqua model list params REST APIs.

Methods
-------
get(self, *args, **kwargs)
Validates parameters for the given model id.
"""

@handle_exceptions
def get(self, model_deployment_id):
"""
Handles streaming inference request for the Active Model Deployments
Raises
------
HTTPError
Raises HTTPError if inputs are missing or are invalid
"""

self.set_header("Content-Type", "application/json")
endpoint: str = ""
model_deployment = AquaDeploymentApp().get(model_deployment_id)
if model_deployment.endpoint.endswith("/"):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can simplify this with something like:
endpoint = model_deployment.endpoint.rstrip("/") + "/predict/v1/models"

endpoint = model_deployment.endpoint + "predict/v1/models"
else:
endpoint = model_deployment.endpoint + "/predict/v1/models"
aqua_client = Client(endpoint=endpoint)
try:
list_model_result = aqua_client.list_models()
return self.finish(list_model_result)
except Exception as ex:
raise HTTPError(500, str(ex))


__handlers__ = [
("deployments/?([^/]*)/params", AquaDeploymentParamsHandler),
("deployments/config/?([^/]*)", AquaDeploymentHandler),
Expand All @@ -381,4 +415,5 @@ def post(self, *args, **kwargs): # noqa: ARG002
("deployments/?([^/]*)/activate", AquaDeploymentHandler),
("deployments/?([^/]*)/deactivate", AquaDeploymentHandler),
("inference/stream/?([^/]*)", AquaDeploymentStreamingInferenceHandler),
("deployments/models/list/?([^/]*)", AquaModelListHandler),
]
24 changes: 24 additions & 0 deletions tests/unitary/with_extras/aqua/test_deployment_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@
from parameterized import parameterized

import ads.aqua
from ads.aqua.modeldeployment.entities import AquaDeploymentDetail
import ads.config
from ads.aqua.extension.deployment_handler import (
AquaDeploymentHandler,
AquaDeploymentParamsHandler,
AquaDeploymentStreamingInferenceHandler,
AquaModelListHandler,
)


Expand Down Expand Up @@ -260,3 +262,25 @@ def test_post(self, mock_get_model_deployment_response):
self.handler.write.assert_any_call("chunk1")
self.handler.write.assert_any_call("chunk2")
self.handler.finish.assert_called_once()


class AquaModelListHandlerTestCase(unittest.TestCase):
default_params = {
"data": [{"id": "id", "object": "object", "owned_by": "openAI", "created": 124}]
}

@patch.object(IPythonHandler, "__init__")
def setUp(self, ipython_init_mock) -> None:
ipython_init_mock.return_value = None
self.aqua_model_list_handler = AquaModelListHandler(MagicMock(), MagicMock())
self.aqua_model_list_handler._headers = MagicMock()

@patch("ads.aqua.modeldeployment.AquaDeploymentApp.get")
@patch("notebook.base.handlers.APIHandler.finish")
def test_get_model_list(self, mock_get, mock_finish):
"""Test to check the handler get method to return model list."""

mock_get.return_value = MagicMock(id="test_model_id")
mock_finish.side_effect = lambda x: x
result = self.aqua_model_list_handler.get(model_id="test_model_id")
mock_get.assert_called()