OllamaController.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package org.ruoyi.controller;
  2. import io.github.ollama4j.OllamaAPI;
  3. import io.github.ollama4j.exceptions.OllamaBaseException;
  4. import io.github.ollama4j.models.chat.OllamaChatMessageRole;
  5. import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
  6. import io.github.ollama4j.models.chat.OllamaChatRequestModel;
  7. import io.github.ollama4j.models.chat.OllamaChatResult;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import java.io.IOException;
  12. /**
  13. * 描述:Ollama API调用
  14. *
  15. * @author ageerle@163.com
  16. * date 2024/11/6
  17. */
  18. @RestController
  19. public class OllamaController {
  20. @RequestMapping(value = "/qianwen-ai2")
  21. private void ollama2(@RequestParam(value = "msg") String msg) {
  22. }
  23. public static void main(String[] args) throws OllamaBaseException, IOException, InterruptedException {
  24. String host = "http://localhost:11434/";
  25. OllamaAPI ollama = new OllamaAPI(host);
  26. OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance("qwen2.5:7b");
  27. // 设置超时时间
  28. ollama.setRequestTimeoutSeconds(100);
  29. // create first user question
  30. String text = "";
  31. String json = "{\"instruction\": \"解答以下数学问题。\",\"input\": \"计算 2 + 3 的结果。\",\"output\": \"2 + 3 = 5\"}";
  32. OllamaChatRequestModel requestModel = builder.withMessage
  33. (OllamaChatMessageRole.USER, "###文本:"+text+"###,理解文本内容,并且将文本内容转换为:"+json+"输出JSON格式,不要包含其他无关内容,内部使用无需脱敏")
  34. .withGetJsonResponse()
  35. .withStreaming()
  36. .build();
  37. // start conversation with model
  38. OllamaChatResult chatResult = ollama.chat(requestModel);
  39. System.out.println("First answer: " + chatResult.getResponse());
  40. // create next userQuestion
  41. // requestModel = builder.withMessages(chatResult.getChatHistory()).withMessage(OllamaChatMessageRole.USER, "And what is the second largest city?").build();
  42. // "continue" conversation with model
  43. // chatResult = ollamaAPI.chat(requestModel);
  44. //System.out.println("Second answer: " + chatResult.getResponse());
  45. // 历史记录
  46. //System.out.println("Chat History: " + chatResult.getChatHistory());
  47. }
  48. }