Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
userpj committed Dec 31, 2024
1 parent 66f8d2d commit b961c2d
Show file tree
Hide file tree
Showing 9 changed files with 352 additions and 156 deletions.
7 changes: 6 additions & 1 deletion go/appbuilder/component_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func NewComponentClient(config *SDKConfig) (*ComponentClient, error) {
return &ComponentClient{sdkConfig: config, client: client}, nil
}

func (t *ComponentClient) Run(component, version, action string, req ComponentRunRequest) (ComponentClientIterator, error) {
func (t *ComponentClient) Run(component, version, action string, stream bool, parameters map[string]any) (ComponentClientIterator, error) {
request := http.Request{}

urlSuffix := fmt.Sprintf("/components/%s", component)
Expand All @@ -66,6 +66,11 @@ func (t *ComponentClient) Run(component, version, action string, req ComponentRu
request.Method = "POST"
header.Set("Content-Type", "application/json")
request.Header = header

req := ComponentRunRequest{
Stream: stream,
Parameters: parameters,
}
data, _ := json.Marshal(req)
request.Body = NopCloser(bytes.NewReader(data))
request.ContentLength = int64(len(data)) // 手动设置长度
Expand Down
20 changes: 8 additions & 12 deletions go/appbuilder/component_client_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,14 @@ type ComponentRunResponse struct {
}

type ComponentRunResponseData struct {
ConversationID string `json:"conversation_id"`
MessageID string `json:"message_id"`
TraceID string `json:"trace_id"`
UserID string `json:"user_id"`
EndUserID string `json:"end_user_id"`
IsCompletion bool `json:"is_completion"`
ComponentOutput ComponentOutput `json:"component_output"`
}

type ComponentOutput struct {
Role string `json:"role"`
Content []Content `json:"content"`
ConversationID string `json:"conversation_id"`
MessageID string `json:"message_id"`
TraceID string `json:"trace_id"`
UserID string `json:"user_id"`
EndUserID string `json:"end_user_id"`
IsCompletion bool `json:"is_completion"`
Role string `json:"role"`
Content []Content `json:"content"`
}

type Content struct {
Expand Down
89 changes: 89 additions & 0 deletions go/appbuilder/component_client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright (c) 2024 Baidu, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package appbuilder

import (
"bytes"
"fmt"
"os"
"testing"
)

func TestComponentClient(t *testing.T) {
var logBuffer bytes.Buffer

// 设置环境变量
os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG")
os.Setenv("APPBUILDER_LOGFILE", "")

// 测试逻辑
config, err := NewSDKConfig("", "")
if err != nil {
t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m")
t.Fatalf("new http client config failed: %v", err)
}

componentID := "44205c67-3980-41f7-aad4-37357b577fd0"
client, err := NewComponentClient(config)
if err != nil {
t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m")
t.Fatalf("new ComponentClient instance failed")
}

parameters := map[string]any{
SysOriginQuery: "北京景点推荐",
}
i, err := client.Run(componentID, "latest", "", false, parameters)
if err != nil {
t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m")
t.Fatalf("run component failed: %v", err)
}

// test result
for answer, err := i.Next(); err == nil; answer, err = i.Next() {
data := answer.Content[0].Text
if data == nil {
t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m")
t.Fatalf("run component failed: data is nil")
}
}

i2, err := client.Run(componentID, "latest", "", true, parameters)
if err != nil {
t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m")
t.Fatalf("run component failed: %v", err)
}

// test stream result
var answerText any
for answer, err := i2.Next(); err == nil; answer, err = i2.Next() {
if len(answer.Content) == 0 {
continue
}
answerText = answer.Content[0].Text
}
if answerText == nil {
t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m")
t.Fatalf("run component failed: data is nil")
}

// 如果测试失败,则输出缓冲区中的日志
if t.Failed() {
fmt.Println(logBuffer.String())
} else { // else 紧跟在右大括号后面
// 测试通过,打印文件名和测试函数名
t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m")
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.baidubce.appbuilder.console.componentclient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.nio.charset.StandardCharsets;

import org.apache.hc.core5.http.ClassicHttpRequest;
Expand All @@ -13,7 +15,6 @@
import com.baidubce.appbuilder.base.utils.http.HttpResponse;
import com.baidubce.appbuilder.base.utils.json.JsonUtils;
import com.baidubce.appbuilder.model.componentclient.ComponentClientIterator;
import com.baidubce.appbuilder.model.componentclient.ComponentClientRunRequest;
import com.baidubce.appbuilder.model.componentclient.ComponentClientRunResponse;

public class ComponentClient extends Component {
Expand All @@ -29,18 +30,23 @@ public ComponentClient(String secretKey, String gateway) {
super(secretKey, gateway);
}

/**
* 执行应用构建客户端运行请求
/**
* 运行Component,根据输入的问题、会话ID、文件ID数组以及是否以流模式等信息返回结果,返回ComponentClientIterator迭代器。
*
* @param requestBody 请求体,包含运行所需的所有信息
* @return 返回包含构建客户端响应的迭代器
* @throws IOException 如果在执行请求时发生I/O错误
* @throws AppBuilderServerException 如果应用构建服务器返回错误响应
*
* @param componentId 组件ID
* @param version 组件版本
* @param action 参数动作
* @param stream 是否以流的形式返回结果
* @param parameters 参数列表
* @return ComponentCientIterator 迭代器,包含 ComponentCientIterator 的运行结果
* @throws IOException 如果在 I/O 操作过程中发生错误
* @throws AppBuilderServerException 如果 AppBuilder 服务器返回错误
*/
public ComponentClientIterator run(String component, String version, String action, ComponentClientRunRequest requestBody)
public ComponentClientIterator run(String componentId, String version, String action, boolean stream, Map<String, Object> parameters)
throws IOException, AppBuilderServerException {
String url = AppBuilderConfig.COMPONENT_RUN_URL;
String urlSuffix = String.format("%s/%s", url, component);
String urlSuffix = String.format("%s/%s", url, componentId);
if (!version.isEmpty()) {
urlSuffix += String.format("/version/%s", version);
}
Expand All @@ -52,7 +58,11 @@ public ComponentClientIterator run(String component, String version, String acti
}
}

Map<String, Object> requestBody = new HashMap<>();
requestBody.put("parameters", parameters);
requestBody.put("stream", stream);
String jsonBody = JsonUtils.serialize(requestBody);

ClassicHttpRequest postRequest = httpClient.createPostRequestV2(urlSuffix,
new StringEntity(jsonBody, StandardCharsets.UTF_8));
postRequest.setHeader("Content-Type", "application/json");
Expand Down
Loading

0 comments on commit b961c2d

Please sign in to comment.