feat: initialize external DobotAI agent gateway
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
package weknora
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
||||
)
|
||||
|
||||
var ErrIncompleteStream = errors.New("weknora stream ended without a terminal event")
|
||||
|
||||
type Client struct {
|
||||
baseURL string
|
||||
apiKey string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
type AgentChatRequest struct {
|
||||
Query string `json:"query"`
|
||||
AgentEnabled bool `json:"agent_enabled"`
|
||||
AgentID string `json:"agent_id"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
EnableMemory bool `json:"enable_memory,omitempty"`
|
||||
DisableTitle bool `json:"disable_title,omitempty"`
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
|
||||
Images []Image `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
type Image struct {
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
type ChatResult struct {
|
||||
RequestID string
|
||||
Answer string
|
||||
References []core.Reference
|
||||
}
|
||||
|
||||
func NewClient(baseURL, apiKey string, timeout time.Duration) (*Client, error) {
|
||||
parsed, err := url.Parse(strings.TrimRight(strings.TrimSpace(baseURL), "/"))
|
||||
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
||||
return nil, errors.New("invalid WEKNORA_BASE_URL")
|
||||
}
|
||||
if strings.TrimSpace(apiKey) == "" {
|
||||
return nil, errors.New("WEKNORA_API_KEY is required")
|
||||
}
|
||||
if timeout <= 0 {
|
||||
timeout = 120 * time.Second
|
||||
}
|
||||
return &Client{baseURL: parsed.String(), apiKey: apiKey, http: &http.Client{Timeout: timeout}}, nil
|
||||
}
|
||||
|
||||
func (c *Client) CreateSession(ctx context.Context, title, description string) (string, error) {
|
||||
var response struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions", map[string]string{
|
||||
"title": title, "description": description,
|
||||
}, &response); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !response.Success || strings.TrimSpace(response.Data.ID) == "" {
|
||||
return "", errors.New("weknora returned an empty session id")
|
||||
}
|
||||
return response.Data.ID, nil
|
||||
}
|
||||
|
||||
func (c *Client) AgentChat(ctx context.Context, sessionID string, request AgentChatRequest) (ChatResult, error) {
|
||||
if strings.TrimSpace(sessionID) == "" || strings.TrimSpace(request.AgentID) == "" || strings.TrimSpace(request.Query) == "" {
|
||||
return ChatResult{}, errors.New("session id, agent id and query are required")
|
||||
}
|
||||
request.AgentEnabled = true
|
||||
body, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return ChatResult{}, fmt.Errorf("encode agent chat request: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/api/v1/agent-chat/"+url.PathEscape(sessionID), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return ChatResult{}, fmt.Errorf("create agent chat request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
req.Header.Set("X-API-Key", c.apiKey)
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return ChatResult{}, fmt.Errorf("call weknora agent chat: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
message, _ := io.ReadAll(io.LimitReader(resp.Body, 32<<10))
|
||||
return ChatResult{}, fmt.Errorf("weknora agent chat returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(message)))
|
||||
}
|
||||
return parseSSE(resp.Body)
|
||||
}
|
||||
|
||||
func (c *Client) doJSON(ctx context.Context, method, path string, input, output any) error {
|
||||
body, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode weknora request: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create weknora request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-API-Key", c.apiKey)
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("call weknora: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
message, _ := io.ReadAll(io.LimitReader(resp.Body, 32<<10))
|
||||
return fmt.Errorf("weknora returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(message)))
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(output); err != nil {
|
||||
return fmt.Errorf("decode weknora response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseSSE(reader io.Reader) (ChatResult, error) {
|
||||
scanner := bufio.NewScanner(reader)
|
||||
scanner.Buffer(make([]byte, 64<<10), 2<<20)
|
||||
var result ChatResult
|
||||
var dataLines []string
|
||||
terminal := false
|
||||
|
||||
flush := func() error {
|
||||
if len(dataLines) == 0 {
|
||||
return nil
|
||||
}
|
||||
raw := strings.Join(dataLines, "\n")
|
||||
dataLines = dataLines[:0]
|
||||
var event struct {
|
||||
ID string `json:"id"`
|
||||
ResponseType string `json:"response_type"`
|
||||
Content string `json:"content"`
|
||||
Done bool `json:"done"`
|
||||
KnowledgeReferences []core.Reference `json:"knowledge_references"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &event); err != nil {
|
||||
return fmt.Errorf("decode weknora SSE event: %w", err)
|
||||
}
|
||||
if event.ID != "" {
|
||||
result.RequestID = event.ID
|
||||
}
|
||||
switch event.ResponseType {
|
||||
case "references":
|
||||
result.References = append([]core.Reference(nil), event.KnowledgeReferences...)
|
||||
case "answer":
|
||||
result.Answer += event.Content
|
||||
if event.Done {
|
||||
terminal = true
|
||||
}
|
||||
case "error":
|
||||
if event.Content == "" {
|
||||
event.Content = "weknora returned an unspecified error"
|
||||
}
|
||||
return errors.New(event.Content)
|
||||
case "complete":
|
||||
if event.Done {
|
||||
terminal = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if line == "" {
|
||||
if err := flush(); err != nil {
|
||||
return ChatResult{}, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
dataLines = append(dataLines, strings.TrimSpace(strings.TrimPrefix(line, "data:")))
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return ChatResult{}, fmt.Errorf("read weknora SSE stream: %w", err)
|
||||
}
|
||||
if err := flush(); err != nil {
|
||||
return ChatResult{}, err
|
||||
}
|
||||
if !terminal {
|
||||
return ChatResult{}, ErrIncompleteStream
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
Reference in New Issue
Block a user