Skip to content

Commit

Permalink
feat: add API object creation from settings (#137)
Browse files Browse the repository at this point in the history
Signed-off-by: Panos Vagenas <35837085+vagenas@users.noreply.github.com>
  • Loading branch information
vagenas authored Sep 26, 2023
1 parent 0d9781c commit 8eeb789
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 10 deletions.
20 changes: 19 additions & 1 deletion deepsearch/core/client/settings_manager.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Dict, Optional

Expand All @@ -20,6 +21,19 @@
LEGACY_CFG_FILENAME = "deepsearch_toolkit.json"


class KnownProfile(str, Enum):
SDS = "sds"
# DS_EXPERIENCE = "ds-experience" # TODO: uncomment once applicable
DS_INTERNAL = "ds-internal"


HOST_BY_PROFILE = {
KnownProfile.SDS.value: "https://sds.app.accelerate.science",
# KnownProfile.DS_EXPERIENCE.value: "https://deepsearch-experience.res.ibm.com", # TODO: uncomment once applicable
KnownProfile.DS_INTERNAL.value: "https://cps.foc-deepsearch.zurich.ibm.com",
}


@dataclass
class ProfileSettingsEntry:
path: Path
Expand Down Expand Up @@ -155,7 +169,11 @@ def _safe_get_profile_entry(self, profile_name: str) -> ProfileSettingsEntry:
try:
return self._profile_cache[profile_name]
except KeyError:
raise ValueError(f'No profile "{profile_name}" configured')
if url := HOST_BY_PROFILE.get(profile_name):
msg = f'Profile "{profile_name}" not configured. To set up, go to: {url}/credentials'
else:
msg = f'No profile "{profile_name}" configured. To set up, check: `deepsearch profile config --help`'
raise ValueError(msg)

def _validate_existing_profile_name(self, profile_name: str) -> None:
_ = self._safe_get_profile_entry(profile_name=profile_name)
Expand Down
33 changes: 25 additions & 8 deletions deepsearch/cps/client/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Optional

import requests
from pydantic import ValidationError

import deepsearch.cps.apis.user
from deepsearch.core.client import (
Expand Down Expand Up @@ -149,22 +150,38 @@ def refresh_token(self, admin: bool = False):

@classmethod
def from_env(cls, profile_name: Optional[str] = None) -> CpsApi:
settings = settings_mgr.get_profile_settings(profile_name=profile_name)
return cls._from_settings(settings=settings)
"""Create an API object resolving the required settings from the environment if possible, otherwise from a stored profile.
@classmethod
def from_cli_prompt(cls) -> CpsApi:
settings = ProfileSettings.from_cli_prompt()
return cls._from_settings(settings=settings)
Args:
profile_name (Optional[str], optional): profile to use if resolution from environment not possible. Defaults to None (active profile).
Returns:
CpsApi: the created API object
"""
try:
settings = ProfileSettings()
except ValidationError:
settings = settings_mgr.get_profile_settings(profile_name=profile_name)
return cls.from_settings(settings=settings)

@classmethod
def _from_settings(cls, settings: ProfileSettings) -> CpsApi:
def from_settings(cls, settings: ProfileSettings) -> CpsApi:
"""Create an API object from the provided settings.
Args:
settings (ProfileSettings): the settings to use.
Returns:
CpsApi: the created API object
"""
auth = DeepSearchKeyAuth(
username=settings.username,
api_key=settings.api_key.get_secret_value(),
)
config = DeepSearchConfig(
host=settings.host, auth=auth, verify_ssl=settings.verify_ssl
host=settings.host,
auth=auth,
verify_ssl=settings.verify_ssl,
)
client = CpsApiClient(config)
return cls(client)
20 changes: 19 additions & 1 deletion docs/guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ $ # -> outputs projects corresponding to "foo"

#### Usage in Python

To use the active profile (recommended usage pattern):
To use the active profile:
```python
from deepsearch.cps.client.api import CpsApi

Expand All @@ -103,6 +103,24 @@ print([p.name for p in api.projects.list()])
# -> outputs projects corresponding to "foo"
```

To use specific settings:
```python
from deepsearch.core.client.settings import ProfileSettings
from deepsearch.cps.client.api import CpsApi

# create a ProfileSettings object, e.g.:
settings = ProfileSettings(
# ...
)
# or interactively via the CLI:
# settings = ProfileSettings.from_cli_prompt()

api = CpsApi.from_settings(settings=settings)

print([p.name for p in api.projects.list()])
# -> outputs projects corresponding to provided settings
```

## Environment variables

Under the hood, the Toolkit leverages [Pydantic Settings with dotenv
Expand Down

0 comments on commit 8eeb789

Please sign in to comment.