tutorial_utils.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import openai
  2. import reflex as rx
  3. class ChatappState(rx.State):
  4. # The current question being asked.
  5. question: str
  6. # Keep track of the chat history as a list of (question, answer) tuples.
  7. chat_history: list[tuple[str, str]]
  8. def answer(self):
  9. # Our chatbot is not very smart right now...
  10. answer = "I don't know!"
  11. self.chat_history.append((self.question, answer))
  12. def answer2(self):
  13. # Our chatbot is not very smart right now...
  14. answer = "I don't know!"
  15. self.chat_history.append((self.question, answer))
  16. # Clear the question input.
  17. self.question = ""
  18. async def answer3(self):
  19. import asyncio
  20. # Our chatbot is not very smart right now...
  21. answer = "I don't know!"
  22. self.chat_history.append((self.question, ""))
  23. # Clear the question input.
  24. self.question = ""
  25. # Yield here to clear the frontend input before continuing.
  26. yield
  27. for i in range(len(answer)):
  28. await asyncio.sleep(0.1)
  29. self.chat_history[-1] = (self.chat_history[-1][0], answer[: i + 1])
  30. yield
  31. def answer4(self):
  32. # Our chatbot has some brains now!
  33. session = openai.ChatCompletion.create(
  34. model="gpt-3.5-turbo",
  35. messages=[{"role": "user", "content": self.question}],
  36. stop=None,
  37. temperature=0.7,
  38. stream=True,
  39. )
  40. # Add to the answer as the chatbot responds.
  41. answer = ""
  42. self.chat_history.append((self.question, answer))
  43. # Clear the question input.
  44. self.question = ""
  45. # Yield here to clear the frontend input before continuing.
  46. yield
  47. for item in session:
  48. if hasattr(item.choices[0].delta, "content"):
  49. answer += item.choices[0].delta.content
  50. self.chat_history[-1] = (self.chat_history[-1][0], answer)
  51. yield