ui.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. from __future__ import annotations
  2. from typing import Any, Literal, cast
  3. from uuid import uuid4
  4. from langchain_core.messages import AnyMessage
  5. from typing_extensions import TypedDict
  6. from langgraph.config import get_config, get_stream_writer
  7. from langgraph.constants import CONF
  8. __all__ = (
  9. "UIMessage",
  10. "RemoveUIMessage",
  11. "AnyUIMessage",
  12. "push_ui_message",
  13. "delete_ui_message",
  14. "ui_message_reducer",
  15. )
  16. class UIMessage(TypedDict):
  17. """A message type for UI updates in LangGraph.
  18. This TypedDict represents a UI message that can be sent to update the UI state.
  19. It contains information about the UI component to render and its properties.
  20. Attributes:
  21. type: Literal type indicating this is a UI message.
  22. id: Unique identifier for the UI message.
  23. name: Name of the UI component to render.
  24. props: Properties to pass to the UI component.
  25. metadata: Additional metadata about the UI message.
  26. """
  27. type: Literal["ui"]
  28. id: str
  29. name: str
  30. props: dict[str, Any]
  31. metadata: dict[str, Any]
  32. class RemoveUIMessage(TypedDict):
  33. """A message type for removing UI components in LangGraph.
  34. This TypedDict represents a message that can be sent to remove a UI component
  35. from the current state.
  36. Attributes:
  37. type: Literal type indicating this is a remove-ui message.
  38. id: Unique identifier of the UI message to remove.
  39. """
  40. type: Literal["remove-ui"]
  41. id: str
  42. AnyUIMessage = UIMessage | RemoveUIMessage
  43. def push_ui_message(
  44. name: str,
  45. props: dict[str, Any],
  46. *,
  47. id: str | None = None,
  48. metadata: dict[str, Any] | None = None,
  49. message: AnyMessage | None = None,
  50. state_key: str | None = "ui",
  51. merge: bool = False,
  52. ) -> UIMessage:
  53. """Push a new UI message to update the UI state.
  54. This function creates and sends a UI message that will be rendered in the UI.
  55. It also updates the graph state with the new UI message.
  56. Args:
  57. name: Name of the UI component to render.
  58. props: Properties to pass to the UI component.
  59. id: Optional unique identifier for the UI message.
  60. If not provided, a random UUID will be generated.
  61. metadata: Optional additional metadata about the UI message.
  62. message: Optional message object to associate with the UI message.
  63. state_key: Key in the graph state where the UI messages are stored.
  64. merge: Whether to merge props with existing UI message (True) or replace
  65. them (False).
  66. Returns:
  67. The created UI message.
  68. Example:
  69. ```python
  70. push_ui_message(
  71. name="component-name",
  72. props={"content": "Hello world"},
  73. )
  74. ```
  75. """
  76. from langgraph._internal._constants import CONFIG_KEY_SEND
  77. writer = get_stream_writer()
  78. config = get_config()
  79. message_id = None
  80. if message:
  81. if isinstance(message, dict) and "id" in message:
  82. message_id = message.get("id")
  83. elif hasattr(message, "id"):
  84. message_id = message.id
  85. evt: UIMessage = {
  86. "type": "ui",
  87. "id": id or str(uuid4()),
  88. "name": name,
  89. "props": props,
  90. "metadata": {
  91. "merge": merge,
  92. "run_id": config.get("run_id", None),
  93. "tags": config.get("tags", None),
  94. "name": config.get("run_name", None),
  95. **(metadata or {}),
  96. **({"message_id": message_id} if message_id else {}),
  97. },
  98. }
  99. writer(evt)
  100. if state_key:
  101. config[CONF][CONFIG_KEY_SEND]([(state_key, evt)])
  102. return evt
  103. def delete_ui_message(id: str, *, state_key: str = "ui") -> RemoveUIMessage:
  104. """Delete a UI message by ID from the UI state.
  105. This function creates and sends a message to remove a UI component from the current state.
  106. It also updates the graph state to remove the UI message.
  107. Args:
  108. id: Unique identifier of the UI component to remove.
  109. state_key: Key in the graph state where the UI messages are stored. Defaults to "ui".
  110. Returns:
  111. The remove UI message.
  112. Example:
  113. ```python
  114. delete_ui_message("message-123")
  115. ```
  116. """
  117. from langgraph._internal._constants import CONFIG_KEY_SEND
  118. writer = get_stream_writer()
  119. config = get_config()
  120. evt: RemoveUIMessage = {"type": "remove-ui", "id": id}
  121. writer(evt)
  122. config[CONF][CONFIG_KEY_SEND]([(state_key, evt)])
  123. return evt
  124. def ui_message_reducer(
  125. left: list[AnyUIMessage] | AnyUIMessage,
  126. right: list[AnyUIMessage] | AnyUIMessage,
  127. ) -> list[AnyUIMessage]:
  128. """Merge two lists of UI messages, supporting removing UI messages.
  129. This function combines two lists of UI messages, handling both regular UI messages
  130. and `remove-ui` messages. When a `remove-ui` message is encountered, it removes any
  131. UI message with the matching ID from the current state.
  132. Args:
  133. left: First list of UI messages or single UI message.
  134. right: Second list of UI messages or single UI message.
  135. Returns:
  136. Combined list of UI messages with removals applied.
  137. Example:
  138. ```python
  139. messages = ui_message_reducer(
  140. [{"type": "ui", "id": "1", "name": "Chat", "props": {}}],
  141. {"type": "remove-ui", "id": "1"},
  142. )
  143. ```
  144. """
  145. if not isinstance(left, list):
  146. left = [left]
  147. if not isinstance(right, list):
  148. right = [right]
  149. # merge messages
  150. merged = left.copy()
  151. merged_by_id = {m.get("id"): i for i, m in enumerate(merged)}
  152. ids_to_remove = set()
  153. for msg in right:
  154. msg_id = msg.get("id")
  155. if (existing_idx := merged_by_id.get(msg_id)) is not None:
  156. if msg.get("type") == "remove-ui":
  157. ids_to_remove.add(msg_id)
  158. else:
  159. ids_to_remove.discard(msg_id)
  160. if cast(UIMessage, msg).get("metadata", {}).get("merge", False):
  161. prev_msg = merged[existing_idx]
  162. msg = msg.copy()
  163. msg["props"] = {**prev_msg["props"], **msg["props"]}
  164. merged[existing_idx] = msg
  165. else:
  166. if msg.get("type") == "remove-ui":
  167. raise ValueError(
  168. f"Attempting to delete an UI message with an ID that doesn't exist ('{msg_id}')"
  169. )
  170. merged_by_id[msg_id] = len(merged)
  171. merged.append(msg)
  172. merged = [m for m in merged if m.get("id") not in ids_to_remove]
  173. return merged