Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
userpj committed Dec 26, 2024
1 parent 535120f commit 8c01fb8
Show file tree
Hide file tree
Showing 5 changed files with 556 additions and 20 deletions.
50 changes: 50 additions & 0 deletions go/appbuilder/component_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,13 @@
package appbuilder

import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
)

Expand All @@ -35,3 +40,48 @@ 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) {
request := http.Request{}

urlSuffix := fmt.Sprintf("/components/%s", component)
if version != "" {
urlSuffix += fmt.Sprintf("/version/%s", version)
}
if action != "" {
if strings.Contains(urlSuffix, "?") {
urlSuffix += fmt.Sprintf("&action=%s", action)
} else {
urlSuffix += fmt.Sprintf("?action=%s", action)
}
}

serviceURL, err := t.sdkConfig.ServiceURLV2(urlSuffix)
if err != nil {
return nil, err
}

header := t.sdkConfig.AuthHeaderV2()
request.URL = serviceURL
request.Method = "POST"
header.Set("Content-Type", "application/json")
request.Header = header
data, _ := json.Marshal(req)
request.Body = NopCloser(bytes.NewReader(data))
request.ContentLength = int64(len(data)) // 手动设置长度

t.sdkConfig.BuildCurlCommand(&request)
resp, err := t.client.Do(&request)
if err != nil {
return nil, err
}
requestID, err := checkHTTPResponse(resp)
if err != nil {
return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err)
}
r := NewSSEReader(1024*1024, bufio.NewReader(resp.Body))
if req.Stream {
return &ComponentClientStreamIterator{requestID: requestID, r: r, body: resp.Body}, nil
}
return &ComponentClientOnceIterator{body: resp.Body}, nil
}
187 changes: 187 additions & 0 deletions go/appbuilder/component_client_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,190 @@

package appbuilder

import (
"encoding/json"
"fmt"
"io"
"strings"
)

const (
SysOriginQuery = "_sys_origin_query"
SysFileUrls = "_sys_file_urls"
SysConversationID = "_sys_conversation_id"
SysEndUserID = "_sys_end_user_id"
SysChatHistory = "_sys_chat_history"
)

type ComponentRunRequest struct {
Stream bool `json:"stream"`
Parameters map[string]any `json:"parameters"`
}

type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}

type ComponentRunResponse struct {
RequestID string `json:"request_id"`
Code string `json:"code"`
Message string `json:"message"`
Data ComponentRunResponseData `json:"data"`
}

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"`
}

type Content struct {
Name string `json:"name"`
VisibleScope string `json:"visible_scope"`
RawData map[string]any `json:"raw_data"`
Usage map[string]any `json:"usage"`
Metrics map[string]any `json:"metrics"`
Type string `json:"type"`
Text map[string]any `json:"text"`
Event ComponentEvent `json:"event"`
}

type ComponentEvent struct {
ID string `json:"id"`
Status string `json:"status"`
Name string `json:"name"`
CreatedTime string `json:"created_time"`
ErrorCode string `json:"error_code"`
ErrorMessage string `json:"error_message"`
}

type Text struct {
Info string `json:"info"`
}

type Code struct {
Code string `json:"code"`
}

type Files struct {
Filename string `json:"filename"`
Url string `json:"url"`
}

type Urls struct {
Url string `json:"url"`
}

type OralText struct {
Info string `json:"info"`
}

type References struct {
Type string `json:"type"`
Source string `json:"source"`
DocID string `json:"doc_id"`
Title string `json:"title"`
Content string `json:"content"`
Extra map[string]any `json:"extra"`
}

type Image struct {
Filename string `json:"filename"`
Url string `json:"url"`
Byte []byte `json:"byte"`
}

type Chart struct {
Type string `json:"type"`
Data string `json:"data"`
}

type Audio struct {
Filename string `json:"filename"`
Url string `json:"url"`
Byte []byte `json:"byte"`
}

type PlanStep struct {
Name string `json:"name"`
Arguments map[string]any `json:"arguments"`
Thought string `json:"thought"`
}

type Plan struct {
Detail string `json:"detail"`
Steps []PlanStep `json:"steps"`
}

type FunctionCall struct {
Thought string `json:"thought"`
Name string `json:"name"`
Arguments map[string]any `json:"arguments"`
}

type Json struct {
Data string `json:"data"`
}

type ComponentClientIterator interface {
// Next 获取处理结果,如果返回error不为空,迭代器自动失效,不允许再调用此方法
Next() (*ComponentRunResponseData, error)
}

type ComponentClientStreamIterator struct {
requestID string
r *sseReader
body io.ReadCloser
}

func (t *ComponentClientStreamIterator) Next() (*ComponentRunResponseData, error) {
data, err := t.r.ReadMessageLine()
if err != nil && !(err == io.EOF) {
t.body.Close()
return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err)
}
if err != nil && err == io.EOF {
t.body.Close()
return nil, err
}
if strings.HasPrefix(string(data), "data:") {
var resp ComponentRunResponse
if err := json.Unmarshal(data[5:], &resp); err != nil {
t.body.Close()
return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err)
}
return &resp.Data, nil
}
// 非SSE格式关闭连接,并返回数据
t.body.Close()
return nil, fmt.Errorf("requestID=%s, body=%s", t.requestID, string(data))
}

// ComponentClientOnceIterator 非流式返回时对应的迭代器,只可迭代一次
type ComponentClientOnceIterator struct {
body io.ReadCloser
requestID string
}

func (t *ComponentClientOnceIterator) Next() (*ComponentRunResponseData, error) {
data, err := io.ReadAll(t.body)
if err != nil {
return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err)
}
defer t.body.Close()
var resp ComponentRunResponse
if err := json.Unmarshal(data, &resp); err != nil {
return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err)
}
return &resp.Data, nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.baidubce.appbuilder.model.componentclient;

import java.util.HashMap;
import java.util.Map;

public class ComponentClientRunRequest {
public static final String SysOriginQuery = "_sys_origin_query";
public static final String SysFileUrls = "_sys_file_urls";
public static final String SysConversationID = "_sys_conversation_id";
public static final String SysEndUserID = "_sys_end_user_id";
public static final String SysChatHistory = "_sys_chat_history";

private boolean stream;
private Map<String, Object> parameters = new HashMap<>();

public boolean isStream() {
return stream;
}

public void setStream(boolean stream) {
this.stream = stream;
}

public Map<String, Object> getParameters() {
return parameters;
}

public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
}
Loading

0 comments on commit 8c01fb8

Please sign in to comment.