插件和流程编排应用

重要

历史文档仅适用于百炼1.0版本的APISDK调用,鉴于旧版功能已停止迭代更新,强烈建议您升级至最新版APISDK,具体详情请参考新版本升级说明

功能描述

本文主要介绍如何使用SDK调用阿里云百炼的插件和流程编排应用,包括从应用广场中创建的插件应用(如插件调用插件调度应用检索&插件调度增强)、流程编排中创建的应用和自然语言转SQL应用。

说明

首先,请参考文档插件和流程编排应用接口说明,查看请求参数和响应参数说明。

其次,请参考文档安装SDK, 安装对应编程语言的SDK。

调用说明

调用示例中的ACCESS_KEY_ID、ACCESS_KEY_SECRET、AGENT_KEYAPP_ID从系统环境变量中获取。执行示例前,请确保已正确设置相关的变量,或者在代码中直接修改变量。比如:

String accessKeyId = "abc******123";
String accessKeySecret = "abd******124";
String agentKey = "abe******125";
String appId = "abf******126";
access_key_id = "abc******123"
access_key_secret = "abd******124"
agent_key = "abe******125"
app_id = "abf******126"
accessKeyId = "abc******123"
accessKeySecret = "abd******124"
agentKey = "abe******125"
appId = "abf******126"

应用调用示例(插件和流程编排)

import com.alibaba.fastjson.JSON;
import com.aliyun.broadscope.bailian.sdk.models.*;
import com.aliyun.broadscope.bailian.sdk.*;

public class ApplicationClientTest {
    /**
     * 插件和流程编排应用使用示例
     */
    public void testFlowAppCompletions() {
        String accessKeyId = System.getenv("ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ACCESS_KEY_SECRET");

        String agentKey = System.getenv("AGENT_KEY");
        String appId = System.getenv("APP_ID");

        AccessTokenClient accessTokenClient = new AccessTokenClient(accessKeyId, accessKeySecret, agentKey);
        String token = accessTokenClient.getToken();

        ApplicationClient client = ApplicationClient.builder()
                .token(token)
                .build();

        String bizParams = "{\"userId\": \"123\"}";

        String prompt = "今天杭州的天气怎么样";
        CompletionsRequest request = new CompletionsRequest()
                .setAppId(appId)
                .setPrompt(prompt)
                .setBizParams(JSON.parseObject(bizParams));

        CompletionsResponse response = client.completions(request);
        if (!response.isSuccess()) {
            System.out.printf("failed to create completion, requestId: %s, code: %s, message: %s",
                    response.getRequestId(), response.getCode(), response.getMessage());
            return;
        }

        System.out.printf("requestId: %s, text: %s", response.getRequestId(), response.getData().getText());
    }
}
import os
import broadscope_bailian


class CompletionTest():
    def test_flow_app_completions(self):
        """ 插件和流程编排应用使用示例 """

        access_key_id = os.environ.get("ACCESS_KEY_ID")
        access_key_secret = os.environ.get("ACCESS_KEY_SECRET")
        agent_key = os.environ.get("AGENT_KEY")
        app_id = os.environ.get("APP_ID")

        client = broadscope_bailian.AccessTokenClient(access_key_id=access_key_id, access_key_secret=access_key_secret,
                                                      agent_key=agent_key)
        token = client.get_token()

        biz_params = {"userId": "123"}

        prompt = "今天杭州的天气怎么样"
        resp = broadscope_bailian.Completions(token=token).create(
            app_id=app_id,
            prompt=prompt,
            biz_params=biz_params
        )

        if not resp.get("Success"):
            print("failed to create completion, request_id: %s, code: %s, message: %s" %
                  (resp.get("RequestId"), resp.get("Code"), resp.get("Message")))
        else:
            print("request_id: %s, text: %s" % (resp.get("RequestId"), resp.get("Data", {}).get("Text")))
import (
	"encoding/json"
	"fmt"
	client "github.com/aliyun/alibabacloud-bailian-go-sdk/client"
	"github.com/google/uuid"
	"log"
	"os"
	"strings"
	"time"
)

/**
插件和流程编排应用示例
*/
func TestCreateFLowAppCompletion(t *testing.T) {
	accessKeyId := os.Getenv("ACCESS_KEY_ID")
	accessKeySecret := os.Getenv("ACCESS_KEY_SECRET")

	agentKey := os.Getenv("AGENT_KEY")
	appId := os.Getenv("APP_ID")

	//尽量避免多次初始化
	tokenClient := client.AccessTokenClient{AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, AgentKey: agentKey}
	token, err := tokenClient.GetToken()
	if err != nil {
		log.Printf("%v\n", err)
		return
	}

	cc := client.CompletionClient{Token: token}

	bizParams := "{\"userId\": \"123\"}"

	data := make(map[string]interface{})
	err = json.Unmarshal([]byte(bizParams), &data)
	if err != nil {
		log.Printf("failed to parse biz param, json: %s, err: %v\n", bizParams, err)
		return
	}

	prompt := "今天杭州的天气怎么样"
	request := &client.CompletionRequest{
		AppId:     appId,
		Prompt:    prompt,
		BizParams: data,
	}

	//调用文本生成接口
	response, err := cc.CreateCompletion(request)
	if err != nil {
		log.Printf("%v\n", err)
		return
	}

	if !response.Success {
		log.Printf("failed to create completion, requestId: %s, code: %s, message: %s\n",
			response.RequestId, response.Code, response.Message)
		return
	}

	log.Printf("requestId: %s, text: %s\n", response.RequestId, response.Data.Text)
}

应用调用示例(自然语言转SQL)

import com.alibaba.fastjson.JSON;
import com.aliyun.broadscope.bailian.sdk.models.*;
import com.aliyun.broadscope.bailian.sdk.*;

public class ApplicationClientTest {
    /**
     * 自然语言转SQL应用使用示例
     */
    public void testNl2SqlCompletion() {
        String accessKeyId = System.getenv("ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ACCESS_KEY_SECRET");

        String agentKey = System.getenv("AGENT_KEY");
        String appId = System.getenv("APP_ID");

        AccessTokenClient accessTokenClient = new AccessTokenClient(accessKeyId, accessKeySecret, agentKey);
        String token = accessTokenClient.getToken();
        ApplicationClient client = ApplicationClient.builder()
                .token(token)
                .build();

        String sqlSchema = "{" +
                "    sqlInput: {" +
                "      \"synonym_infos\": \"国民生产总值: GNP|Gross National Product\"," +
                "      \"schema_infos\": [" +
                "        {" +
                "          \"columns\": [" +
                "            {" +
                "              \"col_caption\": \"地区\"," +
                "              \"col_name\": \"region\"" +
                "            }," +
                "            {" +
                "              \"col_caption\": \"年份\"," +
                "              \"col_name\": \"year\"" +
                "            }," +
                "            {" +
                "              \"col_caption\": \"国民生产总值\"," +
                "              \"col_name\": \"gross_national_product\"" +
                "            }" +
                "          ]," +
                "          \"table_id\": \"t_gross_national_product_1\"," +
                "          \"table_desc\": \"国民生产总值表\"" +
                "        }" +
                "      ]" +
                "    }" +
                "  }";

        String prompt = "浙江近五年GNP总和是多少";
        CompletionsRequest request = new CompletionsRequest()
                .setAppId(appId)
                .setPrompt(prompt)
                .setBizParams(JSON.parseObject(sqlSchema));

        CompletionsResponse response = client.completions(request);
        if (!response.isSuccess()) {
            System.out.printf("failed to create completion, requestId: %s, code: %s, message: %s",
                    response.getRequestId(), response.getCode(), response.getMessage());
            return;
        }

        System.out.printf("requestId: %s, text: %s\n", response.getRequestId(), response.getData().getText());
    }
}
import os
import broadscope_bailian


class CompletionTest():
    def test_nl2sql_completions(self):
        """ 自然语言转SQL应用示例 """

        access_key_id = os.environ.get("ACCESS_KEY_ID")
        access_key_secret = os.environ.get("ACCESS_KEY_SECRET")
        agent_key = os.environ.get("AGENT_KEY")
        app_id = os.environ.get("APP_ID")

        client = broadscope_bailian.AccessTokenClient(access_key_id=access_key_id,
                                                      access_key_secret=access_key_secret,
                                                      agent_key=agent_key)
        token = client.get_token()

        sql_schema = {
            "sqlInput": {
                "synonym_infos": "国民生产总值: GNP|Gross National Product",
                "schema_infos": [
                    {
                        "columns": [
                            {
                                "col_caption": "地区",
                                "col_name": "region"
                            },
                            {
                                "col_caption": "年份",
                                "col_name": "year"
                            },
                            {
                                "col_caption": "国民生产总值",
                                "col_name": "gross_national_product"
                            }
                        ],
                        "table_id": "t_gross_national_product_1",
                        "table_desc": "国民生产总值表"
                    }
                ]
            }
        }
        prompt = "浙江近五年GNP总和是多少"

        resp = broadscope_bailian.Completions(token=token).create(
            app_id=app_id,
            prompt=prompt,
            # 自然语言转sql调用示例
            biz_params=sql_schema
        )

        if not resp.get("Success"):
            print("failed to create completion, request_id: %s, code: %s, message: %s" %
                  (resp.get("RequestId"), resp.get("Code"), resp.get("Message")))
        else:
            print("request_id: %s, text: %s" % (resp.get("RequestId"), resp.get("Data", "").get("Text")))
import (
	"encoding/json"
	"fmt"
	client "github.com/aliyun/alibabacloud-bailian-go-sdk/client"
	"github.com/google/uuid"
	"log"
	"os"
	"strings"
	"time"
)

/**
自然语言转SQL应用示例
*/
func TestCreateNl2SqlCompletion(t *testing.T) {
	accessKeyId := os.Getenv("ACCESS_KEY_ID")
	accessKeySecret := os.Getenv("ACCESS_KEY_SECRET")

	agentKey := os.Getenv("AGENT_KEY")
	appId := os.Getenv("APP_ID")

	//尽量避免多次初始化
	tokenClient := client.AccessTokenClient{AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, AgentKey: agentKey}
	token, err := tokenClient.GetToken()
	if err != nil {
		log.Printf("%v\n", err)
		return
	}

	cc := client.CompletionClient{Token: token}

	//自然语言转sql调用示例
	sqlSchema := "{" +
		"    \"sqlInput\": {" +
		"      \"synonym_infos\": \"国民生产总值: GNP|Gross National Product\"," +
		"      \"schema_infos\": [" +
		"        {" +
		"          \"columns\": [" +
		"            {" +
		"              \"col_caption\": \"地区\"," +
		"              \"col_name\": \"region\"" +
		"            }," +
		"            {" +
		"              \"col_caption\": \"年份\"," +
		"              \"col_name\": \"year\"" +
		"            }," +
		"            {" +
		"              \"col_caption\": \"国民生产总值\"," +
		"              \"col_name\": \"gross_national_product\"" +
		"            }" +
		"          ]," +
		"          \"table_id\": \"t_gross_national_product_1\"," +
		"          \"table_desc\": \"国民生产总值表\"" +
		"        }" +
		"      ]" +
		"    }" +
		"  }"
	data := make(map[string]interface{})
	err = json.Unmarshal([]byte(sqlSchema), &data)
	if err != nil {
		log.Printf("failed to parse sql schema, json: %s, err: %v\n", sqlSchema, err)
		return
	}

	prompt := "浙江近五年GNP总和是多少"
	request := &client.CompletionRequest{
		AppId:     appId,
		Prompt:    prompt,
		BizParams: data,
	}

	//调用文本生成接口
	response, err := cc.CreateCompletion(request)
	if err != nil {
		log.Printf("%v\n", err)
		return
	}

	if !response.Success {
		log.Printf("failed to create completion, requestId: %s, code: %s, message: %s\n",
			response.RequestId, response.Code, response.Message)
		return
	}

	log.Printf("requestId: %s, text: %s\n", response.RequestId, response.Data.Text)
}