chat_api.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from openai import OpenAI
  2. client = OpenAI(
  3. api_key="sk-123",
  4. base_url="http://localhost:11434/v1"
  5. )
  6. stream = True
  7. conversation_history_origin = []
  8. conversation_history = conversation_history_origin.copy()
  9. history_messages_num = 0 # 必须设置为偶数(Q+A),为0则不携带历史对话
  10. while True:
  11. query = input('[Q]: ')
  12. conversation_history.append({"role": "user", "content": query})
  13. response = client.chat.completions.create(
  14. model="minimind-local:latest",
  15. messages=conversation_history[-(history_messages_num or 1):],
  16. stream=stream,
  17. temperature=0.8,
  18. max_tokens=2048,
  19. top_p=0.8,
  20. extra_body={"chat_template_kwargs": {"open_thinking": True}, "reasoning_effort": "medium"} # 思考开关
  21. )
  22. if not stream:
  23. assistant_res = response.choices[0].message.content
  24. print('[A]: ', assistant_res)
  25. else:
  26. print('[A]: ', end='', flush=True)
  27. assistant_res = ''
  28. for chunk in response:
  29. delta = chunk.choices[0].delta
  30. r = getattr(delta, 'reasoning_content', None) or ""
  31. c = delta.content or ""
  32. if r:
  33. print(f'\033[90m{r}\033[0m', end="", flush=True)
  34. if c:
  35. print(c, end="", flush=True)
  36. assistant_res += c
  37. conversation_history.append({"role": "assistant", "content": assistant_res})
  38. print('\n\n')