models.go

v0.6.0
Doc Versions Source
1
package kimi
2
3
import (
4
	"encoding/json"
5
	"fmt"
6
	"io"
7
	"net/http"
8
	"time"
9
)
10
11
type Model struct {
12
	ID                string `json:"id"`
13
	Created           int64  `json:"created"`
14
	CreatedAt         string `json:"created_at"`
15
	Object            string `json:"object"`
16
	DisplayName       string `json:"display_name"`
17
	Type              string `json:"type"`
18
	ContextLength     int    `json:"context_length"`
19
	SupportsReasoning bool   `json:"supports_reasoning"`
20
	SupportsImageIn   bool   `json:"supports_image_in"`
21
	SupportsVideoIn   bool   `json:"supports_video_in"`
22
}
23
24
type modelsResponse struct {
25
	Data    []Model `json:"data"`
26
	Object  string  `json:"object"`
27
	FirstID string  `json:"first_id"`
28
	LastID  string  `json:"last_id"`
29
	HasMore bool    `json:"has_more"`
30
}
31
32
func (m Model) GetName() string {
33
	if m.DisplayName != "" {
34
		return m.DisplayName
35
	}
36
	return m.ID
37
}
38
39
func ListModels(baseURL, apiKey string) ([]Model, error) {
40
	client := &http.Client{Timeout: 30 * time.Second}
41
	url := baseURL + "models"
42
	req, err := http.NewRequest("GET", url, nil)
43
	if err != nil {
44
		return nil, fmt.Errorf("creating request: %w", err)
45
	}
46
	req.Header.Set("Authorization", "Bearer "+apiKey)
47
	resp, err := client.Do(req)
48
	if err != nil {
49
		return nil, fmt.Errorf("fetching models: %w", err)
50
	}
51
	defer resp.Body.Close()
52
	if resp.StatusCode != http.StatusOK {
53
		body, _ := io.ReadAll(resp.Body)
54
		return nil, fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
55
	}
56
	var result modelsResponse
57
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
58
		return nil, fmt.Errorf("decoding response: %w", err)
59
	}
60
	return result.Data, nil
61
}
62
63
func CategorizeModels(models []Model) ([]string, map[string][]Model) {
64
	families := []string{"Available"}
65
	grouped := make(map[string][]Model)
66
	for _, m := range models {
67
		grouped["Available"] = append(grouped["Available"], m)
68
	}
69
	return families, grouped
70
}
71

Source Files