-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathopenai_test.go
More file actions
249 lines (237 loc) · 7.43 KB
/
openai_test.go
File metadata and controls
249 lines (237 loc) · 7.43 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package syndicate
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
openai "github.com/sashabaranov/go-openai"
)
// TestMapToOpenAIMessages verifica que se transformen correctamente los mensajes internos a OpenAI.
func TestMapToOpenAIMessages(t *testing.T) {
messages := []Message{
{
Role: "user",
Name: "testUser",
Content: "Hello, world!",
},
}
openaiMsgs := mapToOpenAIMessages(messages)
if len(openaiMsgs) != 1 {
t.Fatalf("se esperaba 1 mensaje, se obtuvo %d", len(openaiMsgs))
}
if openaiMsgs[0].Role != "user" {
t.Errorf("se esperaba role 'user', se obtuvo '%s'", openaiMsgs[0].Role)
}
if openaiMsgs[0].Name != "testUser" {
t.Errorf("se esperaba name 'testUser', se obtuvo '%s'", openaiMsgs[0].Name)
}
if openaiMsgs[0].Content != "Hello, world!" {
t.Errorf("se esperaba content 'Hello, world!', se obtuvo '%s'", openaiMsgs[0].Content)
}
}
// TestMapToOpenAITools verifica la conversión de las definiciones internas de herramienta a las de OpenAI.
func TestMapToOpenAITools(t *testing.T) {
tools := []ToolDefinition{
{
Name: "testTool",
Description: "A test tool",
Parameters: json.RawMessage(`{"type": "object"}`),
},
}
openaiTools := mapToOpenAITools(tools)
if len(openaiTools) != 1 {
t.Fatalf("se esperaba 1 herramienta, se obtuvo %d", len(openaiTools))
}
tool := openaiTools[0]
if tool.Type != openai.ToolTypeFunction {
t.Errorf("se esperaba tool type '%s', se obtuvo '%s'", openai.ToolTypeFunction, tool.Type)
}
if tool.Function == nil {
t.Fatal("se esperaba que Function no fuera nil")
}
if tool.Function.Name != "testTool" {
t.Errorf("se esperaba name 'testTool', se obtuvo '%s'", tool.Function.Name)
}
if tool.Function.Description != "A test tool" {
t.Errorf("se esperaba description 'A test tool', se obtuvo '%s'", tool.Function.Description)
}
params, ok := tool.Function.Parameters.(json.RawMessage)
if !ok {
t.Fatalf("se esperaba json.RawMessage, se obtuvo %T", tool.Function.Parameters)
}
if string(params) != `{"type": "object"}` {
t.Errorf("se esperaba parameters '{\"type\": \"object\"}', se obtuvo '%s'", string(params))
}
if !tool.Function.Strict {
t.Error("se esperaba Strict en true")
}
}
// TestMapFromOpenAIToolCalls verifica que se mapeen correctamente las llamadas a herramientas de OpenAI.
func TestMapFromOpenAIToolCalls(t *testing.T) {
openaiToolCalls := []openai.ToolCall{
{
ID: "call1",
Function: openai.FunctionCall{
Name: "testTool",
Arguments: `{"arg":"value"}`,
},
},
}
toolCalls := mapFromOpenAIToolCalls(openaiToolCalls)
if len(toolCalls) != 1 {
t.Fatalf("se esperaba 1 tool call, se obtuvo %d", len(toolCalls))
}
tc := toolCalls[0]
if tc.ID != "call1" {
t.Errorf("se esperaba ID 'call1', se obtuvo '%s'", tc.ID)
}
if tc.Name != "testTool" {
t.Errorf("se esperaba Name 'testTool', se obtuvo '%s'", tc.Name)
}
if string(tc.Args) != `{"arg":"value"}` {
t.Errorf("se esperaba Args '{\"arg\":\"value\"}', se obtuvo '%s'", string(tc.Args))
}
}
// TestMapFromOpenAIResponse verifica que se mapee correctamente la respuesta de OpenAI a la estructura interna.
func TestMapFromOpenAIResponse(t *testing.T) {
fakeResp := openai.ChatCompletionResponse{
Choices: []openai.ChatCompletionChoice{
{
Message: openai.ChatCompletionMessage{
Role: "assistant",
Name: "assistant",
Content: "test response",
ToolCalls: []openai.ToolCall{
{
ID: "call1",
Function: openai.FunctionCall{
Name: "testTool",
Arguments: `{"arg":"value"}`,
},
},
},
},
FinishReason: openai.FinishReasonStop,
},
},
Usage: openai.Usage{
PromptTokens: 10,
CompletionTokens: 20,
TotalTokens: 30,
},
}
internalResp := mapFromOpenAIResponse(fakeResp)
if len(internalResp.Choices) != 1 {
t.Fatalf("se esperaba 1 choice, se obtuvo %d", len(internalResp.Choices))
}
choice := internalResp.Choices[0]
if choice.Message.Role != "assistant" {
t.Errorf("se esperaba role 'assistant', se obtuvo '%s'", choice.Message.Role)
}
if choice.Message.Name != "assistant" {
t.Errorf("se esperaba name 'assistant', se obtuvo '%s'", choice.Message.Name)
}
if choice.Message.Content != "test response" {
t.Errorf("se esperaba content 'test response', se obtuvo '%s'", choice.Message.Content)
}
if choice.FinishReason != "stop" {
t.Errorf("se esperaba finish reason 'stop', se obtuvo '%s'", choice.FinishReason)
}
if len(choice.Message.ToolCalls) != 1 {
t.Fatalf("se esperaba 1 tool call, se obtuvo %d", len(choice.Message.ToolCalls))
}
tc := choice.Message.ToolCalls[0]
if tc.ID != "call1" {
t.Errorf("se esperaba tool call ID 'call1', se obtuvo '%s'", tc.ID)
}
if tc.Name != "testTool" {
t.Errorf("se esperaba tool call Name 'testTool', se obtuvo '%s'", tc.Name)
}
if string(tc.Args) != `{"arg":"value"}` {
t.Errorf("se esperaba tool call Args '{\"arg\":\"value\"}', se obtuvo '%s'", string(tc.Args))
}
if internalResp.Usage.PromptTokens != 10 || internalResp.Usage.CompletionTokens != 20 || internalResp.Usage.TotalTokens != 30 {
t.Errorf("usage inesperado: %+v", internalResp.Usage)
}
}
// TestCreateChatCompletion simula una llamada a la API de OpenAI mediante un servidor HTTP fake.
func TestCreateChatCompletion(t *testing.T) {
// Servidor fake para simular la API de OpenAI.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Se puede inspeccionar r.Body si se desea verificar el request.
response := `{
"choices": [{
"message": {
"role": "assistant",
"name": "assistant",
"content": "test response",
"tool_calls": []
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 20,
"total_tokens": 30
}
}`
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(response))
}))
defer server.Close()
// Configuramos el cliente OpenAI para usar el servidor fake.
apiKey := "test-api-key"
config := openai.DefaultAzureConfig(apiKey, server.URL)
fakeClient := openai.NewClientWithConfig(config)
// Creamos la instancia de OpenAIClient con el cliente fake.
client := &OpenAIClient{
client: fakeClient,
}
// Preparamos el request.
req := ChatCompletionRequest{
Model: "gpt-3.5-turbo",
Messages: []Message{
{
Role: "user",
Name: "tester",
Content: "Hello",
},
},
Temperature: 0.7,
Tools: []ToolDefinition{
{
Name: "testTool",
Description: "A test tool",
Parameters: json.RawMessage(`{"type": "object"}`),
},
},
ResponseFormat: &ResponseFormat{
Type: "json_schema",
JSONSchema: &JSONSchema{
Name: "TestSchema",
Schema: json.RawMessage(`{"type": "object"}`),
Strict: true,
},
},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := client.CreateChatCompletion(ctx, req)
if err != nil {
t.Fatalf("CreateChatCompletion retornó error: %v", err)
}
// Verificamos que se mapee correctamente la respuesta.
if len(resp.Choices) != 1 {
t.Fatalf("se esperaba 1 choice, se obtuvo %d", len(resp.Choices))
}
choice := resp.Choices[0]
if !strings.EqualFold(choice.Message.Content, "test response") {
t.Errorf("se esperaba message content 'test response', se obtuvo '%s'", choice.Message.Content)
}
if resp.Usage.PromptTokens != 10 || resp.Usage.CompletionTokens != 20 || resp.Usage.TotalTokens != 30 {
t.Errorf("usage inesperado: %+v", resp.Usage)
}
}