chat_calculator.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 typing import Optional
  20. from taipy.gui import Gui
  21. # The user interacts with the Python interpreter
  22. users = ["human", "Result"]
  23. messages: list[tuple[str, str, str, Optional[str]]] = []
  24. def evaluate(state, var_name: str, payload: dict):
  25. # Retrieve the callback parameters
  26. (_, _, expression, sender_id, image_url) = payload.get("args", [])
  27. # Add the input content as a sent message
  28. messages.append((f"{len(messages)}", expression, sender_id, image_url))
  29. # Default message used if evaluation fails
  30. result = "Invalid expression"
  31. try:
  32. # Evaluate the expression and store the result
  33. result = f"= {eval(expression)}"
  34. except Exception:
  35. pass
  36. # Add the result as an incoming message
  37. messages.append((f"{len(messages)}", result, users[1], None))
  38. state.messages = messages
  39. page = """
  40. <|{messages}|chat|users={users}|sender_id={users[0]}|on_action=evaluate|>
  41. """
  42. Gui(page).run(title="Chat - Calculator")