diff --git a/python/qianfan/consts.py b/python/qianfan/consts.py index 6faa236a..13a03b1f 100644 --- a/python/qianfan/consts.py +++ b/python/qianfan/consts.py @@ -290,6 +290,16 @@ class Consts: PromptGetOptimizeTaskInfoAPI: str = "/wenxinworkshop/prompt/singleOptimize/info" PromptEvaluationAPI: str = "/wenxinworkshop/prompt/evaluate/predict" PromptEvaluationSummaryAPI: str = "/wenxinworkshop/prompt/evaluate/summary" + PromptV2BaseRouteAPI: str = "/v2/promptTemplates" + PromptCreateAction: str = "CreatePromptTemplate" + PromptInfoAction: str = "DescribePromptTemplate" + PromptUpdateAction: str = "ModifyPromptTemplate" + PromptDeleteAction: str = "DeletePromptTemplate" + PromptListAction: str = "DescribePromptTemplates" + PromptV2LabelBaseRouteAPI: str = "/v2/promptLabels" + PromptDeleteLabelAction: str = "DeletePromptLabel" + PromptCreateLabelAction: str = "CreatePromptLabel" + PromptGetLabelsAction: str = "DescribePromptLabels" AppListAPI: str = "/wenxinworkshop/service/appList" EBTokenizerAPI: str = "/rpc/2.0/ai_custom/v1/wenxinworkshop/tokenizer/erniebot" diff --git a/python/qianfan/resources/console/prompt.py b/python/qianfan/resources/console/prompt.py index 693b4a35..44334fa1 100644 --- a/python/qianfan/resources/console/prompt.py +++ b/python/qianfan/resources/console/prompt.py @@ -16,7 +16,7 @@ Prompt API """ import re -from typing import Any, List, Optional, Tuple, Union +from typing import Any, Dict, List, Optional, Tuple, Union from qianfan.consts import ( Consts, @@ -25,7 +25,7 @@ PromptType, ) from qianfan.errors import InvalidArgumentError -from qianfan.resources.console.utils import console_api_request +from qianfan.resources.console.utils import _get_console_v2_query, console_api_request from qianfan.resources.typing import Literal, QfRequest @@ -512,3 +512,445 @@ def _split_identifier(cls, identifier: str) -> Tuple[str, str]: left_id = identifier[: len(identifier) // 2] right_id = identifier[len(identifier) // 2 :] return left_id, right_id + + class V2: + @classmethod + def base_api_route(cls) -> str: + """ + base api url route for service V2. + + Returns: + str: base api url route + """ + return Consts.PromptV2BaseRouteAPI + + @classmethod + def base_label_api_route(cls) -> str: + """ + base api url route for service V2. + + Returns: + str: base api url route + """ + return Consts.PromptV2LabelBaseRouteAPI + + @classmethod + @console_api_request + def create( + cls, + template_name: str, + template_content: str, + labels: Optional[List[str]] = None, + variable_identifier: Literal[ + "{}", "{{}}", "[]", "[[]]", "()", "(())" + ] = "{}", + scene_type: Literal["TextToText", "TextToImage"] = "TextToText", + variables: Optional[List[str]] = None, + negative_template: Optional[str] = None, + negative_variables: Optional[List[str]] = None, + hyper_parameters: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> QfRequest: + """ + Creates a prompt template. + + Parameters: + template_name (str): + A descriptive name for the prompt template. + template_content (str): + The main text of the prompt template. + variable_identifier (Literal["{}", "{{}}", "[]", "[[]]", "()", "(())"]): + The identifier pattern to be used for variable replacement in the + template. + scene_type (Literal["TextToText", "TextToImage"]): + The type of prompt scene, e.g., Text2Text/Text2Image. + framework (PromptFrameworkType): + The framework to be used for prompt generation. + variables (Optional[List[str]]): + List of variables used in the template. If not provided, sdk will + automatically find variables in the template. The variables only support + English, numbers, and underscores (_), and cannot start with a number. + They must be between 2 and 30 characters in length. + label_ids (Optional[List[Union[int, str]]]): + List of label IDs associated with the prompt. + negative_template (Optional[str]): + An optional negative example template. Only available when scene is + Text2Image. + negative_variables (Optional[List[str]]): + List of variables for the negative example. Only available when scene is + Text2Image. + kwargs (Any): + Additional keyword arguments that can be passed to customize the + request. + + Returns: + QfRequest: An object representing the prompt request. + + Note: + The `@console_api_request` decorator is applied to this method, enabling it + to send the generated QfRequest and return a QfResponse to the user. + + + API Doc: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/vlwg55tyy + """ + req = QfRequest( + method="POST", + url=cls.base_api_route(), + query=_get_console_v2_query(Consts.PromptCreateAction), + ) + req.json_body = { + "templateName": template_name, + "templateContent": template_content, + "variableIdentifier": variable_identifier, + "sceneType": scene_type, + **kwargs, + } + # if user does not provide variables + # we will extract them from the template + if variables is None: + variables = Prompt._extract_variables( + template_content, variable_identifier + ) + req.json_body["templateVariables"] = ",".join(variables) + if labels: + req.json_body["labels"] = labels + # following fields are only available when scene is Text2Image + if scene_type == "TextToImage": + if negative_template: + req.json_body["negativeTemplateContent"] = negative_template + # if user does not provide variables + # we will extract them from the template + if negative_variables is None: + negative_variables = ( + Prompt._extract_variables( + negative_template, variable_identifier + ) + if negative_template is not None + else [] + ) + req.json_body["negativeTemplateVariables"] = ",".join( + negative_variables + ) + if hyper_parameters: + req.json_body["hyperParameters"] = hyper_parameters + return req + + @classmethod + @console_api_request + def info(cls, template_id: str, **kwargs: Any) -> QfRequest: + """ + Renders a prompt template and retrieves template details. + + This method is responsible for rendering a prompt template and obtaining + details about the template. + + Parameters: + template_id (str): + The ID of the prompt template to render. + kwargs (Any): + Additional keyword arguments that can be passed to customize the + request. + + Returns: + QfRequest: + An object representing the request for rendering the prompt template. + + Note: + The `@console_api_request` decorator is applied to this method, enabling + it to send the generated QfRequest and return a QfResponse to the user. + + API Doc: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/ylwg56jpb + """ + req = QfRequest( + method="POST", + url=cls.base_api_route(), + query=_get_console_v2_query(Consts.PromptInfoAction), + ) + req.json_body = {"templateId": str(template_id), **kwargs} + return req + + @classmethod + @console_api_request + def update( + cls, + template_id: str, + template_name: Optional[str] = None, + labels: Optional[List[str]] = None, + template_content: Optional[str] = None, + variable_identifier: Optional[ + Literal["{}", "{{}}", "[]", "[[]]", "()", "(())"] + ] = None, + negative_template_content: Optional[str] = None, + hyper_parameters: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> QfRequest: + """ + Update information for a prompt template. + + This method is responsible for updating various attributes of a prompt + template identified by the provided ID. + + Parameters: + template_id (str): + The ID of the prompt template to update. + template_name (Optional[str]): + The new name for the prompt template. + labels (Optional[List[Union[int, str]]]): + The updated list of label IDs associated with the prompt template. + template_content (Optional[str]): + The modified template for the prompt. + variable_identifier (Literal["{}", "{{}}", "[]", "[[]]", "()", "(())"]): + The updated identifier format for the prompt. + negative_template_content (Optional[str]): + The revised negative template for the prompt. + hyper_parameters (Optional[Dict[str, Any]]): + Hyper parameters for inference. + kwargs (Any): + Additional keyword arguments that can be passed to customize the + request. + + Returns: + QfRequest: + An instance of QfRequest representing the update request. + + Note: + The `@console_api_request` decorator is applied to this method, enabling it + to send the generated QfRequest and return a QfResponse to the user. + + API Doc: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/hlwg57a1t + """ + req = QfRequest( + method="POST", + url=cls.base_api_route(), + query=_get_console_v2_query(Consts.PromptUpdateAction), + ) + req.json_body = {"templateId": template_id, **kwargs} + if template_name is not None: + req.json_body["templateName"] = template_name + if labels: + req.json_body["labels"] = labels + if variable_identifier: + req.json_body["variableIdentifier"] = variable_identifier + if template_content: + req.json_body["templateContent"] = template_content + if negative_template_content: + req.json_body["negativeTemplateContent"] = negative_template_content + if hyper_parameters: + req.json_body["hyperParameters"] = hyper_parameters + return req + + @classmethod + @console_api_request + def delete(cls, template_id: str, **kwargs: Any) -> QfRequest: + """ + Deletes a prompt template. + + This method is responsible for deleting a prompt template based on the + specified template ID. + + Parameters: + template_id (str): + The ID of the prompt template to delete. + kwargs (Any): + Additional keyword arguments that can be passed to customize the + request. + + Returns: + QfRequest: + An instance of the QfRequest class representing the API request. + + Note: + The `@console_api_request` decorator is applied to this method, enabling it + to send the generated QfRequest and return a QfResponse to the user. + + API Doc: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/4lwg57x6t + """ + req = QfRequest( + method="POST", + url=cls.base_api_route(), + query=_get_console_v2_query(Consts.PromptDeleteAction), + ) + req.json_body = {"templateId": template_id, **kwargs} + return req + + @classmethod + @console_api_request + def list( + cls, + marker: Optional[str] = None, + max_keys: Optional[int] = None, + page_reverse: Optional[bool] = None, + name: Optional[str] = None, + label_ids: List[str] = [], + type: Optional[str] = None, + **kwargs: Any, + ) -> QfRequest: + """ + Retrieves a list of prompt templates. + + This method is responsible for retrieving a list of prompt templates based + on the specified parameters. + + Parameters: + marker (Optional[str]): + The marker of last request. Leave blank to start from the beginning. + max_keys (Optional[int]): + The max number of prompt templates to retrieve. + page_reverse (Optional[bool]): + Whether to reverse the page order. + name (Optional[str]): + A filter for prompt templates by name. + label_ids (List[Union[int, str]]): + A list of label IDs to filter prompt templates. + type (Optional[PromptType]): + A filter for prompt templates by type. + kwargs (Any): + Additional keyword arguments that can be passed to customize the + request. + + Returns: + QfRequest: + An object representing the request to retrieve prompt templates. + + Note: + The `@console_api_request` decorator is applied to this method, enabling it + to send the generated QfRequest and return a QfResponse to the user. + + API Doc: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Mlwg526y0 + """ + req = QfRequest( + method="POST", + url=cls.base_api_route(), + query=_get_console_v2_query(Consts.PromptListAction), + ) + req.json_body = { + **kwargs, + } + if name is not None: + req.json_body["name"] = name + if type: + req.json_body["type"] = type + if label_ids: + req.json_body["labelIds"] = label_ids + if marker: + req.json_body["marker"] = marker + if max_keys: + req.json_body["maxKeys"] = max_keys + if page_reverse: + req.json_body["pageReverse"] = page_reverse + return req + + @classmethod + @console_api_request + def delete_label(cls, label_id: str, **kwargs: Any) -> QfRequest: + """ + Deletes a prompt label. + + This method is responsible for deleting a prompt template based on the + specified template ID. + + Parameters: + label_id (str): + The ID of the prompt label to delete. + kwargs (Any): + Additional keyword arguments that can be passed to customize the + request. + + Returns: + QfRequest: + An instance of the QfRequest class representing the API request. + + Note: + The `@console_api_request` decorator is applied to this method, enabling it + to send the generated QfRequest and return a QfResponse to the user. + + API Doc: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/alwg7cs0u + """ + req = QfRequest( + method="POST", + url=cls.base_label_api_route(), + query=_get_console_v2_query(Consts.PromptDeleteLabelAction), + ) + req.json_body = {"labelId": label_id, **kwargs} + return req + + @classmethod + @console_api_request + def create_label(cls, name: List[str], **kwargs: Any) -> QfRequest: + """ + Create multiple prompt labels. + + Parameters: + name (List[str]): + The names of the prompt labels to create. + kwargs (Any): + Additional keyword arguments that can be passed to customize the + request. + + Returns: + QfRequest: + An instance of the QfRequest class representing the API request. + + Note: + The `@console_api_request` decorator is applied to this method, enabling it + to send the generated QfRequest and return a QfResponse to the user. + + API Doc: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Plwg7c61v + """ + req = QfRequest( + method="POST", + url=cls.base_label_api_route(), + query=_get_console_v2_query(Consts.PromptCreateLabelAction), + ) + req.json_body = {"name": name, **kwargs} + return req + + @classmethod + @console_api_request + def list_labels( + cls, + marker: Optional[str] = None, + max_keys: Optional[int] = None, + page_reverse: Optional[bool] = None, + **kwargs: Any, + ) -> QfRequest: + """ + Retrieves a list of labels for prompt templates. + + This method is responsible for retrieving a list of labels. Labels provide + information about the categories or attributes associated with each + template. + + Parameters: + offset (int): + The offset for paginating through the list of labels. Default is 0. + page_size (int): + The number of labels to include in each page. Default is 10. + kwargs (Any): + Additional keyword arguments that can be passed to customize the + request. + + Returns: + QfRequest: + An instance of the QfRequest class representing the API request. + + Note: + The `@console_api_request` decorator is applied to this method, enabling it + to send the generated QfRequest and return a QfResponse to the user. + + API Doc: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/tlwg7bbsj + """ + req = QfRequest( + method="POST", + url=cls.base_label_api_route(), + query=_get_console_v2_query(Consts.PromptGetLabelsAction), + ) + req.json_body = {**kwargs} + if marker is not None: + req.json_body["marker"] = marker + if max_keys is not None: + req.json_body["maxKeys"] = max_keys + if page_reverse is not None: + req.json_body["pageReverse"] = page_reverse + + return req