fix(moonshot): resolve 401 Unauthorized errors by trimming API keys and improving request compatibility
Some checks failed
CI / Lint (push) Has been cancelled
CI / Test (push) Has been cancelled
CI / Build (push) Has been cancelled

This commit is contained in:
2026-03-26 17:09:27 +00:00
parent 5be2f6f7aa
commit 9375448087
3 changed files with 24 additions and 5 deletions

View File

@@ -203,5 +203,5 @@ func (c *Config) GetAPIKey(provider string) (string, error) {
if val == "" {
return "", fmt.Errorf("environment variable %s not set for %s", envVar, provider)
}
return val, nil
return strings.TrimSpace(val), nil
}

View File

@@ -58,9 +58,20 @@ func MessagesToOpenAIJSON(messages []models.UnifiedMessage) ([]interface{}, erro
}
}
var finalContent interface{}
if len(parts) == 1 {
if p, ok := parts[0].(map[string]interface{}); ok && p["type"] == "text" {
finalContent = p["text"]
} else {
finalContent = parts
}
} else {
finalContent = parts
}
msg := map[string]interface{}{
"role": m.Role,
"content": parts,
"content": finalContent,
}
if m.ReasoningContent != nil {

View File

@@ -21,7 +21,7 @@ func NewMoonshotProvider(cfg config.MoonshotConfig, apiKey string) *MoonshotProv
return &MoonshotProvider{
client: resty.New(),
config: cfg,
apiKey: apiKey,
apiKey: strings.TrimSpace(apiKey),
}
}
@@ -43,11 +43,15 @@ func (p *MoonshotProvider) ChatCompletion(ctx context.Context, req *models.Unifi
}
}
baseURL := strings.TrimRight(p.config.BaseURL, "/")
resp, err := p.client.R().
SetContext(ctx).
SetHeader("Authorization", "Bearer "+p.apiKey).
SetHeader("Content-Type", "application/json").
SetHeader("Accept", "application/json").
SetBody(body).
Post(fmt.Sprintf("%s/chat/completions", p.config.BaseURL))
Post(fmt.Sprintf("%s/chat/completions", baseURL))
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
@@ -79,12 +83,16 @@ func (p *MoonshotProvider) ChatCompletionStream(ctx context.Context, req *models
}
}
baseURL := strings.TrimRight(p.config.BaseURL, "/")
resp, err := p.client.R().
SetContext(ctx).
SetHeader("Authorization", "Bearer "+p.apiKey).
SetHeader("Content-Type", "application/json").
SetHeader("Accept", "text/event-stream").
SetBody(body).
SetDoNotParseResponse(true).
Post(fmt.Sprintf("%s/chat/completions", p.config.BaseURL))
Post(fmt.Sprintf("%s/chat/completions", baseURL))
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)