langflow icon indicating copy to clipboard operation
langflow copied to clipboard

Postgres 9h9h Issue

Open raprajapati1208 opened this issue 1 year ago • 9 comments

Bug Description

I have Postgres as the database for Langflow. The Agent component is trying to store an invalid JSON schema to the database which gives the below error.

(psycopg.errors.InvalidTextRepresentation) invalid input syntax for type json DETAIL: Token "NaN" is invalid. CONTEXT: JSON data, line 1: ... with sustainability as their\u00a0...", "6": NaN... unnamed portal parameter $2 = '...' [SQL: UPDATE message SET timestamp=%(timestamp)s::TIMESTAMP WITHOUT TIME ZONE, content_blocks=%(content_blocks)s::JSON WHERE message.id = %(message_id)s::UUID] [parameters: {'timestamp': datetime.datetime(2025, 3, 25, 13, 45, 16, tzinfo=datetime.timezone.utc), 'content_blocks': Json([{'title': 'Agent Steps', 'contents ... (2938 chars)), 'message_id': UUID('135dfd6d-0325-4829-890c-3a86b6ad10d3')}] (Background on this error at: https://sqlalche.me/e/20/9h9h).

Traceback (most recent call last): File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1964, in exec_single_context self.dialect.do_execute( File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py", line 942, in do_execute cursor.execute(statement, parameters) File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/psycopg.py", line 594, in execute result = self.await(self._cursor.execute(query, params, **kw)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 132, in await_only return current.parent.switch(awaitable) # type: ignore[no-any-return,attr-defined] # noqa: E501 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 196, in greenlet_spawn value = await result ^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/psycopg/cursor_async.py", line 97, in execute raise ex.with_traceback(None) psycopg.errors.InvalidTextRepresentation: invalid input syntax for type json DETAIL: Token "NaN" is invalid. CONTEXT: JSON data, line 1: ... with sustainability as their\u00a0...", "6": NaN... unnamed portal parameter $2 = '...'

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "/app/.venv/lib/python3.12/site-packages/langflow/base/agents/events.py", line 276, in process_agent_events agent_message, start_time = await tool_handler( ^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/base/agents/events.py", line 175, in handle_on_tool_end agent_message = await send_message_method(message=agent_message) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/custom/custom_component/component.py", line 1113, in send_message stored_message = await self._store_message(message) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/custom/custom_component/component.py", line 1141, in _store_message stored_messages = await astore_message(message, flow_id=flow_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/memory.py", line 266, in astore_message return await aupdate_messages([message]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/memory.py", line 143, in aupdate_messages await session.commit() File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py", line 1011, in commit await greenlet_spawn(self.sync_session.commit) File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 203, in greenlet_spawn result = context.switch(value) ^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 2032, in commit trans.commit(_to_root=True) File "", line 2, in commit File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/state_changes.py", line 139, in _go ret_value = fn(self, *arg, **kw) ^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 1313, in commit self._prepare_impl() File "", line 2, in _prepare_impl File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/state_changes.py", line 139, in _go ret_value = fn(self, *arg, **kw) ^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 1288, in _prepare_impl self.session.flush() File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 4353, in flush self._flush(objects) File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 4488, in _flush with util.safe_reraise(): ^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py", line 146, in exit raise exc_value.with_traceback(exc_tb) File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 4449, in _flush flush_context.execute() File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py", line 466, in execute rec.execute(self) File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py", line 642, in execute util.preloaded.orm_persistence.save_obj( File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py", line 85, in save_obj _emit_update_statements( File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py", line 912, in _emit_update_statements c = connection.execute( ^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1416, in execute return meth( ^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 516, in _execute_on_connection return connection._execute_clauseelement( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1638, in _execute_clauseelement ret = self._execute_context( ^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1843, in _execute_context return self._exec_single_context( ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1983, in _exec_single_context self._handle_dbapi_exception( File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 2352, in _handle_dbapi_exception raise sqlalchemy_exception.with_traceback(exc_info[2]) from e File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1964, in exec_single_context self.dialect.do_execute( File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py", line 942, in do_execute cursor.execute(statement, parameters) File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/psycopg.py", line 594, in execute result = self.await(self._cursor.execute(query, params, **kw)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 132, in await_only return current.parent.switch(awaitable) # type: ignore[no-any-return,attr-defined] # noqa: E501 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 196, in greenlet_spawn value = await result ^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/psycopg/cursor_async.py", line 97, in execute raise ex.with_traceback(None) sqlalchemy.exc.DataError: (psycopg.errors.InvalidTextRepresentation) invalid input syntax for type json DETAIL: Token "NaN" is invalid. CONTEXT: JSON data, line 1: ... with sustainability as their\u00a0...", "6": NaN... unnamed portal parameter $2 = '...' [SQL: UPDATE message SET timestamp=%(timestamp)s::TIMESTAMP WITHOUT TIME ZONE, content_blocks=%(content_blocks)s::JSON WHERE message.id = %(message_id)s::UUID] [parameters: {'timestamp': datetime.datetime(2025, 3, 25, 13, 45, 16, tzinfo=datetime.timezone.utc), 'content_blocks': Json([{'title': 'Agent Steps', 'contents ... (2938 chars)), 'message_id': UUID('135dfd6d-0325-4829-890c-3a86b6ad10d3')}] (Background on this error at: https://sqlalche.me/e/20/9h9h)

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "/app/.venv/lib/python3.12/site-packages/langflow/graph/vertex/base.py", line 757, in _build_results result = await initialize.loading.get_instance_results( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/interface/initialize/loading.py", line 68, in get_instance_results return await build_component(params=custom_params, custom_component=custom_component) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/interface/initialize/loading.py", line 145, in build_component build_results, artifacts = await custom_component.build_results() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/custom/custom_component/component.py", line 892, in build_results return await self._build_with_tracing() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/custom/custom_component/component.py", line 874, in _build_with_tracing results, artifacts = await self._build_results() ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/custom/custom_component/component.py", line 919, in _build_results result = await self._get_output_result(output) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/custom/custom_component/component.py", line 955, in _get_output_result result = await method() if inspect.iscoroutinefunction(method) else await asyncio.to_thread(method) ^^^^^^^^^^^^^^ File "", line 151, in message_response File "/app/.venv/lib/python3.12/site-packages/langflow/base/agents/agent.py", line 162, in run_agent result = await process_agent_events( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.12/site-packages/langflow/base/agents/events.py", line 284, in process_agent_events raise ExceptionWithMessageError(agent_message, str(e)) from e langflow.base.agents.events.ExceptionWithMessageError: (psycopg.errors.InvalidTextRepresentation) invalid input syntax for type json DETAIL: Token "NaN" is invalid. CONTEXT: JSON data, line 1: ... with sustainability as their\u00a0...", "6": NaN... unnamed portal parameter $2 = '...' [SQL: UPDATE message SET timestamp=%(timestamp)s::TIMESTAMP WITHOUT TIME ZONE, content_blocks=%(content_blocks)s::JSON WHERE message.id = %(message_id)s::UUID] [parameters: {'timestamp': datetime.datetime(2025, 3, 25, 13, 45, 16, tzinfo=datetime.timezone.utc), 'content_blocks': Json([{'title': 'Agent Steps', 'contents ... (2938 chars)), 'message_id': UUID('135dfd6d-0325-4829-890c-3a86b6ad10d3')}] (Background on this error at: https://sqlalche.me/e/20/9h9h).

Reproduction

  1. Make an Agent with Google Search API as tool.
  2. Run the Agent component
  3. It tries to send NaN in the content_blocks when storing the message in the database.

Expected behavior

The JSON should be sanitized before sending it to the database.

Who can help?

No response

Operating System

Ubuntu

Langflow Version

1.2.0

Python Version

3.12

Screenshot

No response

Flow File

No response

raprajapati1208 avatar Mar 25 '25 14:03 raprajapati1208

To resolve the issue of an invalid JSON input containing "NaN" being stored in a PostgreSQL database when using the Langflow Agent component, you can modify the _parse_data method to handle "NaN" values. Since JSON does not support "NaN", you can replace "NaN" with a valid JSON value like null before parsing. Here's how you can adjust the code:

def _parse_data(self, input_value) -> str:
    if isinstance(input_value, Message) and isinstance(input_value.text, str):
        # Replace "NaN" with "null" in the JSON string
        return input_value.text.replace("NaN", "null")
    if isinstance(input_value, Data):
        # Convert the data to JSON and replace "NaN" with "null"
        return json.dumps(input_value.data).replace("NaN", "null")
    return str(input_value).replace("NaN", "null")

This modification ensures that any occurrence of "NaN" in the input JSON is replaced with null, which is a valid JSON value, before the JSON parsing process [1].

To continue talking to Dosu, mention @dosu.


Help Dosu learn! Give it feedback: Great Response | Irrelevant Answer | Incorrect Sources | Too Verbose | Hallucination | Bug Report | Other

dosubot[bot] avatar Mar 25 '25 14:03 dosubot[bot]

@dosu

This should have been fixed by Langflow team. Can you tag any member of langflow since I believe a lot of users might be facing this. Also, I would not like to make changes to the core files of langflow.

raprajapati1208 avatar Mar 25 '25 15:03 raprajapati1208

This issue seems to need a closer inspection, @ogabrielluiz could you please take a look?

To continue talking to Dosu, mention @dosu.


Help Dosu learn! Give it feedback: Great Response | Irrelevant Answer | Incorrect Sources | Too Verbose | Hallucination | Bug Report | Other

dosubot[bot] avatar Mar 25 '25 15:03 dosubot[bot]

@ogabrielluiz The issue seems to stem when the Agent Steps in the content_blocks are being stored in the database.

raprajapati1208 avatar Mar 25 '25 15:03 raprajapati1208

Hi, @raprajapati1208. I'm Dosu, and I'm helping the langflow team manage their backlog. I'm marking this issue as stale.

Issue Summary:

  • The issue involves a bug where the Agent component stores an invalid JSON schema with "NaN" in a Postgres database.
  • You prefer not to modify core files and have requested the Langflow team to address the issue.
  • The problem occurs when Agent Steps in the content_blocks are stored in the database.
  • I suggested replacing "NaN" with null as a potential fix.
  • The issue remains unresolved, and further inspection was requested from @ogabrielluiz.

Next Steps:

  • Please confirm if this issue is still relevant to the latest version of the langflow repository by commenting here.
  • If no updates are provided, the issue will be automatically closed in 7 days.

Thank you for your understanding and contribution!

dosubot[bot] avatar Jun 24 '25 16:06 dosubot[bot]

This error is still present in the latest version of LangFlow (1.5.0) using Tavily Search as Tool.

informatica92 avatar Jul 09 '25 06:07 informatica92

I have just discovered that disabling BOTH "Include Image" and "Include Answer" the Tavily Searh tool works as expected:

Image

informatica92 avatar Jul 09 '25 06:07 informatica92

I'm also hiting this error:

Error building Component Agent: (psycopg.errors.InvalidTextRepresentation) invalid input syntax for type json DETAIL: Token "NaN" is invalid. CONTEXT: JSON data, line 1: ...for enhanced logistics efficiency.", "title": null... unnamed portal parameter $2 = '...' [SQL: UPDATE message SET timestamp=%(timestamp)s::TIMESTAMP WITHOUT TIME ZONE, content_blocks=%(content_blocks)s::JSON WHERE message.id = %(message_id)s::UUID] [parameters: {'timestamp': datetime.datetime(2025, 7, 24, 0, 38, 52, tzinfo=datetime.timezone.utc), 'content_blocks': Json([{'title': 'Agent Steps', 'contents ... (18659 chars)), 'message_id': UUID('16adfc26-2832-4410-902d-f5f11518740e')}] (Background on this error at: https://sqlalche.me/e/20/9h9h).


Env: Docker Image Lastest - with Postgres Version: 1.5.0.post1

alan-araya avatar Jul 24 '25 00:07 alan-araya

We just hit this as well. I can confirm that disabling the Tavily image results seem to fix it for now.

chris-emerson avatar Jul 24 '25 12:07 chris-emerson