forked from googleapis/go-genai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.go
More file actions
175 lines (162 loc) · 4.58 KB
/
common.go
File metadata and controls
175 lines (162 loc) · 4.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// Copyright 2024 Google LLC
//
// 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 genai
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"iter"
"net/url"
"reflect"
"sort"
"strconv"
)
// Ptr returns a pointer to its argument.
// It can be used to initialize pointer fields:
//
// genai.GenerateContentConfig{Temperature: genai.Ptr(0.5)}
func Ptr[T any](t T) *T { return &t }
type converterFunc func(*apiClient, map[string]any, map[string]any) (map[string]any, error)
type transformerFunc[T any] func(*apiClient, T) (T, error)
func setValueByPath(data map[string]any, keys []string, value any) {
if value == nil {
return
}
for i := 0; i < len(keys)-1; i++ {
key := keys[i]
if _, ok := data[key]; !ok {
data[key] = make(map[string]any)
}
if _, ok := data[key].(map[string]any); !ok {
data[key] = make(map[string]any)
}
data = data[key].(map[string]any)
}
if !reflect.ValueOf(value).IsZero() {
data[keys[len(keys)-1]] = value
}
}
func getValueByPath(data map[string]any, keys []string) any {
if len(keys) == 1 && keys[0] == "_self" {
return data
}
var current any = data
for _, key := range keys {
switch v := current.(type) {
case map[string]any:
current = v[key]
default:
return nil // Key not found or invalid type
}
}
return current
}
func formatMap(template string, variables map[string]any) (string, error) {
var buffer bytes.Buffer
for i := 0; i < len(template); i++ {
if template[i] == '{' {
j := i + 1
for j < len(template) && template[j] != '}' {
j++
}
if j < len(template) {
key := template[i+1 : j]
if value, ok := variables[key]; ok {
switch val := value.(type) {
case string:
buffer.WriteString(val)
default:
return "", errors.New("formatMap: nested interface or unsupported type found")
}
}
i = j
}
} else {
buffer.WriteByte(template[i])
}
}
return buffer.String(), nil
}
// applyConverterToSlice calls converter function to each element of the slice.
func applyConverterToSlice(ac *apiClient, inputs []any, converter converterFunc) ([]map[string]any, error) {
var outputs []map[string]any
for _, object := range inputs {
object, err := converter(ac, object.(map[string]any), nil)
if err != nil {
return nil, err
}
outputs = append(outputs, object)
}
return outputs, nil
}
// applyItemTransformerToSlice calls item transformer function to each element of the slice.
func applyItemTransformerToSlice[T any](ac *apiClient, inputs []T, itemTransformer transformerFunc[T]) ([]T, error) {
var outputs []T
for _, input := range inputs {
object, err := itemTransformer(ac, input)
if err != nil {
return nil, err
}
outputs = append(outputs, object)
}
return outputs, nil
}
func deepMarshal(input any, output *map[string]any) error {
if inputBytes, err := json.Marshal(input); err != nil {
return fmt.Errorf("deepMarshal: unable to marshal input: %w", err)
} else if err := json.Unmarshal(inputBytes, output); err != nil {
return fmt.Errorf("deepMarshal: unable to unmarshal input: %w", err)
}
return nil
}
// createURLQuery creates a URL query string from a map of key-value pairs.
// The keys are sorted alphabetically before being encoded.
// Supported value types are string, int, float64, bool, and []string.
// An error is returned if an unsupported type is encountered.
func createURLQuery(query map[string]any) (string, error) {
v := url.Values{}
keys := make([]string, 0, len(query))
for k := range query {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
value := query[key]
switch value := value.(type) {
case string:
v.Add(key, value)
case int:
v.Add(key, strconv.Itoa(value))
case float64:
v.Add(key, strconv.FormatFloat(value, 'f', -1, 64))
case bool:
v.Add(key, strconv.FormatBool(value))
case []string:
for _, item := range value {
v.Add(key, item)
}
default:
return "", fmt.Errorf("unsupported type: %T", value)
}
}
return v.Encode(), nil
}
func yieldErrorAndEndIterator[T any](err error) iter.Seq2[*T, error] {
return func(yield func(*T, error) bool) {
if !yield(nil, err) {
return
}
}
}