feat(go-models): add PPIO provider driver (#15099)

### What problem does this PR solve?

Closes #15089.

Adds PPIO support to the Go model-provider layer so PPIO instances can
be routed through the Go API server with the same OpenAI-compatible
chat, streaming, model listing, and connection-check flow used by other
SaaS providers.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

## Summary

- Added a PPIO Go model driver.
- Added the PPIO provider catalog and default OpenAI-compatible API URL.
- Registered PPIO in the model factory.
- Added focused provider and provider-manager tests.

## What changed

- Implemented chat completions, SSE streaming, ListModels, and
CheckConnection for PPIO.
- Covered request shape, stream termination, reasoning fallback, model
listing, custom base URLs, safe transport setup, unsupported methods,
and provider config loading.
- Kept the provider catalog aligned with the existing RAGFlow PPIO
factory model set.
- Cleaned up pre-existing Go model package validation blockers so the
scoped provider tests can run normally with vet enabled.

## Why

The existing Python/provider catalog path includes PPIO, but the Go
model-provider layer did not have a PPIO driver, so the Go API server
could not instantiate or use PPIO as requested in #15089.
This commit is contained in:
ghost
2026-05-21 20:52:18 -07:00
committed by GitHub
parent 04bdb41909
commit b2053cc3c7
15 changed files with 1265 additions and 40 deletions

161
conf/models/ppio.json Normal file
View File

@@ -0,0 +1,161 @@
{
"name": "PPIO",
"url": {
"default": "https://api.ppio.com/openai/v1",
"us": "https://api.ppinfra.com/v3/openai"
},
"url_suffix": {
"chat": "chat/completions",
"models": "models"
},
"class": "ppio",
"models": [
{
"name": "deepseek/deepseek-v4-flash",
"max_tokens": 1048576,
"model_types": [
"chat"
]
},
{
"name": "deepseek/deepseek-v4-pro",
"max_tokens": 1048576,
"model_types": [
"chat"
]
},
{
"name": "deepseek/deepseek-r1/community",
"max_tokens": 64000,
"model_types": [
"chat"
]
},
{
"name": "deepseek/deepseek-v3/community",
"max_tokens": 64000,
"model_types": [
"chat"
]
},
{
"name": "deepseek/deepseek-r1",
"max_tokens": 64000,
"model_types": [
"chat"
]
},
{
"name": "deepseek/deepseek-v3",
"max_tokens": 64000,
"model_types": [
"chat"
]
},
{
"name": "deepseek/deepseek-r1-distill-llama-70b",
"max_tokens": 32000,
"model_types": [
"chat"
]
},
{
"name": "deepseek/deepseek-r1-distill-qwen-32b",
"max_tokens": 64000,
"model_types": [
"chat"
]
},
{
"name": "deepseek/deepseek-r1-distill-qwen-14b",
"max_tokens": 64000,
"model_types": [
"chat"
]
},
{
"name": "deepseek/deepseek-r1-distill-llama-8b",
"max_tokens": 32000,
"model_types": [
"chat"
]
},
{
"name": "qwen/qwen-2.5-72b-instruct",
"max_tokens": 32768,
"model_types": [
"chat"
]
},
{
"name": "qwen/qwen-2-vl-72b-instruct",
"max_tokens": 32768,
"model_types": [
"chat"
]
},
{
"name": "meta-llama/llama-3.2-3b-instruct",
"max_tokens": 32768,
"model_types": [
"chat"
]
},
{
"name": "qwen/qwen2.5-32b-instruct",
"max_tokens": 32000,
"model_types": [
"chat"
]
},
{
"name": "baichuan/baichuan2-13b-chat",
"max_tokens": 14336,
"model_types": [
"chat"
]
},
{
"name": "meta-llama/llama-3.1-70b-instruct",
"max_tokens": 32768,
"model_types": [
"chat"
]
},
{
"name": "meta-llama/llama-3.1-8b-instruct",
"max_tokens": 32768,
"model_types": [
"chat"
]
},
{
"name": "01-ai/yi-1.5-34b-chat",
"max_tokens": 16384,
"model_types": [
"chat"
]
},
{
"name": "01-ai/yi-1.5-9b-chat",
"max_tokens": 16384,
"model_types": [
"chat"
]
},
{
"name": "thudm/glm-4-9b-chat",
"max_tokens": 32768,
"model_types": [
"chat"
]
},
{
"name": "qwen/qwen-2-7b-instruct",
"max_tokens": 32768,
"model_types": [
"chat"
]
}
]
}

View File

@@ -0,0 +1,128 @@
//
// Copyright 2026 The InfiniFlow Authors. 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 entity
import (
"os"
"path/filepath"
modeldrivers "ragflow/internal/entity/models"
"testing"
)
func readPPIOProviderConfig(t *testing.T) []byte {
t.Helper()
for _, candidate := range []string{
filepath.Join("..", "..", "conf", "models", "ppio.json"),
filepath.Join("conf", "models", "ppio.json"),
} {
data, err := os.ReadFile(candidate)
if err == nil {
return data
}
}
t.Fatal("could not locate conf/models/ppio.json")
return nil
}
func TestPPIOProviderConfigLoadsIntoProviderManager(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "ppio.json"), readPPIOProviderConfig(t), 0o600); err != nil {
t.Fatalf("write ppio config: %v", err)
}
pm, err := NewProviderManager(dir)
if err != nil {
t.Fatalf("NewProviderManager: %v", err)
}
provider := pm.FindProvider("ppio")
if provider == nil {
t.Fatal("PPIO provider not found")
}
if provider.Name != "PPIO" {
t.Errorf("provider.Name=%q", provider.Name)
}
if provider.URL["default"] != "https://api.ppio.com/openai/v1" {
t.Errorf("default URL=%q", provider.URL["default"])
}
if provider.URL["us"] != "https://api.ppinfra.com/v3/openai" {
t.Errorf("us URL=%q", provider.URL["us"])
}
if provider.URLSuffix.Chat != "chat/completions" {
t.Errorf("chat suffix=%q", provider.URLSuffix.Chat)
}
if provider.URLSuffix.Models != "models" {
t.Errorf("models suffix=%q", provider.URLSuffix.Models)
}
if _, ok := provider.ModelDriver.(*modeldrivers.PPIOModel); !ok {
t.Fatalf("ModelDriver=%T, want *models.PPIOModel", provider.ModelDriver)
}
if provider.ModelDriver.Name() != "ppio" {
t.Errorf("ModelDriver.Name()=%q", provider.ModelDriver.Name())
}
if len(provider.Models) != 21 {
t.Fatalf("PPIO model count=%d, want 21", len(provider.Models))
}
for _, model := range provider.Models {
if !model.ModelTypeMap["chat"] {
t.Errorf("model %q missing chat type map", model.Name)
}
if model.Class == nil || *model.Class != "PPIO" {
t.Errorf("model %q class=%v", model.Name, model.Class)
}
}
models, err := pm.ListModels("PPIO")
if err != nil {
t.Fatalf("ListModels: %v", err)
}
if len(models) != 21 {
t.Errorf("ListModels count=%d, want 21", len(models))
}
model, err := pm.GetModelByName("ppio", "deepseek/deepseek-r1")
if err != nil {
t.Fatalf("GetModelByName: %v", err)
}
if model.MaxTokens != 64000 {
t.Errorf("deepseek/deepseek-r1 max_tokens=%d", model.MaxTokens)
}
model, err = pm.GetModelByName("ppio", "deepseek/deepseek-v4-pro")
if err != nil {
t.Fatalf("GetModelByName v4 pro: %v", err)
}
if model.MaxTokens != 1048576 {
t.Errorf("deepseek/deepseek-v4-pro max_tokens=%d", model.MaxTokens)
}
model, err = pm.GetModelByName("ppio", "deepseek/deepseek-v4-flash")
if err != nil {
t.Fatalf("GetModelByName v4 flash: %v", err)
}
if model.MaxTokens != 1048576 {
t.Errorf("deepseek/deepseek-v4-flash max_tokens=%d", model.MaxTokens)
}
resp := pm.SearchByType("chat")
if resp.Code != 0 {
t.Fatalf("SearchByType code=%d message=%q", resp.Code, resp.Message)
}
if len(resp.Data) != 21 {
t.Errorf("SearchByType data count=%d, want 21", len(resp.Data))
}
}

View File

@@ -774,7 +774,7 @@ func (b *BaiduModel) ListModels(apiConfig *APIConfig) ([]string, error) {
} }
func (b *BaiduModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { func (b *BaiduModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
return nil, fmt.Errorf(b.Name() + "no such method") return nil, fmt.Errorf("%s, no such method", b.Name())
} }
func (b *BaiduModel) CheckConnection(apiConfig *APIConfig) error { func (b *BaiduModel) CheckConnection(apiConfig *APIConfig) error {
@@ -783,13 +783,13 @@ func (b *BaiduModel) CheckConnection(apiConfig *APIConfig) error {
} }
func (z *BaiduModel) ParseFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, parseFileConfig *ParseFileConfig) (*ParseFileResponse, error) { func (z *BaiduModel) ParseFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, parseFileConfig *ParseFileConfig) (*ParseFileResponse, error) {
return nil, fmt.Errorf("no such method", z.Name()) return nil, fmt.Errorf("%s, no such method", z.Name())
} }
func (z *BaiduModel) ListTasks(apiConfig *APIConfig) ([]ListTaskStatus, error) { func (z *BaiduModel) ListTasks(apiConfig *APIConfig) ([]ListTaskStatus, error) {
return nil, fmt.Errorf("no such method", z.Name()) return nil, fmt.Errorf("%s, no such method", z.Name())
} }
func (z *BaiduModel) ShowTask(taskID string, apiConfig *APIConfig) (*TaskResponse, error) { func (z *BaiduModel) ShowTask(taskID string, apiConfig *APIConfig) (*TaskResponse, error) {
return nil, fmt.Errorf("no such method", z.Name()) return nil, fmt.Errorf("%s, no such method", z.Name())
} }

View File

@@ -670,7 +670,7 @@ func (c *CoHereModel) ListModels(apiConfig *APIConfig) ([]string, error) {
} }
func (c *CoHereModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { func (c *CoHereModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
return nil, fmt.Errorf(c.Name() + " no such method") return nil, fmt.Errorf("%s, no such method", c.Name())
} }
func (c *CoHereModel) CheckConnection(apiConfig *APIConfig) error { func (c *CoHereModel) CheckConnection(apiConfig *APIConfig) error {

View File

@@ -105,6 +105,8 @@ func (f *ModelFactory) CreateModelDriver(providerName string, baseURL map[string
return NewReplicateModel(baseURL, urlSuffix), nil return NewReplicateModel(baseURL, urlSuffix), nil
case "togetherai": case "togetherai":
return NewTogetherAIModel(baseURL, urlSuffix), nil return NewTogetherAIModel(baseURL, urlSuffix), nil
case "ppio":
return NewPPIOModel(baseURL, urlSuffix), nil
case "voyage": case "voyage":
return NewVoyageModel(baseURL, urlSuffix), nil return NewVoyageModel(baseURL, urlSuffix), nil
case "paddleocr": case "paddleocr":

View File

@@ -49,11 +49,11 @@ func (f *FishAudioModel) Name() string {
} }
func (f *FishAudioModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) { func (f *FishAudioModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) {
return nil, fmt.Errorf(f.Name() + " no such method") return nil, fmt.Errorf("%s, no such method", f.Name())
} }
func (f *FishAudioModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error { func (f *FishAudioModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error {
return fmt.Errorf(f.Name() + " no such method") return fmt.Errorf("%s, no such method", f.Name())
} }
func (f *FishAudioModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { func (f *FishAudioModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {

View File

@@ -219,8 +219,8 @@ func (m *MistralModel) ChatWithMessages(modelName string, messages []Message, ap
// actually produces a chain-of-thought: // actually produces a chain-of-thought:
// //
// "content": [ // "content": [
// {"type": "thinking", "thinking": [{"type": "text", "text": "..."}]}, // {"type": "thinking", "thinking": [{"type": "text", "text": "..."}]},
// {"type": "text", "text": "The final answer is ..."} // {"type": "text", "text": "The final answer is ..."}
// ] // ]
// //
// The function concatenates the visible text parts into the assistant // The function concatenates the visible text parts into the assistant
@@ -736,9 +736,9 @@ func (z *MistralModel) ParseFile(modelName *string, content []byte, url *string,
} }
func (z *MistralModel) ListTasks(apiConfig *APIConfig) ([]ListTaskStatus, error) { func (z *MistralModel) ListTasks(apiConfig *APIConfig) ([]ListTaskStatus, error) {
return nil, fmt.Errorf("no such method", z.Name()) return nil, fmt.Errorf("%s, no such method", z.Name())
} }
func (z *MistralModel) ShowTask(taskID string, apiConfig *APIConfig) (*TaskResponse, error) { func (z *MistralModel) ShowTask(taskID string, apiConfig *APIConfig) (*TaskResponse, error) {
return nil, fmt.Errorf("no such method", z.Name()) return nil, fmt.Errorf("%s, no such method", z.Name())
} }

View File

@@ -652,7 +652,7 @@ func (o *OpenRouterModel) ListModels(apiConfig *APIConfig) ([]string, error) {
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API request failed with status %d: %s : %s", resp.StatusCode, string(body)) return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
} }
// Parse response // Parse response

View File

@@ -55,35 +55,35 @@ func (p *PaddleOCRModel) Name() string {
} }
func (p *PaddleOCRModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) { func (p *PaddleOCRModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error { func (p *PaddleOCRModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error {
return fmt.Errorf("no such method", p.Name()) return fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { func (p *PaddleOCRModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { func (p *PaddleOCRModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { func (p *PaddleOCRModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) TranscribeAudioWithSender(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, sender func(*string, *string) error) error { func (p *PaddleOCRModel) TranscribeAudioWithSender(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, sender func(*string, *string) error) error {
return fmt.Errorf("no such method", p.Name()) return fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) { func (p *PaddleOCRModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error { func (p *PaddleOCRModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error {
return fmt.Errorf("no such method", p.Name()) return fmt.Errorf("%s, no such method", p.Name())
} }
type paddleSubmitResponse struct { type paddleSubmitResponse struct {
@@ -276,25 +276,25 @@ func (p *PaddleOCRModel) OCRFile(modelName *string, content []byte, fileURL *str
} }
func (p *PaddleOCRModel) ParseFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, parseFileConfig *ParseFileConfig) (*ParseFileResponse, error) { func (p *PaddleOCRModel) ParseFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, parseFileConfig *ParseFileConfig) (*ParseFileResponse, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) ListModels(apiConfig *APIConfig) ([]string, error) { func (p *PaddleOCRModel) ListModels(apiConfig *APIConfig) ([]string, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { func (p *PaddleOCRModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) CheckConnection(apiConfig *APIConfig) error { func (p *PaddleOCRModel) CheckConnection(apiConfig *APIConfig) error {
return fmt.Errorf("no such method", p.Name()) return fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) ListTasks(apiConfig *APIConfig) ([]ListTaskStatus, error) { func (p *PaddleOCRModel) ListTasks(apiConfig *APIConfig) ([]ListTaskStatus, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }
func (p *PaddleOCRModel) ShowTask(taskID string, apiConfig *APIConfig) (*TaskResponse, error) { func (p *PaddleOCRModel) ShowTask(taskID string, apiConfig *APIConfig) (*TaskResponse, error) {
return nil, fmt.Errorf("no such method", p.Name()) return nil, fmt.Errorf("%s, no such method", p.Name())
} }

View File

@@ -0,0 +1,433 @@
//
// Copyright 2026 The InfiniFlow Authors. 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 models
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// PPIOModel implements ModelDriver for PPIO.
//
// PPIO exposes OpenAI-compatible chat completions and model listing endpoints.
type PPIOModel struct {
BaseURL map[string]string
URLSuffix URLSuffix
httpClient *http.Client
}
func NewPPIOModel(baseURL map[string]string, urlSuffix URLSuffix) *PPIOModel {
defaultTransport, ok := http.DefaultTransport.(*http.Transport)
var transport *http.Transport
if ok {
transport = defaultTransport.Clone()
} else {
transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
}
}
transport.MaxIdleConns = 100
transport.MaxIdleConnsPerHost = 10
transport.IdleConnTimeout = 90 * time.Second
transport.DisableCompression = false
transport.ResponseHeaderTimeout = 60 * time.Second
return &PPIOModel{
BaseURL: baseURL,
URLSuffix: urlSuffix,
httpClient: &http.Client{
Transport: transport,
},
}
}
func (p *PPIOModel) NewInstance(baseURL map[string]string) ModelDriver {
return NewPPIOModel(baseURL, p.URLSuffix)
}
func (p *PPIOModel) Name() string {
return "ppio"
}
func (p *PPIOModel) baseURLForRegion(region string) (string, error) {
base, ok := p.BaseURL[region]
if ok && base != "" {
return strings.TrimSuffix(base, "/"), nil
}
if region == "" {
if base, ok := p.BaseURL["default"]; ok && base != "" {
return strings.TrimSuffix(base, "/"), nil
}
}
return "", fmt.Errorf("ppio: no base URL configured for region %q", region)
}
func (p *PPIOModel) endpoint(apiConfig *APIConfig, suffix string) (string, error) {
region := "default"
if apiConfig != nil && apiConfig.Region != nil {
region = *apiConfig.Region
}
baseURL, err := p.baseURLForRegion(region)
if err != nil {
return "", err
}
return fmt.Sprintf("%s/%s", baseURL, strings.TrimPrefix(suffix, "/")), nil
}
func ppioChatPayload(modelName string, messages []Message, stream bool, chatModelConfig *ChatConfig) map[string]interface{} {
apiMessages := make([]map[string]interface{}, len(messages))
for i, msg := range messages {
apiMessages[i] = map[string]interface{}{
"role": msg.Role,
"content": msg.Content,
}
}
reqBody := map[string]interface{}{
"model": modelName,
"messages": apiMessages,
"stream": stream,
}
if chatModelConfig != nil {
if chatModelConfig.MaxTokens != nil {
reqBody["max_tokens"] = *chatModelConfig.MaxTokens
}
if chatModelConfig.Temperature != nil {
reqBody["temperature"] = *chatModelConfig.Temperature
}
if chatModelConfig.TopP != nil {
reqBody["top_p"] = *chatModelConfig.TopP
}
if chatModelConfig.Stop != nil {
reqBody["stop"] = *chatModelConfig.Stop
}
}
return reqBody
}
type ppioChatMessage struct {
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content"`
Reasoning string `json:"reasoning"`
}
type ppioChatChoice struct {
Message ppioChatMessage `json:"message"`
Delta ppioChatMessage `json:"delta"`
FinishReason string `json:"finish_reason"`
}
type ppioChatResponse struct {
Choices []ppioChatChoice `json:"choices"`
Error interface{} `json:"error"`
FinishReason string `json:"finish_reason"`
}
func (p *PPIOModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) {
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return nil, fmt.Errorf("api key is required")
}
if strings.TrimSpace(modelName) == "" {
return nil, fmt.Errorf("model name is required")
}
if len(messages) == 0 {
return nil, fmt.Errorf("messages is empty")
}
url, err := p.endpoint(apiConfig, p.URLSuffix.Chat)
if err != nil {
return nil, err
}
jsonData, err := json.Marshal(ppioChatPayload(modelName, messages, false, chatModelConfig))
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
resp, err := p.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
var result ppioChatResponse
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
if result.Error != nil {
return nil, fmt.Errorf("ppio: upstream error: %v", result.Error)
}
if len(result.Choices) == 0 {
return nil, fmt.Errorf("no choices in response")
}
content := result.Choices[0].Message.Content
reasonContent := result.Choices[0].Message.ReasoningContent
if reasonContent == "" {
reasonContent = result.Choices[0].Message.Reasoning
}
return &ChatResponse{
Answer: &content,
ReasonContent: &reasonContent,
}, nil
}
const ppioStreamTimeout = 10 * time.Minute
func (p *PPIOModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error {
if sender == nil {
return fmt.Errorf("sender is required")
}
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return fmt.Errorf("api key is required")
}
if strings.TrimSpace(modelName) == "" {
return fmt.Errorf("model name is required")
}
if len(messages) == 0 {
return fmt.Errorf("messages is empty")
}
if chatModelConfig != nil && chatModelConfig.Stream != nil && !*chatModelConfig.Stream {
return fmt.Errorf("stream must be true in ChatStreamlyWithSender")
}
url, err := p.endpoint(apiConfig, p.URLSuffix.Chat)
if err != nil {
return err
}
jsonData, err := json.Marshal(ppioChatPayload(modelName, messages, true, chatModelConfig))
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), ppioStreamTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonData))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
req.Header.Set("Accept", "text/event-stream")
resp, err := p.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "data:") {
continue
}
data := strings.TrimSpace(line[5:])
if data == "[DONE]" {
sawTerminal = true
break
}
var event ppioChatResponse
if err = json.Unmarshal([]byte(data), &event); err != nil {
return fmt.Errorf("ppio: invalid SSE event: %w", err)
}
if event.Error != nil {
return fmt.Errorf("ppio: upstream stream error: %v", event.Error)
}
if len(event.Choices) == 0 {
continue
}
choice := event.Choices[0]
reasoning := choice.Delta.ReasoningContent
if reasoning == "" {
reasoning = choice.Delta.Reasoning
}
if reasoning != "" {
if err := sender(nil, &reasoning); err != nil {
return err
}
}
if choice.Delta.Content != "" {
if err := sender(&choice.Delta.Content, nil); err != nil {
return err
}
}
if choice.FinishReason != "" || event.FinishReason != "" {
sawTerminal = true
break
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
if !sawTerminal {
return fmt.Errorf("ppio: stream ended before [DONE] or finish_reason")
}
endOfStream := "[DONE]"
return sender(&endOfStream, nil)
}
type ppioModelInfo struct {
ID string `json:"id"`
}
type ppioListModelsResponse struct {
Data []ppioModelInfo `json:"data"`
Error interface{} `json:"error"`
}
func (p *PPIOModel) ListModels(apiConfig *APIConfig) ([]string, error) {
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return nil, fmt.Errorf("api key is required")
}
url, err := p.endpoint(apiConfig, p.URLSuffix.Models)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
resp, err := p.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
var result ppioListModelsResponse
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
if result.Error != nil {
return nil, fmt.Errorf("ppio: upstream error: %v", result.Error)
}
models := make([]string, 0, len(result.Data))
for _, model := range result.Data {
if model.ID != "" {
models = append(models, model.ID)
}
}
return models, nil
}
func (p *PPIOModel) CheckConnection(apiConfig *APIConfig) error {
_, err := p.ListModels(apiConfig)
return err
}
func (p *PPIOModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
return nil, fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
return nil, fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
return nil, fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) {
return nil, fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) TranscribeAudioWithSender(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, sender func(*string, *string) error) error {
return fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
return nil, fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error {
return fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) OCRFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, ocrConfig *OCRConfig) (*OCRFileResponse, error) {
return nil, fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) ParseFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, parseFileConfig *ParseFileConfig) (*ParseFileResponse, error) {
return nil, fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) ListTasks(apiConfig *APIConfig) ([]ListTaskStatus, error) {
return nil, fmt.Errorf("%s, no such method", p.Name())
}
func (p *PPIOModel) ShowTask(taskID string, apiConfig *APIConfig) (*TaskResponse, error) {
return nil, fmt.Errorf("%s, no such method", p.Name())
}

View File

@@ -0,0 +1,513 @@
package models
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return f(r)
}
func newPPIOServer(t *testing.T, handler func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter)) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("Authorization"); got != "Bearer test-key" {
t.Errorf("expected Authorization=Bearer test-key, got %q", got)
return
}
if got := r.Header.Get("Content-Type"); r.Method != http.MethodGet && !strings.HasPrefix(got, "application/json") {
t.Errorf("expected Content-Type to start with application/json, got %q", got)
return
}
var body map[string]interface{}
if r.Method == http.MethodPost {
raw, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("read body: %v", err)
return
}
if err := json.Unmarshal(raw, &body); err != nil {
t.Errorf("unmarshal: %v\nraw=%s", err, string(raw))
return
}
}
handler(t, r, body, w)
}))
}
func newPPIOForTest(baseURL string) *PPIOModel {
return NewPPIOModel(
map[string]string{"default": baseURL},
URLSuffix{Chat: "chat/completions", Models: "models"},
)
}
func TestPPIOName(t *testing.T) {
if got := newPPIOForTest("http://unused").Name(); got != "ppio" {
t.Errorf("Name()=%q", got)
}
}
func TestPPIOFactory(t *testing.T) {
driver, err := NewModelFactory().CreateModelDriver("PPIO", map[string]string{"default": "http://unused"}, URLSuffix{})
if err != nil {
t.Fatalf("CreateModelDriver: %v", err)
}
if _, ok := driver.(*PPIOModel); !ok {
t.Fatalf("driver type=%T, want *PPIOModel", driver)
}
}
func TestPPIONewModelWithCustomDefaultTransport(t *testing.T) {
original := http.DefaultTransport
http.DefaultTransport = roundTripperFunc(func(*http.Request) (*http.Response, error) {
return nil, nil
})
t.Cleanup(func() {
http.DefaultTransport = original
})
if model := NewPPIOModel(map[string]string{"default": "http://unused"}, URLSuffix{}); model == nil {
t.Fatal("NewPPIOModel returned nil")
}
}
func TestPPIOChatHappyPath(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
if r.URL.Path != "/chat/completions" {
t.Errorf("path=%s", r.URL.Path)
}
if body["model"] != "deepseek/deepseek-r1" {
t.Errorf("model=%v", body["model"])
}
if body["stream"] != false {
t.Errorf("stream=%v want false", body["stream"])
}
if _, ok := body["reasoning_effort"]; ok {
t.Errorf("reasoning_effort should not be sent: %v", body["reasoning_effort"])
}
if body["max_tokens"] != float64(32) {
t.Errorf("max_tokens=%v", body["max_tokens"])
}
if body["temperature"] != 0.3 {
t.Errorf("temperature=%v", body["temperature"])
}
if body["top_p"] != 0.9 {
t.Errorf("top_p=%v", body["top_p"])
}
stop, ok := body["stop"].([]interface{})
if !ok || len(stop) != 1 || stop[0] != "END" {
t.Errorf("stop=%#v", body["stop"])
}
messages, ok := body["messages"].([]interface{})
if !ok || len(messages) != 1 {
t.Fatalf("messages=%#v", body["messages"])
}
first, ok := messages[0].(map[string]interface{})
if !ok {
t.Fatalf("message type=%T", messages[0])
}
if first["role"] != "user" || first["content"] != "ping" {
t.Errorf("message=%#v", first)
}
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"choices": []map[string]interface{}{{
"message": map[string]interface{}{
"content": "pong",
"reasoning_content": "thinking",
},
}},
})
})
defer srv.Close()
apiKey := "test-key"
mt := 32
temp := 0.3
topP := 0.9
stop := []string{"END"}
effort := "high"
resp, err := newPPIOForTest(srv.URL).ChatWithMessages(
"deepseek/deepseek-r1",
[]Message{{Role: "user", Content: "ping"}},
&APIConfig{ApiKey: &apiKey},
&ChatConfig{MaxTokens: &mt, Temperature: &temp, TopP: &topP, Stop: &stop, Effort: &effort},
)
if err != nil {
t.Fatalf("ChatWithMessages: %v", err)
}
if *resp.Answer != "pong" {
t.Errorf("Answer=%q", *resp.Answer)
}
if *resp.ReasonContent != "thinking" {
t.Errorf("ReasonContent=%q", *resp.ReasonContent)
}
}
func TestPPIOChatUsesReasoningFallback(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"choices": []map[string]interface{}{{
"message": map[string]interface{}{
"content": "pong",
"reasoning": "fallback reasoning",
},
}},
})
})
defer srv.Close()
apiKey := "test-key"
resp, err := newPPIOForTest(srv.URL).ChatWithMessages(
"deepseek/deepseek-r1",
[]Message{{Role: "user", Content: "ping"}},
&APIConfig{ApiKey: &apiKey},
nil,
)
if err != nil {
t.Fatalf("ChatWithMessages: %v", err)
}
if *resp.ReasonContent != "fallback reasoning" {
t.Errorf("ReasonContent=%q", *resp.ReasonContent)
}
}
func TestPPIOChatRequiresModelName(t *testing.T) {
apiKey := "test-key"
_, err := newPPIOForTest("http://unused").ChatWithMessages("", []Message{{Role: "user", Content: "x"}}, &APIConfig{ApiKey: &apiKey}, nil)
if err == nil || !strings.Contains(err.Error(), "model name is required") {
t.Errorf("expected model-name error, got %v", err)
}
}
func TestPPIOChatRequiresMessages(t *testing.T) {
apiKey := "test-key"
_, err := newPPIOForTest("http://unused").ChatWithMessages("deepseek/deepseek-r1", nil, &APIConfig{ApiKey: &apiKey}, nil)
if err == nil || !strings.Contains(err.Error(), "messages is empty") {
t.Errorf("expected messages error, got %v", err)
}
}
func TestPPIOChatSurfacesHTTPError(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
http.Error(w, "bad key", http.StatusUnauthorized)
})
defer srv.Close()
apiKey := "test-key"
_, err := newPPIOForTest(srv.URL).ChatWithMessages("deepseek/deepseek-r1", []Message{{Role: "user", Content: "x"}}, &APIConfig{ApiKey: &apiKey}, nil)
if err == nil || !strings.Contains(err.Error(), "status 401") {
t.Errorf("expected HTTP status error, got %v", err)
}
}
func TestPPIOChatRejectsProviderError(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": map[string]interface{}{"message": "invalid model"},
})
})
defer srv.Close()
apiKey := "test-key"
_, err := newPPIOForTest(srv.URL).ChatWithMessages("deepseek/deepseek-r1", []Message{{Role: "user", Content: "x"}}, &APIConfig{ApiKey: &apiKey}, nil)
if err == nil || !strings.Contains(err.Error(), "upstream error") {
t.Errorf("expected upstream error, got %v", err)
}
}
func TestPPIOStreamHappyPath(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
if r.URL.Path != "/chat/completions" {
t.Errorf("path=%s", r.URL.Path)
}
if body["stream"] != true {
t.Errorf("stream=%v want true", body["stream"])
}
if got := r.Header.Get("Accept"); got != "text/event-stream" {
t.Errorf("Accept=%q", got)
}
w.Header().Set("Content-Type", "text/event-stream")
_, _ = io.WriteString(w,
`data: {"choices":[{"delta":{"reasoning_content":"think "}}]}`+"\n"+
`data: {"choices":[{"delta":{"reasoning":"fallback "}}]}`+"\n"+
`data: {"choices":[{"delta":{"content":"Hello"}}]}`+"\n"+
`data: {"choices":[{"delta":{"content":" world"},"finish_reason":"stop"}]}`+"\n",
)
})
defer srv.Close()
apiKey := "test-key"
var content []string
var reasoning []string
err := newPPIOForTest(srv.URL).ChatStreamlyWithSender(
"deepseek/deepseek-r1",
[]Message{{Role: "user", Content: "hi"}},
&APIConfig{ApiKey: &apiKey}, nil,
func(c *string, r *string) error {
if c != nil {
content = append(content, *c)
}
if r != nil {
reasoning = append(reasoning, *r)
}
return nil
},
)
if err != nil {
t.Fatalf("ChatStreamlyWithSender: %v", err)
}
if strings.Join(content, "") != "Hello world[DONE]" {
t.Errorf("content=%q", strings.Join(content, ""))
}
if strings.Join(reasoning, "") != "think fallback " {
t.Errorf("reasoning=%q", strings.Join(reasoning, ""))
}
if len(content) == 0 || content[len(content)-1] != "[DONE]" {
t.Errorf("final content sentinel missing: %#v", content)
}
}
func TestPPIOStreamSurfacesHTTPError(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
http.Error(w, "bad key", http.StatusUnauthorized)
})
defer srv.Close()
apiKey := "test-key"
err := newPPIOForTest(srv.URL).ChatStreamlyWithSender(
"deepseek/deepseek-r1",
[]Message{{Role: "user", Content: "hi"}},
&APIConfig{ApiKey: &apiKey}, nil,
func(*string, *string) error { return nil },
)
if err == nil || !strings.Contains(err.Error(), "status 401") {
t.Errorf("expected HTTP status error, got %v", err)
}
}
func TestPPIOStreamStopsOnSenderError(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = io.WriteString(w, `data: {"choices":[{"delta":{"content":"partial"}}]}`+"\n")
})
defer srv.Close()
apiKey := "test-key"
err := newPPIOForTest(srv.URL).ChatStreamlyWithSender(
"deepseek/deepseek-r1",
[]Message{{Role: "user", Content: "hi"}},
&APIConfig{ApiKey: &apiKey}, nil,
func(*string, *string) error { return io.ErrUnexpectedEOF },
)
if err == nil || !strings.Contains(err.Error(), "unexpected EOF") {
t.Errorf("expected sender error, got %v", err)
}
}
func TestPPIOStreamRejectsExplicitFalse(t *testing.T) {
apiKey := "test-key"
stream := false
err := newPPIOForTest("http://unused").ChatStreamlyWithSender(
"deepseek/deepseek-r1",
[]Message{{Role: "user", Content: "hi"}},
&APIConfig{ApiKey: &apiKey},
&ChatConfig{Stream: &stream},
func(*string, *string) error { return nil },
)
if err == nil || !strings.Contains(err.Error(), "stream must be true") {
t.Errorf("expected stream guard, got %v", err)
}
}
func TestPPIOStreamRequiresSender(t *testing.T) {
apiKey := "test-key"
err := newPPIOForTest("http://unused").ChatStreamlyWithSender(
"deepseek/deepseek-r1",
[]Message{{Role: "user", Content: "hi"}},
&APIConfig{ApiKey: &apiKey}, nil, nil,
)
if err == nil || !strings.Contains(err.Error(), "sender is required") {
t.Errorf("expected sender error, got %v", err)
}
}
func TestPPIOStreamRequiresTerminalEvent(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = io.WriteString(w, `data: {"choices":[{"delta":{"content":"partial"}}]}`+"\n")
})
defer srv.Close()
apiKey := "test-key"
err := newPPIOForTest(srv.URL).ChatStreamlyWithSender(
"deepseek/deepseek-r1",
[]Message{{Role: "user", Content: "hi"}},
&APIConfig{ApiKey: &apiKey}, nil,
func(*string, *string) error { return nil },
)
if err == nil || !strings.Contains(err.Error(), "stream ended before") {
t.Errorf("expected unterminated stream error, got %v", err)
}
}
func TestPPIOListModelsAndCheckConnection(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
if r.Method != http.MethodGet {
t.Errorf("method=%s", r.Method)
}
if r.URL.Path != "/models" {
t.Errorf("path=%s", r.URL.Path)
}
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"data": []map[string]interface{}{
{"id": "deepseek/deepseek-r1"},
{"id": "qwen/qwen-2.5-72b-instruct"},
},
})
})
defer srv.Close()
apiKey := "test-key"
model := newPPIOForTest(srv.URL)
models, err := model.ListModels(&APIConfig{ApiKey: &apiKey})
if err != nil {
t.Fatalf("ListModels: %v", err)
}
if strings.Join(models, ",") != "deepseek/deepseek-r1,qwen/qwen-2.5-72b-instruct" {
t.Errorf("models=%v", models)
}
if err := model.CheckConnection(&APIConfig{ApiKey: &apiKey}); err != nil {
t.Fatalf("CheckConnection: %v", err)
}
}
func TestPPIOListModelsRequiresAPIKey(t *testing.T) {
_, err := newPPIOForTest("http://unused").ListModels(&APIConfig{})
if err == nil || !strings.Contains(err.Error(), "api key is required") {
t.Errorf("expected api-key error, got %v", err)
}
}
func TestPPIOListModelsRejectsProviderError(t *testing.T) {
srv := newPPIOServer(t, func(t *testing.T, r *http.Request, body map[string]interface{}, w http.ResponseWriter) {
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": map[string]interface{}{"message": "unauthorized"},
})
})
defer srv.Close()
apiKey := "test-key"
_, err := newPPIOForTest(srv.URL).ListModels(&APIConfig{ApiKey: &apiKey})
if err == nil || !strings.Contains(err.Error(), "upstream error") {
t.Errorf("expected upstream error, got %v", err)
}
}
func TestPPIOEndpointTrimsTrailingSlash(t *testing.T) {
model := NewPPIOModel(map[string]string{"default": "https://example.test/base/"}, URLSuffix{Chat: "/chat/completions"})
apiKey := "test-key"
endpoint, err := model.endpoint(&APIConfig{ApiKey: &apiKey}, model.URLSuffix.Chat)
if err != nil {
t.Fatalf("endpoint: %v", err)
}
if endpoint != "https://example.test/base/chat/completions" {
t.Errorf("endpoint=%q", endpoint)
}
}
func TestPPIODefaultEndpointUsesPPIOAPI(t *testing.T) {
model := NewPPIOModel(map[string]string{"default": "https://api.ppio.com/openai/v1"}, URLSuffix{Chat: "chat/completions"})
apiKey := "test-key"
endpoint, err := model.endpoint(&APIConfig{ApiKey: &apiKey}, model.URLSuffix.Chat)
if err != nil {
t.Fatalf("endpoint: %v", err)
}
if endpoint != "https://api.ppio.com/openai/v1/chat/completions" {
t.Errorf("endpoint=%q", endpoint)
}
}
func TestPPIOEmptyRegionCustomBaseURL(t *testing.T) {
model := NewPPIOModel(map[string]string{"": "https://custom.example/openai/v1"}, URLSuffix{Models: "models"})
apiKey := "test-key"
region := ""
endpoint, err := model.endpoint(&APIConfig{ApiKey: &apiKey, Region: &region}, model.URLSuffix.Models)
if err != nil {
t.Fatalf("endpoint: %v", err)
}
if endpoint != "https://custom.example/openai/v1/models" {
t.Errorf("endpoint=%q", endpoint)
}
}
func TestPPIONamedRegionBaseURL(t *testing.T) {
model := NewPPIOModel(map[string]string{
"default": "https://api.ppio.com/openai/v1",
"us": "https://api.ppinfra.com/v3/openai",
}, URLSuffix{Chat: "chat/completions"})
apiKey := "test-key"
region := "us"
endpoint, err := model.endpoint(&APIConfig{ApiKey: &apiKey, Region: &region}, model.URLSuffix.Chat)
if err != nil {
t.Fatalf("endpoint: %v", err)
}
if endpoint != "https://api.ppinfra.com/v3/openai/chat/completions" {
t.Errorf("endpoint=%q", endpoint)
}
}
func TestPPIOMissingRegionBaseURL(t *testing.T) {
model := NewPPIOModel(map[string]string{"default": "https://api.ppinfra.com/v3/openai"}, URLSuffix{Models: "models"})
apiKey := "test-key"
region := "missing"
_, err := model.endpoint(&APIConfig{ApiKey: &apiKey, Region: &region}, model.URLSuffix.Models)
if err == nil || !strings.Contains(err.Error(), "no base URL configured") {
t.Errorf("expected base URL error, got %v", err)
}
}
func TestPPIOUnsupportedMethods(t *testing.T) {
m := newPPIOForTest("http://unused")
if _, err := m.Embed(nil, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Embed error=%v", err)
}
if _, err := m.Rerank(nil, "", nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Rerank error=%v", err)
}
if _, err := m.Balance(nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Balance error=%v", err)
}
if _, err := m.TranscribeAudio(nil, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("TranscribeAudio error=%v", err)
}
if err := m.TranscribeAudioWithSender(nil, nil, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("TranscribeAudioWithSender error=%v", err)
}
if _, err := m.AudioSpeech(nil, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("AudioSpeech error=%v", err)
}
if err := m.AudioSpeechWithSender(nil, nil, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("AudioSpeechWithSender error=%v", err)
}
if _, err := m.OCRFile(nil, nil, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("OCRFile error=%v", err)
}
if _, err := m.ParseFile(nil, nil, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("ParseFile error=%v", err)
}
if _, err := m.ListTasks(nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("ListTasks error=%v", err)
}
if _, err := m.ShowTask("", nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("ShowTask error=%v", err)
}
}

View File

@@ -309,9 +309,6 @@ func TestReplicateListModelsAndCheckConnection(t *testing.T) {
func TestReplicateUnsupportedMethods(t *testing.T) { func TestReplicateUnsupportedMethods(t *testing.T) {
m := newReplicateForTest("http://unused") m := newReplicateForTest("http://unused")
if _, err := m.Embed(nil, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Embed error=%v", err)
}
if _, err := m.Rerank(nil, "", nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") { if _, err := m.Rerank(nil, "", nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Rerank error=%v", err) t.Errorf("Rerank error=%v", err)
} }

View File

@@ -265,9 +265,6 @@ func TestTogetherAIListModelsAndCheckConnection(t *testing.T) {
func TestTogetherAIUnsupportedMethods(t *testing.T) { func TestTogetherAIUnsupportedMethods(t *testing.T) {
m := newTogetherAIForTest("http://unused") m := newTogetherAIForTest("http://unused")
if _, err := m.Embed(nil, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Embed error=%v", err)
}
if _, err := m.Rerank(nil, "", nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") { if _, err := m.Rerank(nil, "", nil, nil, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Rerank error=%v", err) t.Errorf("Rerank error=%v", err)
} }

View File

@@ -17,7 +17,7 @@ func newXinferenceForTest(baseURL string) *XinferenceModel {
Chat: "v1/chat/completions", Chat: "v1/chat/completions",
Embedding: "v1/embeddings", Embedding: "v1/embeddings",
Models: "v1/models", Models: "v1/models",
Rerank: "v1/rerank", Rerank: "v1/rerank",
}, },
) )
} }
@@ -490,12 +490,6 @@ func TestXinferenceUnsupportedMethodsReturnNoSuchMethod(t *testing.T) {
x := newXinferenceForTest("http://unused") x := newXinferenceForTest("http://unused")
model := "qwen2.5-instruct" model := "qwen2.5-instruct"
if _, err := x.Rerank(&model, "q", []string{"d"}, &APIConfig{}, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Rerank: expected no such method, got %v", err)
}
if _, err := x.Embed(&model, []string{"x"}, &APIConfig{}, nil); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Embed: expected no such method, got %v", err)
}
if _, err := x.Balance(&APIConfig{}); err == nil || !strings.Contains(err.Error(), "no such method") { if _, err := x.Balance(&APIConfig{}); err == nil || !strings.Contains(err.Error(), "no such method") {
t.Errorf("Balance: expected no such method, got %v", err) t.Errorf("Balance: expected no such method, got %v", err)
} }

View File

@@ -411,7 +411,7 @@ func (x *XunFeiModel) ListModels(apiConfig *APIConfig) ([]string, error) {
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API request failed with status %d: %s : %s", resp.StatusCode, string(body)) return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
} }
// Parse response // Parse response