chat_openai_api.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. from openai import OpenAI
  2. client = OpenAI(
  3. api_key="ollama",
  4. base_url="http://127.0.0.1:8998/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",
  15. messages=conversation_history[-(history_messages_num or 1):],
  16. stream=stream,
  17. temperature=0.7,
  18. max_tokens=2048,
  19. top_p=0.9
  20. )
  21. if not stream:
  22. assistant_res = response.choices[0].message.content
  23. print('[A]: ', assistant_res)
  24. else:
  25. print('[A]: ', end='')
  26. assistant_res = ''
  27. for chunk in response:
  28. print(chunk.choices[0].delta.content or "", end="")
  29. assistant_res += chunk.choices[0].delta.content or ""
  30. conversation_history.append({"role": "assistant", "content": assistant_res})
  31. print('\n\n')