chat_api.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. if not response.choices or response.choices[0].message is None:
  24. raise ValueError("LLM returned empty or filtered response")
  25. assistant_res = response.choices[0].message.content
  26. print('[A]: ', assistant_res)
  27. else:
  28. print('[A]: ', end='', flush=True)
  29. assistant_res = ''
  30. for chunk in response:
  31. if not chunk.choices:
  32. continue
  33. delta = chunk.choices[0].delta
  34. if delta is None:
  35. continue
  36. r = getattr(delta, 'reasoning_content', None) or ""
  37. c = delta.content or ""
  38. if r:
  39. print(f'\033[90m{r}\033[0m', end="", flush=True)
  40. if c:
  41. print(c, end="", flush=True)
  42. assistant_res += c
  43. conversation_history.append({"role": "assistant", "content": assistant_res})
  44. print('\n\n')