-
Notifications
You must be signed in to change notification settings - Fork 17
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
ENG-1551 ai xplain sdk caching onboarded models pipelines and agents #389
Open
xainaz
wants to merge
6
commits into
development
Choose a base branch
from
ENG-1551-ai-xplain-sdk-caching-onboarded-models-pipelines-and-agents
base: development
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
292f441
caching for agents, pipelines and models
xainaz 6c8e3cf
formatting
xainaz 7872aa4
Agent Cache Class added
xainaz 92d8e28
removed unused imports
ahmetgunduz 6dec714
Solve conflict
thiago-aixplain 31d7b79
made requested changes and added functional tests
xainaz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import os | ||
import json | ||
import logging | ||
from datetime import datetime | ||
from enum import Enum | ||
from urllib.parse import urljoin | ||
from typing import Dict, Optional, List, Tuple, Union, Text | ||
from aixplain.utils import config | ||
from aixplain.utils.request_utils import _request_with_retry | ||
from aixplain.utils.cache_utils import save_to_cache, load_from_cache, CACHE_FOLDER | ||
from aixplain.enums import Supplier | ||
from aixplain.modules.agent.tool import Tool | ||
|
||
AGENT_CACHE_FILE = f"{CACHE_FOLDER}/agents.json" | ||
LOCK_FILE = f"{AGENT_CACHE_FILE}.lock" | ||
|
||
|
||
def load_agents(cache_expiry: Optional[int] = None) -> Tuple[Enum, Dict]: | ||
""" | ||
Load AI agents from cache or fetch from backend if not cached. | ||
Only agents with status "onboarded" should be cached. | ||
|
||
Args: | ||
cache_expiry (int, optional): Expiry time in seconds. Default is 24 hours. | ||
|
||
Returns: | ||
Tuple[Enum, Dict]: (Enum of agent IDs, Dictionary with agent details) | ||
""" | ||
if cache_expiry is None: | ||
cache_expiry = 86400 | ||
|
||
os.makedirs(CACHE_FOLDER, exist_ok=True) | ||
|
||
cached_data = load_from_cache(AGENT_CACHE_FILE, LOCK_FILE) | ||
|
||
if cached_data is not None: | ||
return parse_agents(cached_data) | ||
|
||
api_key = config.TEAM_API_KEY | ||
backend_url = config.BACKEND_URL | ||
url = urljoin(backend_url, "sdk/agents") | ||
headers = {"x-api-key": api_key, "Content-Type": "application/json"} | ||
|
||
try: | ||
response = _request_with_retry("get", url, headers=headers) | ||
response.raise_for_status() | ||
agents_data = response.json() | ||
except Exception as e: | ||
logging.error(f"Failed to fetch agents from API: {e}") | ||
return Enum("Agent", {}), {} | ||
|
||
onboarded_agents = [agent for agent in agents_data if agent.get("status", "").lower() == "onboarded"] | ||
|
||
save_to_cache(AGENT_CACHE_FILE, {"items": onboarded_agents}, LOCK_FILE) | ||
|
||
return parse_agents({"items": onboarded_agents}) | ||
|
||
|
||
def parse_agents(agents_data: Dict) -> Tuple[Enum, Dict]: | ||
""" | ||
Convert agent data into an Enum and dictionary format for easy use. | ||
|
||
Args: | ||
agents_data (Dict): JSON response with agents list. | ||
|
||
Returns: | ||
- agents_enum: Enum with agent IDs. | ||
- agents_details: Dictionary containing all agent parameters. | ||
""" | ||
if not agents_data["items"]: | ||
logging.warning("No onboarded agents found.") | ||
return Enum("Agent", {}), {} | ||
|
||
agents_enum = Enum( | ||
"Agent", | ||
{a["id"].upper().replace("-", "_"): a["id"] for a in agents_data["items"]}, | ||
type=str, | ||
) | ||
|
||
agents_details = { | ||
agent["id"]: { | ||
"id": agent["id"], | ||
"name": agent.get("name", ""), | ||
"description": agent.get("description", ""), | ||
"role": agent.get("role", ""), | ||
"tools": [Tool(t) if isinstance(t, dict) else t for t in agent.get("tools", [])], | ||
"llm_id": agent.get("llm_id", "6646261c6eb563165658bbb1"), | ||
"supplier": agent.get("supplier", "aiXplain"), | ||
"version": agent.get("version", "1.0"), | ||
"status": agent.get("status", "onboarded"), | ||
"created_at": agent.get("created_at", ""), | ||
"tasks": agent.get("tasks", []), | ||
**agent, | ||
} | ||
for agent in agents_data["items"] | ||
} | ||
|
||
return agents_enum, agents_details | ||
|
||
|
||
Agent, AgentDetails = load_agents() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
import os | ||
import json | ||
import time | ||
import logging | ||
from datetime import datetime | ||
from enum import Enum | ||
from urllib.parse import urljoin | ||
from typing import Dict, Optional, Union, Text | ||
from aixplain.utils import config | ||
from aixplain.utils.request_utils import _request_with_retry | ||
from aixplain.utils.cache_utils import save_to_cache, load_from_cache, CACHE_FOLDER | ||
from aixplain.enums import Supplier, Function | ||
|
||
CACHE_FILE = f"{CACHE_FOLDER}/models.json" | ||
LOCK_FILE = f"{CACHE_FILE}.lock" | ||
|
||
|
||
def load_models(cache_expiry: Optional[int] = None): | ||
""" | ||
Load models from cache or fetch from backend if not cached. | ||
Only models with status "onboarded" should be cached. | ||
|
||
Args: | ||
cache_expiry (int, optional): Expiry time in seconds. Default is user-configurable. | ||
""" | ||
|
||
api_key = config.TEAM_API_KEY | ||
backend_url = config.BACKEND_URL | ||
|
||
cached_data = load_from_cache(CACHE_FILE, LOCK_FILE) | ||
|
||
if cached_data is not None: | ||
|
||
return parse_models(cached_data) | ||
|
||
url = urljoin(backend_url, "sdk/models") | ||
headers = {"x-api-key": api_key, "Content-Type": "application/json"} | ||
|
||
response = _request_with_retry("get", url, headers=headers) | ||
if not 200 <= response.status_code < 300: | ||
raise Exception(f"Models could not be loaded, API key '{api_key}' might be invalid.") | ||
|
||
models_data = response.json() | ||
|
||
onboarded_models = [model for model in models_data["items"] if model["status"].lower() == "onboarded"] | ||
save_to_cache(CACHE_FILE, {"items": onboarded_models}, LOCK_FILE) | ||
|
||
return parse_models({"items": onboarded_models}) | ||
|
||
|
||
def parse_models(models_data): | ||
""" | ||
Convert model data into an Enum and dictionary format for easy use. | ||
|
||
Returns: | ||
- models_enum: Enum with model IDs. | ||
- models_details: Dictionary containing all model parameters. | ||
""" | ||
|
||
if not models_data["items"]: | ||
logging.warning("No onboarded models found.") | ||
return Enum("Model", {}), {} | ||
models_enum = Enum("Model", {m["id"].upper().replace("-", "_"): m["id"] for m in models_data["items"]}, type=str) | ||
|
||
models_details = { | ||
model["id"]: { | ||
"id": model["id"], | ||
"name": model.get("name", ""), | ||
"description": model.get("description", ""), | ||
"api_key": model.get("api_key", config.TEAM_API_KEY), | ||
"supplier": model.get("supplier", "aiXplain"), | ||
"version": model.get("version"), | ||
"function": model.get("function"), | ||
"is_subscribed": model.get("is_subscribed", False), | ||
"cost": model.get("cost"), | ||
"created_at": model.get("created_at"), | ||
"input_params": model.get("input_params"), | ||
"output_params": model.get("output_params"), | ||
"model_params": model.get("model_params"), | ||
**model, | ||
} | ||
for model in models_data["items"] | ||
} | ||
|
||
return models_enum, models_details | ||
|
||
|
||
Model, ModelDetails = load_models() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we need the entire data to populate Model class instance, why we wouldn't directly get the related Model class instance directly from the cache?
For example below the sample code should be used in the
ModelFactory