Skip to main content
Application Calling

Custom application parameter pass-through

Passe parâmetros personalizados, principalmente para plugins e nós personalizados, ao chamar a Agent Application e a Workflow Application do Alibaba Cloud Model Studio (que substituem as aplicações de orquestração de agentes).

Obter uma chave de API e exportar a chave de API como variável de ambiente. Se utilizar um SDK para fazer chamadas, instale o DashScope SDK.

Parâmetros de plugin personalizado

Este artigo utiliza a ferramenta de consulta de convenções de dormitório para demonstrar como passar parâmetros para um plugin personalizado via API.
Os parâmetros de plugins personalizados são transmitidos por meio de uma Agent Application associada ou do nó de plugin de uma Workflow Application.
O exemplo a seguir mostra como passar parâmetros de plugin personalizado para uma Agent Application.

Uso

Etapa 1: Criar um plugin personalizado

Caso já tenha criado uma ferramenta de plugin ou importado um plugin, pule esta etapa.
  1. Crie um plugin personalizado: Acesse a página Plugins no console do Model Studio e clique em Add Custom Plug-in. Insira as informações do plugin. Se for necessária autenticação, ative a opção Enable Authentication e configure as definições.
    Exemplo de descrição do plugin: Consulta convenções de dormitório e localiza entradas específicas por índice numérico.
    Exemplo de URL do plugin: https://domitorgreement-plugin-example-icohrkdjxy.cn-beijing.fcapp.run
    image
    Nota: O campo Plug-in Description resume brevemente a finalidade do plugin. Isso auxilia o modelo grande a decidir se deve chamar o plugin para uma determinada tarefa. Descreva-o em linguagem natural.
  2. Crie uma ferramenta: Preencha as informações da ferramenta e configure os parâmetros de entrada e saída. Nota:
    1. A Tool Description ajuda o modelo grande a compreender melhor as funções e os casos de uso da ferramenta. Utilize linguagem natural e forneça exemplos sempre que possível.
    2. Um Parameter Name descritivo facilita o entendimento do modelo grande sobre a informação representada.
    3. A Parameter Description explica a função do parâmetro de entrada. Deve ser concisa e precisa para ajudar o modelo grande a determinar o valor correto a ser utilizado.
    4. É obrigatório selecionar Business Pass-through no campo Passing Method do parâmetro de entrada.
    Neste exemplo, o índice de conteúdo da convenção de dormitório, article_index, é definido como um parâmetro de repasse.
    image
  3. Clique em Test Tool. Após a aprovação do teste, Publish o plugin.

Etapa 2: Associar um plugin a um agente

Só é possível associar plugins a uma Agent Application que esteja no mesmo workspace.
  1. No cartão de um plugin publicado, clique em Add to Agent e selecione uma aplicação de agente.
  2. Alternativamente, clique em + Plugin dentro de uma aplicação para associar um plugin personalizado.
  3. Por fim, Publish a aplicação.

Etapa 3: Chamada de API

  • Quando a autenticação não é necessária: Para chamar um plugin personalizado via API, utilize o parâmetro user_defined_params de biz_params para transmitir as informações do plugin. Substitua your_plugin_code pelo ID real do plugin e passe os pares chave-valor dos parâmetros de entrada configurados no plugin.
    É possível encontrar o ID do plugin no cartão do plugin.
    Neste exemplo, passar o valor 2 para o parâmetro article_index consulta o conteúdo da segunda convenção de dormitório e retorna o resultado correto.
    • Python
    • Java
    • HTTP
    Exemplo de solicitação
    import os
    from http import HTTPStatus
    # We recommend using DashScope SDK v1.14.0 or later.
    from dashscope import Application
    biz_params = {
        # Pass the input parameters for the agent application's custom plugin. Replace `your_plugin_code` with your plugin ID.
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}}}
    response = Application.call(
            # If the environment variable is not set, you can use your Model Studio API key by replacing the following line with api_key="sk-xxx". We recommend using an environment variable in production to avoid leaking your API key.
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            app_id='YOUR_APP_ID',
            prompt='Dormitory convention content',
            biz_params=biz_params)
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process and output only the text.
        # print('%s\n' % (response.usage))
    
    Exemplo de resposta
    The second article of the dormitory convention is as follows:
    
    "Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere."
    
    This suggests that roommates should foster a positive living and learning environment by supporting and helping each other, while also learning to understand and respect others. If you want to learn about other articles of the convention, just ask!
    
    • Python
    • Java
    • HTTP
    Exemplo de solicitação
    import os
    from http import HTTPStatus
    # We recommend using DashScope SDK v1.14.0 or later.
    import dashscope
    from dashscope import Application
    
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    biz_params = {
        # Pass the input parameters for the agent application's custom plugin. Replace `your_plugin_code` with your plugin ID.
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}}}
    response = Application.call(
            # If the environment variable is not set, you can use your Model Studio API key by replacing the following line with api_key="sk-xxx". We recommend using an environment variable in production to avoid leaking your API key.
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            app_id='YOUR_APP_ID',
            prompt='Dormitory convention content',
            biz_params=biz_params)
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process and output only the text.
        # print('%s\n' % (response.usage))
    
    Exemplo de resposta
    The second article of the dormitory convention is as follows:
    
    "Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere."
    
    This suggests that roommates should foster a positive living and learning environment by supporting and helping each other, while also learning to understand and respect others. If you want to learn about other articles of the convention, just ask!
    
  • Quando a autenticação é necessária: Este cenário descreve como chamar um plugin personalizado que possui Authentication ativada e está configurado com User-level Authentication.
    É possível encontrar o ID do plugin no cartão do plugin.
    • Utilize user_defined_params no campo biz_params para passar as informações do plugin personalizado. Substitua your_plugin_code pelo ID do seu plugin e forneça os parâmetros de entrada como pares chave-valor.
    • Utilize user_defined_tokens no campo biz_params para passar as credenciais de autenticação. Substitua your_plugin_code pelo ID do seu plugin e defina o valor de user_token como seu token de autenticação, como uma chave de API do DashScope.
    • Após a autenticação bem-sucedida, o serviço consulta o item especificado com base no parâmetro de índice fornecido e retorna o resultado correto.
    Neste exemplo, o parâmetro article_index é definido como 2, e o valor de user_token, YOUR_TOKEN, é substituído pela DASHSCOPE_API_KEY real. Após a autenticação bem-sucedida, o conteúdo da segunda regra do dormitório é consultado e o resultado correto é retornado.
    • Python
    • Java
    • HTTP
    Exemplo de solicitação
    from http import HTTPStatus
    import os
    # We recommend using DashScope SDK v1.14.0 or later.
    from dashscope import Application
    biz_params = {
        # Pass authentication credentials for the agent application's custom plugin.
        # Replace your_plugin_code with your plugin ID and YOUR_TOKEN with your authentication token, such as an API key.
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}},
        "user_defined_tokens": {
            "your_plugin_code": {
                "user_token": "YOUR_TOKEN"}}}
    response = Application.call(
                # If the environment variable is not configured, you can use a DashScope API key by replacing the next line with: api_key="sk-xxx".
                # However, we do not recommend hardcoding the API key in a production environment to reduce the risk of key leakage.
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='YOUR_APP_ID',
                prompt='Dormitory convention content',
                biz_params=biz_params)
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process and output only the text.
        # print('%s\n' % (response.usage))
    
    Exemplo de resposta
    The second article of the dormitory convention is as follows:
    
    Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.
    
    If you need to know about other articles of the convention, please let me know.
    
    • Python
    • Java
    • HTTP
    Exemplo de solicitação
    from http import HTTPStatus
    import os
    # We recommend using DashScope SDK v1.14.0 or later.
    import dashscope
    from dashscope import Application
    
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    biz_params = {
        # Pass authentication credentials for the agent application's custom plugin.
        # Replace your_plugin_code with your plugin ID and YOUR_TOKEN with your authentication token, such as an API key.
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}},
        "user_defined_tokens": {
            "your_plugin_code": {
                "user_token": "YOUR_TOKEN"}}}
    response = Application.call(
                # If the environment variable is not configured, you can use a DashScope API key by replacing the next line with: api_key="sk-xxx".
                # However, we do not recommend hardcoding the API key in a production environment to reduce the risk of key leakage.
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='YOUR_APP_ID',
                prompt='Dormitory convention content',
                biz_params=biz_params)
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process and output only the text.
        # print('%s\n' % (response.usage))
    
    Exemplo de resposta
    The second article of the dormitory convention is as follows:
    
    Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.
    
    If you need to know about other articles of the convention, please let me know.
    

Repasse de parâmetros de nó personalizado

Este tópico utiliza o exemplo de Consulta de divisões administrativas por nome da cidade para demonstrar como passar parâmetros de nó personalizado para uma aplicação através de uma chamada de API.
Os parâmetros de nó personalizado de uma aplicação são transmitidos através do nó inicial de uma Workflow Application.
O exemplo a seguir mostra como passar parâmetros personalizados para o nó inicial em uma Workflow Application.

Uso

Etapa 1: Configurar parâmetros de nó personalizado

Acesse a página My Applications no console do Model Studio. Selecione uma Workflow Application e defina parâmetros personalizados para seu nó inicial. Para este exemplo, crie uma variável String chamada city. Em seguida, insira as variáveis city e query no prompt e Publish a aplicação.

Etapa 2: Fazer uma chamada de API

Ao realizar a chamada de API, passe o valor de city no campo biz_params e o valor de query no campo prompt.
  • Python
  • Java
  • HTTP
Exemplo de solicitação
import os
from http import HTTPStatus
from dashscope import Application
# Pass custom parameters for a workflow application.
biz_params = {"city": "Hangzhou"}
response = Application.call(
    # If you have not configured an environment variable, you can use your Model Studio API key by replacing the following line with: api_key="sk-xxx".
    # We recommend that you do not hardcode the API key in your code in a production environment to reduce the risk of API key leaks.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='YOUR_APP_ID',  # Replace with your actual application ID.
    prompt='Query the administrative divisions of this city',
    biz_params=biz_params  # Pass business parameters.
)

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
    print(f'{response.output.text}')  # Process and output only the text.
Exemplo de resposta
Hangzhou, as the capital city of Zhejiang Province, has the following 10 municipal districts: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, and Lin'an. Each district has unique characteristics and development priorities.

- Shangcheng District: Located in the center of Hangzhou, it is one of the city's political, economic, and cultural centers.
- Gongshu District: Characterized by its canal culture, it hosts numerous historical and cultural heritage sites.
- Xihu District: Home to the famous West Lake Scenic Area, it is a major tourist destination.
- Binjiang District: A hub for high-tech industries, where well-known companies like Alibaba are located.
- Xiaoshan District: An administrative district in the southeast that has experienced rapid economic growth, especially in the manufacturing sector.
- Yuhang District: Has developed rapidly in recent years, particularly in the internet economy sector. (Note: Alibaba's headquarters is actually in Binjiang District).
- Linping District: A newly established district aimed at promoting comprehensive economic and social development in the area.
- Qiantang District: Also a result of recent administrative restructuring, it emphasizes the combination of innovative development and ecological protection.
- Fuyang District: Located to the southwest of Hangzhou, it is known for its rich natural landscapes and long history and culture.
- Lin'an District: Situated in the west of Hangzhou, it is famous for its excellent ecological environment and profound cultural heritage.

Please note that specific city planning may change over time. Refer to the latest official information.
  • Python
  • Java
  • HTTP
Exemplo de solicitação
import os
from http import HTTPStatus
import dashscope
from dashscope import Application
# Pass custom parameters for a workflow application.

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
biz_params = {"city": "Hangzhou"}
response = Application.call(
    # If you have not configured an environment variable, you can use your Model Studio API key by replacing the following line with: api_key="sk-xxx".
    # We recommend that you do not hardcode the API key in your code in a production environment to reduce the risk of API key leaks.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='YOUR_APP_ID',  # Replace with your actual application ID.
    prompt='Query the administrative divisions of this city',
    biz_params=biz_params  # Pass business parameters.
)

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
    print(f'{response.output.text}')  # Process and output only the text.
Exemplo de resposta
Hangzhou, the capital city of Zhejiang Province, is divided into 10 municipal districts: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, and Lin'an. Each district has its own unique features and development priorities.

- Shangcheng District: Located in the center of Hangzhou, it is one of the city's political, economic, and cultural hubs.
- Gongshu District: Known for its canal culture and numerous historical and cultural heritage sites.
- Xihu District: Home to the famous West Lake scenic area, a major tourist destination.
- Binjiang District: A hub for high-tech industries, where well-known companies such as Alibaba are located.
- Xiaoshan District: An administrative district in the southeast known for its rapid economic development, especially in manufacturing.
- Yuhang District: Has developed rapidly in recent years, especially in the internet economy. Alibaba's headquarters is also located here (Note: Alibaba's headquarters is actually in Binjiang District).
- Linping District: A newly established administrative district aimed at promoting comprehensive economic and social development in the area.
- Qiantang District: Also a result of recent administrative division adjustments, it emphasizes both innovative development and ecological protection.
- Fuyang District: Located to the southwest of Hangzhou, it is known for its rich natural landscapes and long history and culture.
- Lin'an District: Situated in the western part of Hangzhou, it is famous for its beautiful ecology and profound cultural heritage.

Note that specific urban planning may change over time. Refer to the latest official information.

Documentação relacionada

Plugin personalizado: Saiba como criar um plugin personalizado. Invocação de aplicação: Saiba como invocar aplicações e explorar mais casos de uso. API de invocação de aplicação: Consulte a lista completa de parâmetros e exemplos de invocação.