|
| 1 | +__author__ = "lucaspavanelli" |
| 2 | + |
| 3 | +""" |
| 4 | +Copyright 2024 The aiXplain SDK authors |
| 5 | +
|
| 6 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +you may not use this file except in compliance with the License. |
| 8 | +You may obtain a copy of the License at |
| 9 | +
|
| 10 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +
|
| 12 | +Unless required by applicable law or agreed to in writing, software |
| 13 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +See the License for the specific language governing permissions and |
| 16 | +limitations under the License. |
| 17 | +
|
| 18 | +Author: Thiago Castro Ferreira and Lucas Pavanelli |
| 19 | +Date: August 15th 2024 |
| 20 | +Description: |
| 21 | + TeamAgent Factory Class |
| 22 | +""" |
| 23 | + |
| 24 | +import json |
| 25 | +import logging |
| 26 | + |
| 27 | +from aixplain.enums.supplier import Supplier |
| 28 | +from aixplain.factories.agent_factory import AgentFactory |
| 29 | +from aixplain.factories.agent_factory.utils import validate_llm, validate_name |
| 30 | +from aixplain.modules.agent import Agent |
| 31 | +from aixplain.modules.team_agent import TeamAgent |
| 32 | +from aixplain.utils import config |
| 33 | +from aixplain.factories.team_agent_factory.utils import build_team_agent |
| 34 | +from aixplain.utils.file_utils import _request_with_retry |
| 35 | +from typing import Dict, List, Optional, Text, Union |
| 36 | +from urllib.parse import urljoin |
| 37 | + |
| 38 | + |
| 39 | +class TeamAgentFactory: |
| 40 | + @classmethod |
| 41 | + def create( |
| 42 | + cls, |
| 43 | + name: Text, |
| 44 | + agents: List[Union[Text, Agent]], |
| 45 | + llm_id: Text = "669a63646eb56306647e1091", |
| 46 | + description: Text = "", |
| 47 | + api_key: Text = config.TEAM_API_KEY, |
| 48 | + supplier: Union[Dict, Text, Supplier, int] = "aiXplain", |
| 49 | + version: Optional[Text] = None, |
| 50 | + use_mentalist_and_inspector: bool = True, |
| 51 | + ) -> TeamAgent: |
| 52 | + """Create a new team agent in the platform.""" |
| 53 | + validate_name(name) |
| 54 | + # validate LLM ID |
| 55 | + validate_llm(llm_id) |
| 56 | + assert len(agents) > 0, "TeamAgent Onboarding Error: At least one agent must be provided." |
| 57 | + for agent in agents: |
| 58 | + if isinstance(agent, Text) is True: |
| 59 | + try: |
| 60 | + agent = AgentFactory.get(agent) |
| 61 | + except Exception: |
| 62 | + raise Exception(f"TeamAgent Onboarding Error: Agent {agent} does not exist.") |
| 63 | + else: |
| 64 | + assert isinstance(agent, Agent), "TeamAgent Onboarding Error: Agents must be instances of Agent class" |
| 65 | + |
| 66 | + mentalist_and_inspector_llm_id = None |
| 67 | + if use_mentalist_and_inspector is True: |
| 68 | + mentalist_and_inspector_llm_id = llm_id |
| 69 | + try: |
| 70 | + team_agent = None |
| 71 | + url = urljoin(config.BACKEND_URL, "sdk/agent-communities") |
| 72 | + headers = {"x-api-key": api_key} |
| 73 | + |
| 74 | + if isinstance(supplier, dict): |
| 75 | + supplier = supplier["code"] |
| 76 | + elif isinstance(supplier, Supplier): |
| 77 | + supplier = supplier.value["code"] |
| 78 | + |
| 79 | + agent_list = [] |
| 80 | + for idx, agent in enumerate(agents): |
| 81 | + agent_list.append({"assetId": agent.id, "number": idx, "type": "AGENT", "label": "AGENT"}) |
| 82 | + |
| 83 | + payload = { |
| 84 | + "name": name, |
| 85 | + "agents": agent_list, |
| 86 | + "links": [], |
| 87 | + "description": description, |
| 88 | + "llmId": llm_id, |
| 89 | + "supervisorId": llm_id, |
| 90 | + "plannerId": mentalist_and_inspector_llm_id, |
| 91 | + "supplier": supplier, |
| 92 | + "version": version, |
| 93 | + } |
| 94 | + |
| 95 | + logging.info(f"Start service for POST Create TeamAgent - {url} - {headers} - {json.dumps(payload)}") |
| 96 | + r = _request_with_retry("post", url, headers=headers, json=payload) |
| 97 | + if 200 <= r.status_code < 300: |
| 98 | + response = r.json() |
| 99 | + team_agent = build_team_agent(payload=response, api_key=api_key) |
| 100 | + else: |
| 101 | + error = r.json() |
| 102 | + error_msg = "TeamAgent Onboarding Error: Please contact the administrators." |
| 103 | + if "message" in error: |
| 104 | + msg = error["message"] |
| 105 | + if error["message"] == "err.name_already_exists": |
| 106 | + msg = "TeamAgent name already exists." |
| 107 | + elif error["message"] == "err.asset_is_not_available": |
| 108 | + msg = "Some tools are not available." |
| 109 | + error_msg = f"TeamAgent Onboarding Error (HTTP {r.status_code}): {msg}" |
| 110 | + logging.exception(error_msg) |
| 111 | + raise Exception(error_msg) |
| 112 | + except Exception as e: |
| 113 | + raise Exception(e) |
| 114 | + return team_agent |
| 115 | + |
| 116 | + @classmethod |
| 117 | + def list(cls) -> Dict: |
| 118 | + """List all agents available in the platform.""" |
| 119 | + url = urljoin(config.BACKEND_URL, "sdk/agent-communities") |
| 120 | + headers = {"x-api-key": config.TEAM_API_KEY, "Content-Type": "application/json"} |
| 121 | + |
| 122 | + payload = {} |
| 123 | + logging.info(f"Start service for GET List Agents - {url} - {headers} - {json.dumps(payload)}") |
| 124 | + try: |
| 125 | + r = _request_with_retry("get", url, headers=headers) |
| 126 | + resp = r.json() |
| 127 | + |
| 128 | + if 200 <= r.status_code < 300: |
| 129 | + agents, page_total, total = [], 0, 0 |
| 130 | + results = resp |
| 131 | + page_total = len(results) |
| 132 | + total = len(results) |
| 133 | + logging.info(f"Response for GET List Agents - Page Total: {page_total} / Total: {total}") |
| 134 | + for agent in results: |
| 135 | + agents.append(build_team_agent(agent)) |
| 136 | + return {"results": agents, "page_total": page_total, "page_number": 0, "total": total} |
| 137 | + else: |
| 138 | + error_msg = "Agent Listing Error: Please contact the administrators." |
| 139 | + if "message" in resp: |
| 140 | + msg = resp["message"] |
| 141 | + error_msg = f"Agent Listing Error (HTTP {r.status_code}): {msg}" |
| 142 | + logging.exception(error_msg) |
| 143 | + raise Exception(error_msg) |
| 144 | + except Exception as e: |
| 145 | + raise Exception(e) |
| 146 | + |
| 147 | + @classmethod |
| 148 | + def get(cls, agent_id: Text, api_key: Optional[Text] = None) -> Agent: |
| 149 | + """Get agent by id.""" |
| 150 | + url = urljoin(config.BACKEND_URL, f"sdk/agent-communities/{agent_id}") |
| 151 | + if config.AIXPLAIN_API_KEY != "": |
| 152 | + headers = {"x-aixplain-key": f"{config.AIXPLAIN_API_KEY}", "Content-Type": "application/json"} |
| 153 | + else: |
| 154 | + api_key = api_key if api_key is not None else config.TEAM_API_KEY |
| 155 | + headers = {"x-api-key": api_key, "Content-Type": "application/json"} |
| 156 | + logging.info(f"Start service for GET Agent - {url} - {headers}") |
| 157 | + r = _request_with_retry("get", url, headers=headers) |
| 158 | + resp = r.json() |
| 159 | + if 200 <= r.status_code < 300: |
| 160 | + return build_team_agent(resp) |
| 161 | + else: |
| 162 | + msg = "Please contact the administrators." |
| 163 | + if "message" in resp: |
| 164 | + msg = resp["message"] |
| 165 | + error_msg = f"Agent Get Error (HTTP {r.status_code}): {msg}" |
| 166 | + raise Exception(error_msg) |
0 commit comments