routes_generate_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. package server
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "strings"
  10. "sync"
  11. "testing"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. "github.com/google/go-cmp/cmp"
  15. "github.com/ollama/ollama/api"
  16. "github.com/ollama/ollama/discover"
  17. "github.com/ollama/ollama/fs/ggml"
  18. "github.com/ollama/ollama/llm"
  19. )
  20. type mockRunner struct {
  21. llm.LlamaServer
  22. // CompletionRequest is only valid until the next call to Completion
  23. llm.CompletionRequest
  24. llm.CompletionResponse
  25. CompletionFn func(context.Context, llm.CompletionRequest, func(llm.CompletionResponse)) error
  26. }
  27. func (m *mockRunner) Completion(ctx context.Context, r llm.CompletionRequest, fn func(r llm.CompletionResponse)) error {
  28. m.CompletionRequest = r
  29. if m.CompletionFn != nil {
  30. return m.CompletionFn(ctx, r, fn)
  31. }
  32. fn(m.CompletionResponse)
  33. return nil
  34. }
  35. func (mockRunner) Tokenize(_ context.Context, s string) (tokens []int, err error) {
  36. for range strings.Fields(s) {
  37. tokens = append(tokens, len(tokens))
  38. }
  39. return
  40. }
  41. func newMockServer(mock *mockRunner) func(discover.GpuInfoList, string, *ggml.GGML, []string, []string, api.Options, int) (llm.LlamaServer, error) {
  42. return func(gpus discover.GpuInfoList, model string, f *ggml.GGML, projectors, system []string, opts api.Options, numParallel int) (llm.LlamaServer, error) {
  43. return mock, nil
  44. }
  45. }
  46. func TestGenerateChat(t *testing.T) {
  47. gin.SetMode(gin.TestMode)
  48. mock := mockRunner{
  49. CompletionResponse: llm.CompletionResponse{
  50. Done: true,
  51. DoneReason: "stop",
  52. PromptEvalCount: 1,
  53. PromptEvalDuration: 1,
  54. EvalCount: 1,
  55. EvalDuration: 1,
  56. },
  57. }
  58. s := Server{
  59. sched: &Scheduler{
  60. pendingReqCh: make(chan *LlmRequest, 1),
  61. finishedReqCh: make(chan *LlmRequest, 1),
  62. expiredCh: make(chan *runnerRef, 1),
  63. unloadedCh: make(chan any, 1),
  64. loaded: make(map[string]*runnerRef),
  65. newServerFn: newMockServer(&mock),
  66. getGpuFn: discover.GetGPUInfo,
  67. getCpuFn: discover.GetCPUInfo,
  68. reschedDelay: 250 * time.Millisecond,
  69. loadFn: func(req *LlmRequest, f *ggml.GGML, gpus discover.GpuInfoList, numParallel int) {
  70. // add small delay to simulate loading
  71. time.Sleep(time.Millisecond)
  72. req.successCh <- &runnerRef{
  73. llama: &mock,
  74. }
  75. },
  76. },
  77. }
  78. go s.sched.Run(context.TODO())
  79. w := createRequest(t, s.CreateHandler, api.CreateRequest{
  80. Model: "test",
  81. Modelfile: fmt.Sprintf(`FROM %s
  82. TEMPLATE """
  83. {{- if .Tools }}
  84. {{ .Tools }}
  85. {{ end }}
  86. {{- range .Messages }}
  87. {{- .Role }}: {{ .Content }}
  88. {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}}
  89. {{- end }}
  90. {{ end }}"""
  91. `, createBinFile(t, ggml.KV{
  92. "general.architecture": "llama",
  93. "llama.block_count": uint32(1),
  94. "llama.context_length": uint32(8192),
  95. "llama.embedding_length": uint32(4096),
  96. "llama.attention.head_count": uint32(32),
  97. "llama.attention.head_count_kv": uint32(8),
  98. "tokenizer.ggml.tokens": []string{""},
  99. "tokenizer.ggml.scores": []float32{0},
  100. "tokenizer.ggml.token_type": []int32{0},
  101. }, []ggml.Tensor{
  102. {Name: "token_embd.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  103. {Name: "blk.0.attn_norm.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  104. {Name: "blk.0.ffn_down.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  105. {Name: "blk.0.ffn_gate.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  106. {Name: "blk.0.ffn_up.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  107. {Name: "blk.0.ffn_norm.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  108. {Name: "blk.0.attn_k.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  109. {Name: "blk.0.attn_output.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  110. {Name: "blk.0.attn_q.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  111. {Name: "blk.0.attn_v.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  112. {Name: "output.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  113. })),
  114. Stream: &stream,
  115. })
  116. if w.Code != http.StatusOK {
  117. t.Fatalf("expected status 200, got %d", w.Code)
  118. }
  119. t.Run("missing body", func(t *testing.T) {
  120. w := createRequest(t, s.ChatHandler, nil)
  121. if w.Code != http.StatusBadRequest {
  122. t.Errorf("expected status 400, got %d", w.Code)
  123. }
  124. if diff := cmp.Diff(w.Body.String(), `{"error":"model is required"}`); diff != "" {
  125. t.Errorf("mismatch (-got +want):\n%s", diff)
  126. }
  127. })
  128. t.Run("missing model", func(t *testing.T) {
  129. w := createRequest(t, s.ChatHandler, api.ChatRequest{})
  130. if w.Code != http.StatusBadRequest {
  131. t.Errorf("expected status 400, got %d", w.Code)
  132. }
  133. if diff := cmp.Diff(w.Body.String(), `{"error":"model is required"}`); diff != "" {
  134. t.Errorf("mismatch (-got +want):\n%s", diff)
  135. }
  136. })
  137. t.Run("missing capabilities chat", func(t *testing.T) {
  138. w := createRequest(t, s.CreateHandler, api.CreateRequest{
  139. Model: "bert",
  140. Modelfile: fmt.Sprintf("FROM %s", createBinFile(t, ggml.KV{
  141. "general.architecture": "bert",
  142. "bert.pooling_type": uint32(0),
  143. }, []ggml.Tensor{})),
  144. Stream: &stream,
  145. })
  146. if w.Code != http.StatusOK {
  147. t.Fatalf("expected status 200, got %d", w.Code)
  148. }
  149. w = createRequest(t, s.ChatHandler, api.ChatRequest{
  150. Model: "bert",
  151. })
  152. if w.Code != http.StatusBadRequest {
  153. t.Errorf("expected status 400, got %d", w.Code)
  154. }
  155. if diff := cmp.Diff(w.Body.String(), `{"error":"\"bert\" does not support chat"}`); diff != "" {
  156. t.Errorf("mismatch (-got +want):\n%s", diff)
  157. }
  158. })
  159. t.Run("load model", func(t *testing.T) {
  160. w := createRequest(t, s.ChatHandler, api.ChatRequest{
  161. Model: "test",
  162. })
  163. if w.Code != http.StatusOK {
  164. t.Errorf("expected status 200, got %d", w.Code)
  165. }
  166. var actual api.ChatResponse
  167. if err := json.NewDecoder(w.Body).Decode(&actual); err != nil {
  168. t.Fatal(err)
  169. }
  170. if actual.Model != "test" {
  171. t.Errorf("expected model test, got %s", actual.Model)
  172. }
  173. if !actual.Done {
  174. t.Errorf("expected done true, got false")
  175. }
  176. if actual.DoneReason != "load" {
  177. t.Errorf("expected done reason load, got %s", actual.DoneReason)
  178. }
  179. })
  180. checkChatResponse := func(t *testing.T, body io.Reader, model, content string) {
  181. t.Helper()
  182. var actual api.ChatResponse
  183. if err := json.NewDecoder(body).Decode(&actual); err != nil {
  184. t.Fatal(err)
  185. }
  186. if actual.Model != model {
  187. t.Errorf("expected model test, got %s", actual.Model)
  188. }
  189. if !actual.Done {
  190. t.Errorf("expected done false, got true")
  191. }
  192. if actual.DoneReason != "stop" {
  193. t.Errorf("expected done reason stop, got %s", actual.DoneReason)
  194. }
  195. if diff := cmp.Diff(actual.Message, api.Message{
  196. Role: "assistant",
  197. Content: content,
  198. }); diff != "" {
  199. t.Errorf("mismatch (-got +want):\n%s", diff)
  200. }
  201. if actual.PromptEvalCount == 0 {
  202. t.Errorf("expected prompt eval count > 0, got 0")
  203. }
  204. if actual.PromptEvalDuration == 0 {
  205. t.Errorf("expected prompt eval duration > 0, got 0")
  206. }
  207. if actual.EvalCount == 0 {
  208. t.Errorf("expected eval count > 0, got 0")
  209. }
  210. if actual.EvalDuration == 0 {
  211. t.Errorf("expected eval duration > 0, got 0")
  212. }
  213. if actual.LoadDuration == 0 {
  214. t.Errorf("expected load duration > 0, got 0")
  215. }
  216. if actual.TotalDuration == 0 {
  217. t.Errorf("expected total duration > 0, got 0")
  218. }
  219. }
  220. mock.CompletionResponse.Content = "Hi!"
  221. t.Run("messages", func(t *testing.T) {
  222. w := createRequest(t, s.ChatHandler, api.ChatRequest{
  223. Model: "test",
  224. Messages: []api.Message{
  225. {Role: "user", Content: "Hello!"},
  226. },
  227. Stream: &stream,
  228. })
  229. if w.Code != http.StatusOK {
  230. t.Errorf("expected status 200, got %d", w.Code)
  231. }
  232. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "user: Hello!\n"); diff != "" {
  233. t.Errorf("mismatch (-got +want):\n%s", diff)
  234. }
  235. checkChatResponse(t, w.Body, "test", "Hi!")
  236. })
  237. w = createRequest(t, s.CreateHandler, api.CreateRequest{
  238. Model: "test-system",
  239. Modelfile: "FROM test\nSYSTEM You are a helpful assistant.",
  240. })
  241. if w.Code != http.StatusOK {
  242. t.Fatalf("expected status 200, got %d", w.Code)
  243. }
  244. t.Run("messages with model system", func(t *testing.T) {
  245. w := createRequest(t, s.ChatHandler, api.ChatRequest{
  246. Model: "test-system",
  247. Messages: []api.Message{
  248. {Role: "user", Content: "Hello!"},
  249. },
  250. Stream: &stream,
  251. })
  252. if w.Code != http.StatusOK {
  253. t.Errorf("expected status 200, got %d", w.Code)
  254. }
  255. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "system: You are a helpful assistant.\nuser: Hello!\n"); diff != "" {
  256. t.Errorf("mismatch (-got +want):\n%s", diff)
  257. }
  258. checkChatResponse(t, w.Body, "test-system", "Hi!")
  259. })
  260. mock.CompletionResponse.Content = "Abra kadabra!"
  261. t.Run("messages with system", func(t *testing.T) {
  262. w := createRequest(t, s.ChatHandler, api.ChatRequest{
  263. Model: "test-system",
  264. Messages: []api.Message{
  265. {Role: "system", Content: "You can perform magic tricks."},
  266. {Role: "user", Content: "Hello!"},
  267. },
  268. Stream: &stream,
  269. })
  270. if w.Code != http.StatusOK {
  271. t.Errorf("expected status 200, got %d", w.Code)
  272. }
  273. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "system: You can perform magic tricks.\nuser: Hello!\n"); diff != "" {
  274. t.Errorf("mismatch (-got +want):\n%s", diff)
  275. }
  276. checkChatResponse(t, w.Body, "test-system", "Abra kadabra!")
  277. })
  278. t.Run("messages with interleaved system", func(t *testing.T) {
  279. w := createRequest(t, s.ChatHandler, api.ChatRequest{
  280. Model: "test-system",
  281. Messages: []api.Message{
  282. {Role: "user", Content: "Hello!"},
  283. {Role: "assistant", Content: "I can help you with that."},
  284. {Role: "system", Content: "You can perform magic tricks."},
  285. {Role: "user", Content: "Help me write tests."},
  286. },
  287. Stream: &stream,
  288. })
  289. if w.Code != http.StatusOK {
  290. t.Errorf("expected status 200, got %d", w.Code)
  291. }
  292. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "system: You are a helpful assistant.\nuser: Hello!\nassistant: I can help you with that.\nsystem: You can perform magic tricks.\nuser: Help me write tests.\n"); diff != "" {
  293. t.Errorf("mismatch (-got +want):\n%s", diff)
  294. }
  295. checkChatResponse(t, w.Body, "test-system", "Abra kadabra!")
  296. })
  297. t.Run("messages with tools (non-streaming)", func(t *testing.T) {
  298. if w.Code != http.StatusOK {
  299. t.Fatalf("failed to create test-system model: %d", w.Code)
  300. }
  301. tools := []api.Tool{
  302. {
  303. Type: "function",
  304. Function: api.ToolFunction{
  305. Name: "get_weather",
  306. Description: "Get the current weather",
  307. Parameters: struct {
  308. Type string `json:"type"`
  309. Required []string `json:"required"`
  310. Properties map[string]struct {
  311. Type string `json:"type"`
  312. Description string `json:"description"`
  313. Enum []string `json:"enum,omitempty"`
  314. } `json:"properties"`
  315. }{
  316. Type: "object",
  317. Required: []string{"location"},
  318. Properties: map[string]struct {
  319. Type string `json:"type"`
  320. Description string `json:"description"`
  321. Enum []string `json:"enum,omitempty"`
  322. }{
  323. "location": {
  324. Type: "string",
  325. Description: "The city and state",
  326. },
  327. "unit": {
  328. Type: "string",
  329. Enum: []string{"celsius", "fahrenheit"},
  330. },
  331. },
  332. },
  333. },
  334. },
  335. }
  336. mock.CompletionResponse = llm.CompletionResponse{
  337. Content: `{"name":"get_weather","arguments":{"location":"Seattle, WA","unit":"celsius"}}`,
  338. Done: true,
  339. DoneReason: "done",
  340. PromptEvalCount: 1,
  341. PromptEvalDuration: 1,
  342. EvalCount: 1,
  343. EvalDuration: 1,
  344. }
  345. streamRequest := true
  346. w := createRequest(t, s.ChatHandler, api.ChatRequest{
  347. Model: "test-system",
  348. Messages: []api.Message{
  349. {Role: "user", Content: "What's the weather in Seattle?"},
  350. },
  351. Tools: tools,
  352. Stream: &streamRequest,
  353. })
  354. if w.Code != http.StatusOK {
  355. var errResp struct {
  356. Error string `json:"error"`
  357. }
  358. if err := json.NewDecoder(w.Body).Decode(&errResp); err != nil {
  359. t.Logf("Failed to decode error response: %v", err)
  360. } else {
  361. t.Logf("Error response: %s", errResp.Error)
  362. }
  363. }
  364. if w.Code != http.StatusOK {
  365. t.Errorf("expected status 200, got %d", w.Code)
  366. }
  367. var resp api.ChatResponse
  368. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  369. t.Fatal(err)
  370. }
  371. if resp.Message.ToolCalls == nil {
  372. t.Error("expected tool calls, got nil")
  373. }
  374. expectedToolCall := api.ToolCall{
  375. Function: api.ToolCallFunction{
  376. Name: "get_weather",
  377. Arguments: api.ToolCallFunctionArguments{
  378. "location": "Seattle, WA",
  379. "unit": "celsius",
  380. },
  381. },
  382. }
  383. if diff := cmp.Diff(resp.Message.ToolCalls[0], expectedToolCall); diff != "" {
  384. t.Errorf("tool call mismatch (-got +want):\n%s", diff)
  385. }
  386. })
  387. t.Run("messages with tools (streaming)", func(t *testing.T) {
  388. tools := []api.Tool{
  389. {
  390. Type: "function",
  391. Function: api.ToolFunction{
  392. Name: "get_weather",
  393. Description: "Get the current weather",
  394. Parameters: struct {
  395. Type string `json:"type"`
  396. Required []string `json:"required"`
  397. Properties map[string]struct {
  398. Type string `json:"type"`
  399. Description string `json:"description"`
  400. Enum []string `json:"enum,omitempty"`
  401. } `json:"properties"`
  402. }{
  403. Type: "object",
  404. Required: []string{"location"},
  405. Properties: map[string]struct {
  406. Type string `json:"type"`
  407. Description string `json:"description"`
  408. Enum []string `json:"enum,omitempty"`
  409. }{
  410. "location": {
  411. Type: "string",
  412. Description: "The city and state",
  413. },
  414. "unit": {
  415. Type: "string",
  416. Enum: []string{"celsius", "fahrenheit"},
  417. },
  418. },
  419. },
  420. },
  421. },
  422. }
  423. // Simulate streaming response with multiple chunks
  424. var wg sync.WaitGroup
  425. wg.Add(1)
  426. mock.CompletionFn = func(ctx context.Context, r llm.CompletionRequest, fn func(r llm.CompletionResponse)) error {
  427. defer wg.Done()
  428. // Send chunks with small delays to simulate streaming
  429. responses := []llm.CompletionResponse{
  430. {
  431. Content: `{"name":"get_`,
  432. Done: false,
  433. PromptEvalCount: 1,
  434. PromptEvalDuration: 1,
  435. },
  436. {
  437. Content: `weather","arguments":{"location":"Seattle`,
  438. Done: false,
  439. PromptEvalCount: 2,
  440. PromptEvalDuration: 1,
  441. },
  442. {
  443. Content: `, WA","unit":"celsius"}}`,
  444. Done: true,
  445. DoneReason: "tool_call",
  446. PromptEvalCount: 3,
  447. PromptEvalDuration: 1,
  448. },
  449. }
  450. for _, resp := range responses {
  451. select {
  452. case <-ctx.Done():
  453. return ctx.Err()
  454. default:
  455. fn(resp)
  456. time.Sleep(10 * time.Millisecond) // Small delay between chunks
  457. }
  458. }
  459. return nil
  460. }
  461. w := createRequest(t, s.ChatHandler, api.ChatRequest{
  462. Model: "test-system",
  463. Messages: []api.Message{
  464. {Role: "user", Content: "What's the weather in Seattle?"},
  465. },
  466. Tools: tools,
  467. Stream: &stream,
  468. })
  469. wg.Wait()
  470. if w.Code != http.StatusOK {
  471. t.Errorf("expected status 200, got %d", w.Code)
  472. }
  473. // Read and validate the streamed responses
  474. decoder := json.NewDecoder(w.Body)
  475. var finalToolCall api.ToolCall
  476. for {
  477. var resp api.ChatResponse
  478. if err := decoder.Decode(&resp); err == io.EOF {
  479. break
  480. } else if err != nil {
  481. t.Fatal(err)
  482. }
  483. if resp.Done {
  484. if len(resp.Message.ToolCalls) != 1 {
  485. t.Errorf("expected 1 tool call in final response, got %d", len(resp.Message.ToolCalls))
  486. }
  487. finalToolCall = resp.Message.ToolCalls[0]
  488. }
  489. }
  490. expectedToolCall := api.ToolCall{
  491. Function: api.ToolCallFunction{
  492. Name: "get_weather",
  493. Arguments: api.ToolCallFunctionArguments{
  494. "location": "Seattle, WA",
  495. "unit": "celsius",
  496. },
  497. },
  498. }
  499. if diff := cmp.Diff(finalToolCall, expectedToolCall); diff != "" {
  500. t.Errorf("final tool call mismatch (-got +want):\n%s", diff)
  501. }
  502. })
  503. }
  504. func TestGenerate(t *testing.T) {
  505. gin.SetMode(gin.TestMode)
  506. mock := mockRunner{
  507. CompletionResponse: llm.CompletionResponse{
  508. Done: true,
  509. DoneReason: "stop",
  510. PromptEvalCount: 1,
  511. PromptEvalDuration: 1,
  512. EvalCount: 1,
  513. EvalDuration: 1,
  514. },
  515. }
  516. s := Server{
  517. sched: &Scheduler{
  518. pendingReqCh: make(chan *LlmRequest, 1),
  519. finishedReqCh: make(chan *LlmRequest, 1),
  520. expiredCh: make(chan *runnerRef, 1),
  521. unloadedCh: make(chan any, 1),
  522. loaded: make(map[string]*runnerRef),
  523. newServerFn: newMockServer(&mock),
  524. getGpuFn: discover.GetGPUInfo,
  525. getCpuFn: discover.GetCPUInfo,
  526. reschedDelay: 250 * time.Millisecond,
  527. loadFn: func(req *LlmRequest, _ *ggml.GGML, gpus discover.GpuInfoList, numParallel int) {
  528. // add small delay to simulate loading
  529. time.Sleep(time.Millisecond)
  530. req.successCh <- &runnerRef{
  531. llama: &mock,
  532. }
  533. },
  534. },
  535. }
  536. go s.sched.Run(context.TODO())
  537. w := createRequest(t, s.CreateHandler, api.CreateRequest{
  538. Model: "test",
  539. Modelfile: fmt.Sprintf(`FROM %s
  540. TEMPLATE """
  541. {{- if .System }}System: {{ .System }} {{ end }}
  542. {{- if .Prompt }}User: {{ .Prompt }} {{ end }}
  543. {{- if .Response }}Assistant: {{ .Response }} {{ end }}"""
  544. `, createBinFile(t, ggml.KV{
  545. "general.architecture": "llama",
  546. "llama.block_count": uint32(1),
  547. "llama.context_length": uint32(8192),
  548. "llama.embedding_length": uint32(4096),
  549. "llama.attention.head_count": uint32(32),
  550. "llama.attention.head_count_kv": uint32(8),
  551. "tokenizer.ggml.tokens": []string{""},
  552. "tokenizer.ggml.scores": []float32{0},
  553. "tokenizer.ggml.token_type": []int32{0},
  554. }, []ggml.Tensor{
  555. {Name: "token_embd.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  556. {Name: "blk.0.attn_norm.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  557. {Name: "blk.0.ffn_down.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  558. {Name: "blk.0.ffn_gate.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  559. {Name: "blk.0.ffn_up.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  560. {Name: "blk.0.ffn_norm.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  561. {Name: "blk.0.attn_k.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  562. {Name: "blk.0.attn_output.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  563. {Name: "blk.0.attn_q.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  564. {Name: "blk.0.attn_v.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  565. {Name: "output.weight", Shape: []uint64{1}, WriterTo: bytes.NewReader(make([]byte, 4))},
  566. })),
  567. Stream: &stream,
  568. })
  569. if w.Code != http.StatusOK {
  570. t.Fatalf("expected status 200, got %d", w.Code)
  571. }
  572. t.Run("missing body", func(t *testing.T) {
  573. w := createRequest(t, s.GenerateHandler, nil)
  574. if w.Code != http.StatusNotFound {
  575. t.Errorf("expected status 404, got %d", w.Code)
  576. }
  577. if diff := cmp.Diff(w.Body.String(), `{"error":"model '' not found"}`); diff != "" {
  578. t.Errorf("mismatch (-got +want):\n%s", diff)
  579. }
  580. })
  581. t.Run("missing model", func(t *testing.T) {
  582. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{})
  583. if w.Code != http.StatusNotFound {
  584. t.Errorf("expected status 404, got %d", w.Code)
  585. }
  586. if diff := cmp.Diff(w.Body.String(), `{"error":"model '' not found"}`); diff != "" {
  587. t.Errorf("mismatch (-got +want):\n%s", diff)
  588. }
  589. })
  590. t.Run("missing capabilities generate", func(t *testing.T) {
  591. w := createRequest(t, s.CreateHandler, api.CreateRequest{
  592. Model: "bert",
  593. Modelfile: fmt.Sprintf("FROM %s", createBinFile(t, ggml.KV{
  594. "general.architecture": "bert",
  595. "bert.pooling_type": uint32(0),
  596. }, []ggml.Tensor{})),
  597. Stream: &stream,
  598. })
  599. if w.Code != http.StatusOK {
  600. t.Fatalf("expected status 200, got %d", w.Code)
  601. }
  602. w = createRequest(t, s.GenerateHandler, api.GenerateRequest{
  603. Model: "bert",
  604. })
  605. if w.Code != http.StatusBadRequest {
  606. t.Errorf("expected status 400, got %d", w.Code)
  607. }
  608. if diff := cmp.Diff(w.Body.String(), `{"error":"\"bert\" does not support generate"}`); diff != "" {
  609. t.Errorf("mismatch (-got +want):\n%s", diff)
  610. }
  611. })
  612. t.Run("missing capabilities suffix", func(t *testing.T) {
  613. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
  614. Model: "test",
  615. Prompt: "def add(",
  616. Suffix: " return c",
  617. })
  618. if w.Code != http.StatusBadRequest {
  619. t.Errorf("expected status 400, got %d", w.Code)
  620. }
  621. if diff := cmp.Diff(w.Body.String(), `{"error":"test does not support insert"}`); diff != "" {
  622. t.Errorf("mismatch (-got +want):\n%s", diff)
  623. }
  624. })
  625. t.Run("load model", func(t *testing.T) {
  626. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
  627. Model: "test",
  628. })
  629. if w.Code != http.StatusOK {
  630. t.Errorf("expected status 200, got %d", w.Code)
  631. }
  632. var actual api.GenerateResponse
  633. if err := json.NewDecoder(w.Body).Decode(&actual); err != nil {
  634. t.Fatal(err)
  635. }
  636. if actual.Model != "test" {
  637. t.Errorf("expected model test, got %s", actual.Model)
  638. }
  639. if !actual.Done {
  640. t.Errorf("expected done true, got false")
  641. }
  642. if actual.DoneReason != "load" {
  643. t.Errorf("expected done reason load, got %s", actual.DoneReason)
  644. }
  645. })
  646. checkGenerateResponse := func(t *testing.T, body io.Reader, model, content string) {
  647. t.Helper()
  648. var actual api.GenerateResponse
  649. if err := json.NewDecoder(body).Decode(&actual); err != nil {
  650. t.Fatal(err)
  651. }
  652. if actual.Model != model {
  653. t.Errorf("expected model test, got %s", actual.Model)
  654. }
  655. if !actual.Done {
  656. t.Errorf("expected done false, got true")
  657. }
  658. if actual.DoneReason != "stop" {
  659. t.Errorf("expected done reason stop, got %s", actual.DoneReason)
  660. }
  661. if actual.Response != content {
  662. t.Errorf("expected response %s, got %s", content, actual.Response)
  663. }
  664. if actual.Context == nil {
  665. t.Errorf("expected context not nil")
  666. }
  667. if actual.PromptEvalCount == 0 {
  668. t.Errorf("expected prompt eval count > 0, got 0")
  669. }
  670. if actual.PromptEvalDuration == 0 {
  671. t.Errorf("expected prompt eval duration > 0, got 0")
  672. }
  673. if actual.EvalCount == 0 {
  674. t.Errorf("expected eval count > 0, got 0")
  675. }
  676. if actual.EvalDuration == 0 {
  677. t.Errorf("expected eval duration > 0, got 0")
  678. }
  679. if actual.LoadDuration == 0 {
  680. t.Errorf("expected load duration > 0, got 0")
  681. }
  682. if actual.TotalDuration == 0 {
  683. t.Errorf("expected total duration > 0, got 0")
  684. }
  685. }
  686. mock.CompletionResponse.Content = "Hi!"
  687. t.Run("prompt", func(t *testing.T) {
  688. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
  689. Model: "test",
  690. Prompt: "Hello!",
  691. Stream: &stream,
  692. })
  693. if w.Code != http.StatusOK {
  694. t.Errorf("expected status 200, got %d", w.Code)
  695. }
  696. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "User: Hello! "); diff != "" {
  697. t.Errorf("mismatch (-got +want):\n%s", diff)
  698. }
  699. checkGenerateResponse(t, w.Body, "test", "Hi!")
  700. })
  701. w = createRequest(t, s.CreateHandler, api.CreateRequest{
  702. Model: "test-system",
  703. Modelfile: "FROM test\nSYSTEM You are a helpful assistant.",
  704. })
  705. if w.Code != http.StatusOK {
  706. t.Fatalf("expected status 200, got %d", w.Code)
  707. }
  708. t.Run("prompt with model system", func(t *testing.T) {
  709. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
  710. Model: "test-system",
  711. Prompt: "Hello!",
  712. Stream: &stream,
  713. })
  714. if w.Code != http.StatusOK {
  715. t.Errorf("expected status 200, got %d", w.Code)
  716. }
  717. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "System: You are a helpful assistant. User: Hello! "); diff != "" {
  718. t.Errorf("mismatch (-got +want):\n%s", diff)
  719. }
  720. checkGenerateResponse(t, w.Body, "test-system", "Hi!")
  721. })
  722. mock.CompletionResponse.Content = "Abra kadabra!"
  723. t.Run("prompt with system", func(t *testing.T) {
  724. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
  725. Model: "test-system",
  726. Prompt: "Hello!",
  727. System: "You can perform magic tricks.",
  728. Stream: &stream,
  729. })
  730. if w.Code != http.StatusOK {
  731. t.Errorf("expected status 200, got %d", w.Code)
  732. }
  733. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "System: You can perform magic tricks. User: Hello! "); diff != "" {
  734. t.Errorf("mismatch (-got +want):\n%s", diff)
  735. }
  736. checkGenerateResponse(t, w.Body, "test-system", "Abra kadabra!")
  737. })
  738. t.Run("prompt with template", func(t *testing.T) {
  739. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
  740. Model: "test-system",
  741. Prompt: "Help me write tests.",
  742. System: "You can perform magic tricks.",
  743. Template: `{{- if .System }}{{ .System }} {{ end }}
  744. {{- if .Prompt }}### USER {{ .Prompt }} {{ end }}
  745. {{- if .Response }}### ASSISTANT {{ .Response }} {{ end }}`,
  746. Stream: &stream,
  747. })
  748. if w.Code != http.StatusOK {
  749. t.Errorf("expected status 200, got %d", w.Code)
  750. }
  751. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "You can perform magic tricks. ### USER Help me write tests. "); diff != "" {
  752. t.Errorf("mismatch (-got +want):\n%s", diff)
  753. }
  754. checkGenerateResponse(t, w.Body, "test-system", "Abra kadabra!")
  755. })
  756. w = createRequest(t, s.CreateHandler, api.CreateRequest{
  757. Model: "test-suffix",
  758. Modelfile: `FROM test
  759. TEMPLATE """{{- if .Suffix }}<PRE> {{ .Prompt }} <SUF>{{ .Suffix }} <MID>
  760. {{- else }}{{ .Prompt }}
  761. {{- end }}"""`,
  762. })
  763. if w.Code != http.StatusOK {
  764. t.Fatalf("expected status 200, got %d", w.Code)
  765. }
  766. t.Run("prompt with suffix", func(t *testing.T) {
  767. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
  768. Model: "test-suffix",
  769. Prompt: "def add(",
  770. Suffix: " return c",
  771. })
  772. if w.Code != http.StatusOK {
  773. t.Errorf("expected status 200, got %d", w.Code)
  774. }
  775. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "<PRE> def add( <SUF> return c <MID>"); diff != "" {
  776. t.Errorf("mismatch (-got +want):\n%s", diff)
  777. }
  778. })
  779. t.Run("prompt without suffix", func(t *testing.T) {
  780. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
  781. Model: "test-suffix",
  782. Prompt: "def add(",
  783. })
  784. if w.Code != http.StatusOK {
  785. t.Errorf("expected status 200, got %d", w.Code)
  786. }
  787. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "def add("); diff != "" {
  788. t.Errorf("mismatch (-got +want):\n%s", diff)
  789. }
  790. })
  791. t.Run("raw", func(t *testing.T) {
  792. w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
  793. Model: "test-system",
  794. Prompt: "Help me write tests.",
  795. Raw: true,
  796. Stream: &stream,
  797. })
  798. if w.Code != http.StatusOK {
  799. t.Errorf("expected status 200, got %d", w.Code)
  800. }
  801. if diff := cmp.Diff(mock.CompletionRequest.Prompt, "Help me write tests."); diff != "" {
  802. t.Errorf("mismatch (-got +want):\n%s", diff)
  803. }
  804. })
  805. }