Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: get messages from messages table for the playground #3874

Merged
merged 190 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
190 commits
Select commit Hold shift + click to select a range
90e89a6
refactor: Update MessageBase text attribute based on isinstance check.
ogabrielluiz Aug 19, 2024
9ca83a0
feat: Add update_message function to update a message in the database.
ogabrielluiz Aug 19, 2024
a79282e
refactor(chat): Update imports and remove unnecessary config method i…
ogabrielluiz Aug 19, 2024
c71f6b4
refactor: Add stream_message method to ChatComponent.
ogabrielluiz Aug 19, 2024
37a5ac6
refactor: Update method call in ChatOutput component.
ogabrielluiz Aug 19, 2024
ff3eec5
feat: Add callback function to custom component and update build_resu…
ogabrielluiz Aug 19, 2024
61e5d72
feat: Add callback parameter to instantiate_class function.
ogabrielluiz Aug 19, 2024
ef8815c
feat(graph): Add callback functions for sync and async operations.
ogabrielluiz Aug 19, 2024
bf2618d
feat: Add callback function support to vertex build process.
ogabrielluiz Aug 19, 2024
e1fe1be
feat: Add handling for added message in InterfaceVertex class.
ogabrielluiz Aug 19, 2024
4c41950
feat: Add callback support to Graph methods.
ogabrielluiz Aug 19, 2024
d2a200a
feat(chat): Add callback function to build_vertices function.
ogabrielluiz Aug 19, 2024
fc9c9df
refactor: Simplify update_message function and use session_scope for …
ogabrielluiz Aug 19, 2024
5e9388b
fix: Call set_callback method if available on custom component.
ogabrielluiz Aug 19, 2024
ea9ad4e
refactor(chat): Update chat message chunk handling and ID conversion.
ogabrielluiz Aug 19, 2024
54f35cd
feat: Add null check before setting cache in build_vertex_stream func…
ogabrielluiz Aug 19, 2024
6929631
refactor: Fix send_event_wrapper function and add callback parameter …
ogabrielluiz Aug 19, 2024
d1f9c75
refactor: Simplify conditional statement and import order in ChatOutput.
ogabrielluiz Aug 19, 2024
e4db7bc
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 19, 2024
abaa23e
refactor: move log method to Component class.
ogabrielluiz Aug 20, 2024
9a8019f
refactor: Simplify CallbackFunction definition.
ogabrielluiz Aug 20, 2024
441015e
feat: Initialize _current_output attribute in Component class.
ogabrielluiz Aug 20, 2024
6fec2b3
feat: store current output name in custom component during processing.
ogabrielluiz Aug 20, 2024
b2119d2
feat: Add current output and component ID to log data.
ogabrielluiz Aug 20, 2024
93a7802
fix: Add condition to check current output before invoking callback.
ogabrielluiz Aug 20, 2024
8766c43
refactor: Update callback to log_callback in graph methods.
ogabrielluiz Aug 20, 2024
5e25adf
feat: Add test for callback graph execution with log messages.
ogabrielluiz Aug 20, 2024
d2b4bf7
update projects
ogabrielluiz Aug 23, 2024
0817895
fix(chat.py): fix condition to check if message text is a string befo…
ogabrielluiz Aug 27, 2024
b46f536
refactor(ChatOutput.py): update ChatOutput class to correctly store a…
ogabrielluiz Aug 27, 2024
49b73d1
refactor(chat.py): update return type of store_message method to retu…
ogabrielluiz Aug 27, 2024
1db1b0e
update starter projects
ogabrielluiz Aug 27, 2024
28d00c9
refactor(component.py): update type hint for name parameter in log me…
ogabrielluiz Aug 28, 2024
6c2876b
feat: Add EventManager class for managing events and event registration
ogabrielluiz Aug 28, 2024
ad37fc3
refactor: Update log_callback to event_manager in custom component cl…
ogabrielluiz Aug 28, 2024
06ced11
refactor(component.py): rename _log_callback to _event_manager and up…
ogabrielluiz Aug 28, 2024
31898ea
refactor(chat.py): rename _log_callback method to _event_manager.on_t…
ogabrielluiz Aug 28, 2024
b2c4bf4
refactor: Rename log_callback to event_manager for clarity and consis…
ogabrielluiz Aug 28, 2024
e88c145
refactor: Update Vertex class to use EventManager instead of log_call…
ogabrielluiz Aug 28, 2024
2d29f00
refactor: update build_flow to use EventManager
ogabrielluiz Aug 28, 2024
d8320de
refactor: Update EventManager class to use Protocol for event callbacks
ogabrielluiz Aug 28, 2024
b630bba
if event_type is not passed, it uses the default send_event
ogabrielluiz Aug 28, 2024
c72bd9b
Add method to register event functions in EventManager
ogabrielluiz Aug 28, 2024
2c95daf
update test_callback_graph
ogabrielluiz Aug 28, 2024
8834512
Add unit tests for EventManager in test_event_manager.py
ogabrielluiz Aug 28, 2024
d375bd4
feat: Add callback function support to vertex build process.
ogabrielluiz Aug 19, 2024
bfce547
feat: Add callback support to Graph methods.
ogabrielluiz Aug 19, 2024
108d09a
feat(chat): Add callback function to build_vertices function.
ogabrielluiz Aug 19, 2024
578f1a5
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 19, 2024
ef24c22
refactor: Update callback to log_callback in graph methods.
ogabrielluiz Aug 20, 2024
ffc3094
fetching data from messages and builds at the same time, need to remo…
anovazzi1 Aug 23, 2024
07e6991
refactor: Sort chat history by timestamp in ChatView component
anovazzi1 Aug 26, 2024
8247d2e
fix: update serialization and improve error handling (#3516)
ogabrielluiz Aug 23, 2024
f13399f
remove use memo to prevent bugs
anovazzi1 Aug 26, 2024
ec52860
feat: add updateMessagePartial method to MessagesStoreType
anovazzi1 Aug 27, 2024
21259d7
feat: update message partially in MessagesStoreType
anovazzi1 Aug 27, 2024
ea460d0
feat: add log callback for start message in ChatComponent
anovazzi1 Aug 27, 2024
46ad530
feat: update log_callback name
anovazzi1 Aug 27, 2024
f493af6
feat: add log_callback for message in ChatComponent that are not stre…
anovazzi1 Aug 27, 2024
ea11475
refactor: remove console.log statement in buildFlowVertices function
anovazzi1 Aug 28, 2024
d5397d6
refactor: store message in ChatInput after updating flow_id
anovazzi1 Aug 28, 2024
67f7f72
refactor: move message storage logic in ChatInput after updating flow_id
anovazzi1 Aug 28, 2024
7e9ccdc
refactor: update ChatComponent to use stored_message.id instead of se…
anovazzi1 Aug 28, 2024
604fbd2
refactor: remove unused code and console.log statements
anovazzi1 Aug 28, 2024
c3576bc
raw: temp serializer fix
italojohnny Sep 2, 2024
b299a9e
streaming working but the message comes in one shot
anovazzi1 Sep 3, 2024
a4825c2
refactor: optimize message update in useMessagesStore
anovazzi1 Sep 3, 2024
c9a8f19
Refactor `serialize_flow_id` method to correctly handle UUID serializ…
ogabrielluiz Sep 3, 2024
a18d02c
Refactor `send_event` method to use `jsonable_encoder` for data seria…
ogabrielluiz Sep 3, 2024
5fe292e
refactor: optimize message update in useMessagesStore
anovazzi1 Sep 3, 2024
8420ec5
streaming working with timeout
anovazzi1 Sep 3, 2024
6d321e9
refactor: update buildUtils.ts to use data instead of data.data in ad…
anovazzi1 Sep 3, 2024
7b1b8f8
version with reactState for chatHistory
anovazzi1 Sep 3, 2024
49129eb
refactor: update on_message method in ChatComponent
anovazzi1 Sep 3, 2024
932295c
Merge branch 'main' into UpdateChatDataSource
anovazzi1 Sep 3, 2024
b598231
refactor: update on_message method in ChatComponent
anovazzi1 Sep 3, 2024
560de16
refactor: Remove unused dependency in package-lock.json
anovazzi1 Sep 6, 2024
c27c73a
Refactor chatView component and add hiddenSession prop
anovazzi1 Sep 6, 2024
35d3aa4
Refactor chatView component and update hiddenSessions prop
anovazzi1 Sep 6, 2024
4283600
Refactor chatView component to use visibleSessions prop instead of hi…
anovazzi1 Sep 9, 2024
1d54fdb
Refactor IOModal component to remove redundant code
anovazzi1 Sep 9, 2024
3dfbe66
Refactor chatView component to include focusChat prop
anovazzi1 Sep 9, 2024
314747d
Refactor chatView component to include focusChat prop and trigger foc…
anovazzi1 Sep 9, 2024
e593e5b
Merge remote-tracking branch 'origin/main' into UpdateChatDataSource
anovazzi1 Sep 9, 2024
ecabdb1
Refactor IOModal component to update visible sessions when new sessio…
anovazzi1 Sep 10, 2024
6d65c50
Merge remote-tracking branch 'origin/main' into UpdateChatDataSource
anovazzi1 Sep 12, 2024
a360615
feat: Add session parameter to buildFlowVertices function
anovazzi1 Sep 12, 2024
16ec7f2
feat: Add someFlowTemplateFields function
anovazzi1 Sep 12, 2024
5dbdf57
feat: Add session parameter to buildFlowVertices function
anovazzi1 Sep 12, 2024
631468f
feat: Add session parameter to buildFlowVertices function
anovazzi1 Sep 12, 2024
18af981
update Session logic on ioModal
anovazzi1 Sep 12, 2024
0fe7c00
Refactor ChatView component: Remove unused eraser button
anovazzi1 Sep 12, 2024
35cbea4
Refactor Vertex class: Inject session_id if provided in inputs
anovazzi1 Sep 13, 2024
5f9e6a0
Refactor build_flow function: Set default session if inputs are empty
anovazzi1 Sep 13, 2024
95ccbdb
Refactor InputValueRequest schema: Add session parameter
anovazzi1 Sep 13, 2024
4c42d48
Refactor IOModal component: Update session logic
anovazzi1 Sep 13, 2024
c324cca
Refactor buildFlowVertices function: Update input handling
anovazzi1 Sep 13, 2024
ab7ee2a
Refactor MessagesStoreType in zustand/messages/index.ts: Remove unuse…
anovazzi1 Sep 13, 2024
ed86d88
Refactor MessagesStoreType: Remove unused columns property and setCol…
anovazzi1 Sep 13, 2024
3211b22
Refactor SessionView component: Update columns extraction logic
anovazzi1 Sep 13, 2024
1580757
Refactor ChatView component: Remove unused variables
anovazzi1 Sep 13, 2024
6a0b8ef
Refactor useGetMessagesQuery: Remove unused setColumns method
anovazzi1 Sep 13, 2024
4571a8b
Refactor RenderIcons component: Set default value for filteredShortcu…
anovazzi1 Sep 13, 2024
de4f3fc
create edit message component for chat view
anovazzi1 Sep 18, 2024
80ff185
Refactor useUpdateMessage: Add refetch option to trigger query refetch
anovazzi1 Sep 18, 2024
3ac3bae
Refactor IOModal component: Remove unused variables and update useGet…
anovazzi1 Sep 18, 2024
4779185
Refactor ChatView component: Add session ID to message object
anovazzi1 Sep 18, 2024
8c97c4d
update chat message to handle message edit
anovazzi1 Sep 18, 2024
aa0d65d
update types
anovazzi1 Sep 18, 2024
d115487
fix: Update API call to send entire message object
anovazzi1 Sep 18, 2024
778e886
Refactor EditMessageField component: Add timeout to onBlur event
anovazzi1 Sep 18, 2024
9bb1510
Refactor EditMessageField component: Update layout of edit message field
anovazzi1 Sep 18, 2024
8344549
create migration
anovazzi1 Sep 19, 2024
b72d36a
add fields to data table
anovazzi1 Sep 19, 2024
b245d57
feat: Add "edit" flag to message_dict in update_message API endpoint
anovazzi1 Sep 19, 2024
8302fd4
Refactor EditMessageField component: Improve onBlur event handling an…
anovazzi1 Sep 19, 2024
e3b6f3c
Refactor code to include "edit" flag in message types
anovazzi1 Sep 20, 2024
2df54d9
feat: Add EditMessageButton component for editing chat messages
anovazzi1 Sep 20, 2024
3e2cd4e
Refactor ChatMessage component: Add EditMessageButton and improve layout
anovazzi1 Sep 20, 2024
7a10e70
fix: Add refetch query for current flow messages not all flows
anovazzi1 Sep 20, 2024
e1cd809
Refactor ChatMessage component: Add ShadTooltip for EditMessageButton
anovazzi1 Sep 20, 2024
80eecbf
add info into edit message field
anovazzi1 Sep 20, 2024
60f8bb9
fix: migrate
italojohnny Sep 21, 2024
70a0f3c
Merge remote-tracking branch 'origin/main' into UpdateChatDataSource
anovazzi1 Sep 23, 2024
ab2ec07
fix running chat input directly from the flow
anovazzi1 Sep 23, 2024
b88a2f9
[autofix.ci] apply automated fixes
autofix-ci[bot] Sep 23, 2024
739b3aa
fix edit flag
anovazzi1 Sep 23, 2024
6f86f32
Refactor IOModal component to generate a unique session ID based on t…
anovazzi1 Sep 23, 2024
c12106b
[autofix.ci] apply automated fixes
autofix-ci[bot] Sep 23, 2024
0dd3dff
Refactor IOModal component to improve session management and interaction
anovazzi1 Sep 24, 2024
902e941
[autofix.ci] apply automated fixes
autofix-ci[bot] Sep 24, 2024
3a3a48e
Merge branch 'main' into UpdateChatDataSource
ogabrielluiz Oct 8, 2024
a5094a6
Refactor sessionSelector component to improve session management and …
anovazzi1 Oct 7, 2024
c6d3a74
chore: Refactor sessionSelector component to improve session manageme…
anovazzi1 Oct 8, 2024
e6b7761
Merge remote-tracking branch 'origin/main' into UpdateChatDataSource
anovazzi1 Oct 8, 2024
249f21a
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 8, 2024
6cb5f59
create mutation to handle session rename
anovazzi1 Oct 8, 2024
36fa128
refactor: Rename useUpdateSession to useUpdateSessionName for clarity
anovazzi1 Oct 8, 2024
e1ab7bc
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 8, 2024
eb5820c
Refactor sessionSelector component for improved session management an…
anovazzi1 Oct 8, 2024
bf111ea
Refactor sessionSelector component to update visible session on sessi…
anovazzi1 Oct 8, 2024
c55bd67
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 8, 2024
fc2cfca
add message related events back
anovazzi1 Oct 8, 2024
40968c7
chore: Add console logs for debugging in buildFlowVertices function
anovazzi1 Oct 8, 2024
5cbffa5
Refactor IOModal component to update tab trigger label from "Memories…
anovazzi1 Oct 8, 2024
ccce475
improve edit name feature
anovazzi1 Oct 9, 2024
f78b322
Refactor IOModal component button label to "New Chat"
anovazzi1 Oct 9, 2024
cbbc35c
Refactor sessionSelector component to improve session management and …
anovazzi1 Oct 9, 2024
52dbbef
Refactor IOModal component to remove unused code and improve session …
anovazzi1 Oct 9, 2024
91a8deb
fix typing error
anovazzi1 Oct 9, 2024
586777f
fix run chat input on component level
anovazzi1 Oct 9, 2024
7ed460f
prevent toogle visibility on session menu
anovazzi1 Oct 9, 2024
94d6cbb
fix bug on rename session while in table view mode
anovazzi1 Oct 9, 2024
215b3f2
chore: Update setSelectedView prop type in sessionSelector component
anovazzi1 Oct 9, 2024
a553623
add first test version not working yet
anovazzi1 Oct 9, 2024
9fccd7f
fix bug for renaming and deleting session
anovazzi1 Oct 9, 2024
eae60d2
refactor: Update sessionSelector component to handle session changes
anovazzi1 Oct 9, 2024
6cd91af
improve test
anovazzi1 Oct 10, 2024
0059309
fix rename session multiple session bugs
anovazzi1 Oct 10, 2024
bedcdab
change visible session from array to string
anovazzi1 Oct 10, 2024
3b09d3e
chore: Update editMessageField component to include margin-right for …
anovazzi1 Oct 10, 2024
56a9cb0
Merge branch 'main' into UpdateChatDataSource
ogabrielluiz Oct 11, 2024
312ec21
Merge branch 'main' into UpdateChatDataSource
ogabrielluiz Oct 14, 2024
1a6a3c0
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 14, 2024
a7cc9bd
Update down_revision in Alembic migration script
ogabrielluiz Oct 14, 2024
c99a0e9
Merge branch 'main' into UpdateChatDataSource
ogabrielluiz Oct 14, 2024
c836daf
Refactor IOModal component to simplify session visibility handling
anovazzi1 Oct 14, 2024
40b03bc
Merge branch 'main' into UpdateChatDataSource
ogabrielluiz Oct 14, 2024
cb048f6
Fix comparison operator for filtering error messages in memory.py
ogabrielluiz Oct 15, 2024
a385eea
Refactor ChatInput to conditionally store and update messages
ogabrielluiz Oct 15, 2024
322acaf
Refactor JSON formatting for improved readability in starter projects
ogabrielluiz Oct 15, 2024
8f5f22a
Merge branch 'main' into UpdateChatDataSource
ogabrielluiz Oct 15, 2024
308a441
Add type casting for message_text and import cast from typing module
ogabrielluiz Oct 15, 2024
60a1cfe
Refactor input handling to use direct dictionary access for 'session'…
ogabrielluiz Oct 15, 2024
6d7fd05
Allow `update_message` to accept `str` type for `message_id` parameter
ogabrielluiz Oct 15, 2024
9624b55
Merge branch 'main' into UpdateChatDataSource
anovazzi1 Oct 15, 2024
68a9678
⬆️ (pyproject.toml): upgrade duckduckgo-search dependency to version …
Cristhianzl Oct 15, 2024
f2222dc
Refactor test file: generalBugs-shard-0.spec.ts
anovazzi1 Oct 15, 2024
7570ffb
Refactor test file: freeze.spec.ts
anovazzi1 Oct 15, 2024
b43ce12
Refactor test files: update element selectors and actions
anovazzi1 Oct 15, 2024
88b62a0
Refactor test file: chatInputOutput.spec.ts
anovazzi1 Oct 15, 2024
ce5f842
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 15, 2024
70d63e6
Refactor chatMessage component to handle different types of children …
anovazzi1 Oct 15, 2024
655ebda
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 15, 2024
454c5c7
fix bug color on clipboard icon
anovazzi1 Oct 15, 2024
7757c81
Merge branch 'main' into UpdateChatDataSource
anovazzi1 Oct 15, 2024
109179f
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 15, 2024
6b15b11
fix delete session
anovazzi1 Oct 15, 2024
5bb7728
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 15, 2024
c89a45b
Merge branch 'main' into UpdateChatDataSource
anovazzi1 Oct 15, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ dependencies = [
"jq>=1.8.0",
"pydantic-settings==2.4.0",
"ragstack-ai-knowledge-store>=0.2.1",
"duckduckgo-search>=6.3.0",
"duckduckgo-search>=6.3.1",
"langchain-elasticsearch>=0.2.0",
"opensearch-py>=2.7.1",
]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Add error and edit flags to message

Revision ID: eb5e72293a8e
Revises: 5ace73a7f223
Create Date: 2024-09-19 16:18:50.828648

"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op
from sqlalchemy.engine.reflection import Inspector

# revision identifiers, used by Alembic.
revision: str = "eb5e72293a8e"
down_revision: Union[str, None] = "5ace73a7f223"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
conn = op.get_bind()
inspector = Inspector.from_engine(conn) # type: ignore
table_names = inspector.get_table_names() # noqa
column_names = [column["name"] for column in inspector.get_columns("message")]
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("message", schema=None) as batch_op:
if "error" not in column_names:
batch_op.add_column(sa.Column("error", sa.Boolean(), nullable=False, server_default=sa.false()))
if "edit" not in column_names:
batch_op.add_column(sa.Column("edit", sa.Boolean(), nullable=False, server_default=sa.false()))

# ### end Alembic commands ###


def downgrade() -> None:
conn = op.get_bind()
inspector = Inspector.from_engine(conn) # type: ignore
table_names = inspector.get_table_names() # noqa
column_names = [column["name"] for column in inspector.get_columns("message")]
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("message", schema=None) as batch_op:
if "edit" in column_names:
batch_op.drop_column("edit")
if "error" in column_names:
batch_op.drop_column("error")

# ### end Alembic commands ###
3 changes: 3 additions & 0 deletions src/backend/base/langflow/api/v1/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ async def build_flow(
telemetry_service: TelemetryService = Depends(get_telemetry_service),
session=Depends(get_session),
):
if not inputs:
inputs = InputValueRequest(session=str(flow_id))

async def build_graph_and_get_order() -> tuple[list[str], list[str], Graph]:
start_time = time.perf_counter()
components_count = None
Expand Down
1 change: 1 addition & 0 deletions src/backend/base/langflow/api/v1/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ async def update_message(

try:
message_dict = message.model_dump(exclude_unset=True, exclude_none=True)
message_dict["edit"] = True
db_message.sqlmodel_update(message_dict)
session.add(db_message)
session.commit()
Expand Down
4 changes: 4 additions & 0 deletions src/backend/base/langflow/api/v1/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ class VerticesBuiltResponse(BaseModel):
class InputValueRequest(BaseModel):
components: list[str] | None = []
input_value: str | None = None
session: str | None = None
type: InputType | None = Field(
"any",
description="Defines on which components the input value should be applied. "
Expand All @@ -310,9 +311,12 @@ class InputValueRequest(BaseModel):
{
"components": ["components_id", "Component Name"],
"input_value": "input_value",
"session": "session_id",
},
{"components": ["Component Name"], "input_value": "input_value"},
{"input_value": "input_value"},
{"components": ["Component Name"], "input_value": "input_value", "session": "session_id"},
{"input_value": "input_value", "session": "session_id"},
{"type": "chat", "input_value": "input_value"},
{"type": "json", "input_value": '{"key": "value"}'},
]
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/base/astra_assistants/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def get_patched_openai_client(shared_component_cache):
data = json.loads(response.text)

# Extract the model names into a Python list
litellm_model_names = [model for model, _ in data.items() if model != "sample_spec"]
litellm_model_names = [model for model in data if model != "sample_spec"]


# To store the class names that extend ToolInterface
Expand Down
96 changes: 54 additions & 42 deletions src/backend/base/langflow/base/io/chat.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from collections.abc import AsyncIterator, Iterator
from typing import cast

from langflow.custom import Component
from langflow.memory import store_message
Expand All @@ -12,43 +13,52 @@ class ChatComponent(Component):
display_name = "Chat Component"
description = "Use as base for chat components."

# Keep this method for backward compatibility
def store_message(
self,
message: Message,
) -> Message:
messages = store_message(
message,
flow_id=self.graph.flow_id,
)
if len(messages) > 1:
def store_message(self, message: Message) -> Message:
messages = store_message(message, flow_id=self.graph.flow_id)
if len(messages) != 1:
msg = "Only one message can be stored at a time."
raise ValueError(msg)

stored_message = messages[0]
if (
hasattr(self, "_event_manager")
and self._event_manager
and stored_message.id
and not isinstance(message.text, str)
):
self._send_message_event(stored_message)

if self._should_stream_message(stored_message, message):
complete_message = self._stream_message(message, stored_message.id)
message_table = update_message(message_id=stored_message.id, message={"text": complete_message})
stored_message = Message(**message_table.model_dump())
self.vertex._added_message = stored_message
stored_message = self._update_stored_message(stored_message.id, complete_message)

self.status = stored_message
return stored_message

def _send_message_event(self, message: Message):
if hasattr(self, "_event_manager") and self._event_manager:
self._event_manager.on_message(data=message.data)

def _should_stream_message(self, stored_message: Message, original_message: Message) -> bool:
return bool(
hasattr(self, "_event_manager")
and self._event_manager
and stored_message.id
and not isinstance(original_message.text, str)
)

def _update_stored_message(self, message_id: str, complete_message: str) -> Message:
message_table = update_message(message_id=message_id, message={"text": complete_message})
updated_message = Message(**message_table.model_dump())
self.vertex._added_message = updated_message
return updated_message

def _process_chunk(self, chunk: str, complete_message: str, message: Message, message_id: str) -> str:
complete_message += chunk
data = {
"text": complete_message,
"chunk": chunk,
"sender": message.sender,
"sender_name": message.sender_name,
"id": str(message_id),
}
if self._event_manager:
self._event_manager.on_token(data=data)
self._event_manager.on_token(
data={
"text": complete_message,
"chunk": chunk,
"sender": message.sender,
"sender_name": message.sender_name,
"id": str(message_id),
}
)
return complete_message

async def _handle_async_iterator(self, iterator: AsyncIterator, message: Message, message_id: str) -> str:
Expand All @@ -69,7 +79,6 @@ def _stream_message(self, message: Message, message_id: str) -> str:
complete_message = ""
for chunk in iterator:
complete_message = self._process_chunk(chunk.content, complete_message, message, message_id)

return complete_message

def build_with_data(
Expand All @@ -80,22 +89,25 @@ def build_with_data(
input_value: str | Data | Message | None = None,
files: list[str] | None = None,
session_id: str | None = None,
return_message: bool | None = False,
) -> Message:
if isinstance(input_value, Data):
# Update the data of the record
message = Message.from_data(input_value)
else:
message = Message(
text=input_value, sender=sender, sender_name=sender_name, files=files, session_id=session_id
)
return_message: bool = False,
) -> str | Message:
message = self._create_message(input_value, sender, sender_name, files, session_id)
message_text = message.text if not return_message else message

self.status = message_text
if session_id and isinstance(message, Message) and isinstance(message.text, str):
messages = store_message(
message,
flow_id=self.graph.flow_id,
)
messages = store_message(message, flow_id=self.graph.flow_id)
self.status = messages
return message_text # type: ignore[return-value]
self._send_messages_events(messages)

return cast(str | Message, message_text)

def _create_message(self, input_value, sender, sender_name, files, session_id) -> Message:
if isinstance(input_value, Data):
return Message.from_data(input_value)
return Message(text=input_value, sender=sender, sender_name=sender_name, files=files, session_id=session_id)

def _send_messages_events(self, messages):
if hasattr(self, "_event_manager") and self._event_manager:
for stored_message in messages:
self._event_manager.on_message(data=stored_message.data)
15 changes: 4 additions & 11 deletions src/backend/base/langflow/components/inputs/ChatInput.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from langflow.base.io.chat import ChatComponent
from langflow.inputs import BoolInput
from langflow.io import DropdownInput, FileInput, MessageTextInput, MultilineInput, Output
from langflow.memory import store_message
from langflow.schema.message import Message
from langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_USER, MESSAGE_SENDER_USER

Expand Down Expand Up @@ -69,18 +68,12 @@ def message_response(self) -> Message:
session_id=self.session_id,
files=self.files,
)

if (
self.session_id
and isinstance(message, Message)
and isinstance(message.text, str)
and self.should_store_message
):
store_message(
if self.session_id and isinstance(message, Message) and self.should_store_message:
stored_message = self.store_message(
message,
flow_id=self.graph.flow_id,
)
self.message.value = message
self.message.value = stored_message
message = stored_message

self.status = message
return message
14 changes: 4 additions & 10 deletions src/backend/base/langflow/components/outputs/ChatOutput.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from langflow.base.io.chat import ChatComponent
from langflow.inputs import BoolInput
from langflow.io import DropdownInput, MessageTextInput, Output
from langflow.memory import store_message
from langflow.schema.message import Message
from langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER

Expand Down Expand Up @@ -65,17 +64,12 @@ def message_response(self) -> Message:
sender_name=self.sender_name,
session_id=self.session_id,
)
if (
self.session_id
and isinstance(message, Message)
and isinstance(message.text, str)
and self.should_store_message
):
store_message(
if self.session_id and isinstance(message, Message) and self.should_store_message:
stored_message = self.store_message(
message,
flow_id=self.graph.flow_id,
)
self.message.value = message
self.message.value = stored_message
message = stored_message

self.status = message
return message
4 changes: 3 additions & 1 deletion src/backend/base/langflow/events/event_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import uuid
from functools import partial

from fastapi.encoders import jsonable_encoder
from typing_extensions import Protocol

from langflow.schema.log import LoggableType
Expand Down Expand Up @@ -52,7 +53,8 @@ def register_event(self, name: str, event_type: str, callback: EventCallback | N
self.events[name] = _callback

def send_event(self, *, event_type: str, data: LoggableType):
json_data = {"event": event_type, "data": data}
jsonable_data = jsonable_encoder(data)
json_data = {"event": event_type, "data": jsonable_data}
event_id = uuid.uuid4()
str_data = json.dumps(json_data) + "\n\n"
self.queue.put_nowait((event_id, str_data.encode("utf-8"), time.time()))
Expand Down
15 changes: 12 additions & 3 deletions src/backend/base/langflow/graph/vertex/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,11 +793,20 @@ async def build(
# and we are just getting the result for the requester
return await self.get_requester_result(requester)
self._reset()

# inject session_id if it is not None
if inputs is not None and "session" in inputs and inputs["session"] is not None and self.has_session_id:
session_id_value = self.get_value_from_template_dict("session_id")
if session_id_value == "":
self.update_raw_params({"session_id": inputs["session"]}, overwrite=True)
if self._is_chat_input() and (inputs or files):
chat_input = {}
if inputs:
chat_input.update({"input_value": inputs.get(INPUT_FIELD_NAME, "")})
if (
inputs
and isinstance(inputs, dict)
and "input_value" in inputs
and inputs["input_value"] is not None
):
chat_input.update({"input_value": inputs[INPUT_FIELD_NAME]})
if files:
chat_input.update({"files": files})

Expand Down
Loading
Loading