Skip to content

Commit 4d011c5

Browse files
committed
feat: add OpenRouter balance update functionality and improve code formatting
1 parent eb96aa6 commit 4d011c5

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

controller/channel-billing.go

+25
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,13 @@ type DeepSeekUsageResponse struct {
112112
} `json:"balance_infos"`
113113
}
114114

115+
type OpenRouterResponse struct {
116+
Data struct {
117+
TotalCredits float64 `json:"total_credits"`
118+
TotalUsage float64 `json:"total_usage"`
119+
} `json:"data"`
120+
}
121+
115122
// GetAuthHeader get auth header
116123
func GetAuthHeader(token string) http.Header {
117124
h := http.Header{}
@@ -285,6 +292,22 @@ func updateChannelDeepSeekBalance(channel *model.Channel) (float64, error) {
285292
return balance, nil
286293
}
287294

295+
func updateChannelOpenRouterBalance(channel *model.Channel) (float64, error) {
296+
url := "https://openrouter.ai/api/v1/credits"
297+
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
298+
if err != nil {
299+
return 0, err
300+
}
301+
response := OpenRouterResponse{}
302+
err = json.Unmarshal(body, &response)
303+
if err != nil {
304+
return 0, err
305+
}
306+
balance := response.Data.TotalCredits - response.Data.TotalUsage
307+
channel.UpdateBalance(balance)
308+
return balance, nil
309+
}
310+
288311
func updateChannelBalance(channel *model.Channel) (float64, error) {
289312
baseURL := channeltype.ChannelBaseURLs[channel.Type]
290313
if channel.GetBaseURL() == "" {
@@ -313,6 +336,8 @@ func updateChannelBalance(channel *model.Channel) (float64, error) {
313336
return updateChannelSiliconFlowBalance(channel)
314337
case channeltype.DeepSeek:
315338
return updateChannelDeepSeekBalance(channel)
339+
case channeltype.OpenRouter:
340+
return updateChannelOpenRouterBalance(channel)
316341
default:
317342
return 0, errors.New("尚未实现")
318343
}

controller/channel-test.go

+1
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ func testChannel(ctx context.Context, channel *model.Channel, request *relaymode
153153
rawResponse := w.Body.String()
154154
_, responseMessage, err = parseTestResponse(rawResponse)
155155
if err != nil {
156+
logger.SysError(fmt.Sprintf("failed to parse error: %s, \nresponse: %s", err.Error(), rawResponse))
156157
return "", err, nil
157158
}
158159
result := w.Result()

web/default/src/components/ChannelsTable.js

+2
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ function renderBalance(type, balance, t) {
5757
return <span>¥{balance.toFixed(2)}</span>;
5858
case 13: // AIGC2D
5959
return <span>{renderNumber(balance)}</span>;
60+
case 20: // OpenRouter
61+
return <span>${balance.toFixed(2)}</span>;
6062
case 36: // DeepSeek
6163
return <span>¥{balance.toFixed(2)}</span>;
6264
case 44: // SiliconFlow

0 commit comments

Comments
 (0)