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 // Call returns call number n.
38 func (f *ModelFake) Call(n int) ModelFakeCall {
40 defer f.mutex.Unlock()
45 // Calls returns the number of calls.
46 func (f *ModelFake) Calls() int {
48 defer f.mutex.Unlock()
53 func (f *ModelFake) serve(w http.ResponseWriter, r *http.Request) {
54 raw, err := io.ReadAll(r.Body)
56 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)
72 call.number = len(f.calls)
73 f.calls = append(f.calls, call)
80 func newModelFake(t *testing.T) *ModelFake {
84 reply: func(w http.ResponseWriter, _ ModelFakeCall) {
85 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("a line")}, 100, 0, 5))
89 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
95 func modelTestRequest() ModelRequest {
99 Input: []any{modelUserMessage("hello")},
103 // modelWriteEvents writes events as a server-sent event stream.
104 func modelWriteEvents(w http.ResponseWriter, events ...any) {
105 w.Header().Set("Content-Type", "text/event-stream")
106 for _, event := range events {
107 data, err := json.Marshal(event)
112 _, err = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event.(map[string]any)["type"], data)
119 func modelMessageItem(text string) map[string]any {
120 return map[string]any{
124 map[string]any{"type": "output_text", "text": text},
129 func modelCompletedEvent(output []any, input, cached, out int) map[string]any {
134 return map[string]any{
135 "type": "response.completed",
136 "response": map[string]any{
138 "usage": map[string]any{
139 "input_tokens": input,
140 "input_tokens_details": map[string]any{"cached_tokens": cached},
141 "output_tokens": out,
147 func modelReadUsage(t *testing.T, path string) []ModelUsageRecord {
150 file, err := os.Open(path)
151 require.NoError(t, err)
154 require.NoError(t, file.Close())
157 var records []ModelUsageRecord
158 scanner := bufio.NewScanner(file)
160 var record ModelUsageRecord
161 require.NoError(t, json.Unmarshal(scanner.Bytes(), &record))
162 records = append(records, record)
165 require.NoError(t, scanner.Err())
170 func modelReasoningItem(id, encrypted string) map[string]any {
171 return map[string]any{
174 "encrypted_content": encrypted,
179 func modelFunctionCallItem(id, callID, name, arguments string) map[string]any {
180 return map[string]any{
181 "type": "function_call",
185 "arguments": arguments,