chat-calculator.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. # -----------------------------------------------------------------------------------------
  12. # To execute this script, make sure that the taipy-gui package is installed in your
  13. # Python environment and run:
  14. # python <script>
  15. # -----------------------------------------------------------------------------------------
  16. # Human-computer dialog UI based on the chat control.
  17. # -----------------------------------------------------------------------------------------
  18. from math import cos, pi, sin, sqrt, tan # noqa: F401
  19. from taipy.gui import Gui
  20. # The user interacts with the Python interpreter
  21. users = ["human", "Result"]
  22. messages: list[tuple[str, str, str]] = []
  23. def evaluate(state, var_name: str, payload: dict):
  24. # Retrieve the callback parameters
  25. (_, _, expression, sender_id) = payload.get("args", [])
  26. # Add the input content as a sent message
  27. messages.append((f"{len(messages)}", expression, sender_id))
  28. # Default message used if evaluation fails
  29. result = "Invalid expression"
  30. try:
  31. # Evaluate the expression and store the result
  32. result = f"= {eval(expression)}"
  33. except Exception:
  34. pass
  35. # Add the result as an incoming message
  36. messages.append((f"{len(messages)}", result, users[1]))
  37. state.messages = messages
  38. page = """
  39. <|{messages}|chat|users={users}|sender_id={users[0]}|on_action=evaluate|>
  40. """
  41. Gui(page).run()