14 "github.com/stretchr/testify/require"
17 // modelTestKey is a fake API key.
18 const modelTestKey = "sk-test-not-a-real-key"
20 // ModelFakeCall is one call to a fake endpoint, numbered from 0.
21 type ModelFakeCall struct {
28 // ModelFake is an httptest Responses endpoint. It keeps each call, and reply
29 // writes the response. The default reply is one short message.
30 type ModelFake struct {
34 reply func(http.ResponseWriter, ModelFakeCall)
37 func newModelFake(t *testing.T) *ModelFake {
41 reply: func(w http.ResponseWriter, _ ModelFakeCall) {
42 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("a line")}, 100, 0, 5))
46 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
52 func (f *ModelFake) serve(w http.ResponseWriter, r *http.Request) {
53 raw, err := io.ReadAll(r.Body)
55 http.Error(w, err.Error(), http.StatusBadRequest)
60 call := ModelFakeCall{
61 header: r.Header.Clone(),
65 err = json.Unmarshal(raw, &call.body)
67 http.Error(w, err.Error(), http.StatusBadRequest)
74 call.number = len(f.calls)
75 f.calls = append(f.calls, call)
82 // Call returns call number n.
83 func (f *ModelFake) Call(n int) ModelFakeCall {
85 defer f.mutex.Unlock()
90 // Calls returns the number of calls.
91 func (f *ModelFake) Calls() int {
93 defer f.mutex.Unlock()
98 // modelWriteEvents writes events as a server-sent event stream.
99 func modelWriteEvents(w http.ResponseWriter, events ...any) {
100 w.Header().Set("Content-Type", "text/event-stream")
102 for _, event := range events {
103 data, err := json.Marshal(event)
108 _, err = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event.(map[string]any)["type"], data)
115 func modelCompletedEvent(output []any, input, cached, out int) map[string]any {
120 return map[string]any{
121 "type": "response.completed",
122 "response": map[string]any{
124 "usage": map[string]any{
125 "input_tokens": input,
126 "input_tokens_details": map[string]any{"cached_tokens": cached},
127 "output_tokens": out,
133 func modelMessageItem(text string) map[string]any {
134 return map[string]any{
138 map[string]any{"type": "output_text", "text": text},
143 func modelTestRequest() ModelRequest {
147 Input: []any{modelUserMessage("hello")},
151 func modelReadUsage(t *testing.T, path string) []ModelUsageRecord {
154 file, err := os.Open(path)
155 require.NoError(t, err)
158 require.NoError(t, file.Close())
161 var records []ModelUsageRecord
163 scanner := bufio.NewScanner(file)
165 var record ModelUsageRecord
167 require.NoError(t, json.Unmarshal(scanner.Bytes(), &record))
169 records = append(records, record)
172 require.NoError(t, scanner.Err())
177 func modelFunctionCallItem(id, callID, name, arguments string) map[string]any {
178 return map[string]any{
179 "type": "function_call",
183 "arguments": arguments,