Get historical conversation records? #20322

Closed
opened 2026-02-21 20:06:49 -05:00 by yindo · 8 comments
Owner

Originally created by @lhxxrds on GitHub (Nov 14, 2025).

Self Checks

  • I have read the Contributing Guide and Language Policy.
  • This is only for bug report, if you would like to ask a question, please head to Discussions.
  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report, otherwise it will be closed.
  • 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • Please do not modify this template :) and fill in all the required fields.

Dify version

1.2

Cloud or Self Hosted

Self Hosted (Docker)

Steps to reproduce

How to obtain the session record of a certain user through the python method?

✔️ Expected Behavior

How to obtain the session record of a certain user through the python method?

Actual Behavior

How to obtain the session record of a certain user through the python method?

Originally created by @lhxxrds on GitHub (Nov 14, 2025). ### Self Checks - [x] I have read the [Contributing Guide](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md) and [Language Policy](https://github.com/langgenius/dify/issues/1542). - [x] This is only for bug report, if you would like to ask a question, please head to [Discussions](https://github.com/langgenius/dify/discussions/categories/general). - [x] I have searched for existing issues [search for existing issues](https://github.com/langgenius/dify/issues), including closed ones. - [x] I confirm that I am using English to submit this report, otherwise it will be closed. - [x] 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :) - [x] Please do not modify this template :) and fill in all the required fields. ### Dify version 1.2 ### Cloud or Self Hosted Self Hosted (Docker) ### Steps to reproduce How to obtain the session record of a certain user through the python method? ### ✔️ Expected Behavior How to obtain the session record of a certain user through the python method? ### ❌ Actual Behavior **How to obtain the session record of a certain user through the python method?**
yindo added the 🙋‍♂️ questionoutdated labels 2026-02-21 20:06:49 -05:00
yindo closed this issue 2026-02-21 20:06:50 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Nov 14, 2025):

You can retrieve a user's historical conversation records in Dify (v1.2, self-hosted) using Python via the official API or the Python SDK.

Using the Python SDK:

Dify provides a Python client (dify_client) with methods to fetch conversations and messages for a user. Here’s a minimal example:

from dify_client import ChatClient

# Initialize the client with your API key and base URL
client = ChatClient(
    api_key="YOUR_DIFY_API_KEY",
    base_url="http://your-dify-server/api/v1"  # Adjust if needed
)

user_id = "the_user_id"  # Replace with the actual user identifier

# Get all conversations for the user
conversations = client.get_conversations(user=user_id)
print(conversations)

# For a specific conversation, get its messages
conversation_id = "the_conversation_id"  # Replace with actual conversation ID
messages = client.get_conversation_messages(user=user_id, conversation_id=conversation_id)
print(messages)

The SDK handles authentication via the API key and uses the /conversations and /messages endpoints under the hood. You can paginate and filter results as needed.
Reference: Python SDK methods

Using direct API calls:

You can also use the requests library to call the API directly:

import requests

api_key = "YOUR_DIFY_API_KEY"
base_url = "http://your-dify-server/api/v1"
user_id = "the_user_id"

headers = {"Authorization": f"Bearer {api_key}"}

# Get conversations
resp = requests.get(f"{base_url}/conversations", params={"user": user_id}, headers=headers)
print(resp.json())

# Get messages for a conversation
conversation_id = "the_conversation_id"
resp = requests.get(f"{base_url}/messages", params={"user": user_id, "conversation_id": conversation_id}, headers=headers)
print(resp.json())

Make sure the user has the necessary permissions and that you use the correct API key.
Reference: API endpoints and permissions

If you need to filter by session or end user, use the user parameter (which maps to from_end_user_id or from_account_id in the database). The data model and API are designed for this use case.

Let me know if you need help with user IDs or conversation IDs!

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

@dosubot[bot] commented on GitHub (Nov 14, 2025): <!-- Answer --> You can retrieve a user's historical conversation records in Dify (v1.2, self-hosted) using Python via the official API or the Python SDK. **Using the Python SDK:** Dify provides a Python client (`dify_client`) with methods to fetch conversations and messages for a user. Here’s a minimal example: ```python from dify_client import ChatClient # Initialize the client with your API key and base URL client = ChatClient( api_key="YOUR_DIFY_API_KEY", base_url="http://your-dify-server/api/v1" # Adjust if needed ) user_id = "the_user_id" # Replace with the actual user identifier # Get all conversations for the user conversations = client.get_conversations(user=user_id) print(conversations) # For a specific conversation, get its messages conversation_id = "the_conversation_id" # Replace with actual conversation ID messages = client.get_conversation_messages(user=user_id, conversation_id=conversation_id) print(messages) ``` The SDK handles authentication via the API key and uses the `/conversations` and `/messages` endpoints under the hood. You can paginate and filter results as needed. [Reference: Python SDK methods](https://github.com/langgenius/dify/blob/15fbedfcadd46f0e78a165adf3b8047eba2de94f/sdks/python-client/dify_client/client.py#L19-L231) **Using direct API calls:** You can also use the `requests` library to call the API directly: ```python import requests api_key = "YOUR_DIFY_API_KEY" base_url = "http://your-dify-server/api/v1" user_id = "the_user_id" headers = {"Authorization": f"Bearer {api_key}"} # Get conversations resp = requests.get(f"{base_url}/conversations", params={"user": user_id}, headers=headers) print(resp.json()) # Get messages for a conversation conversation_id = "the_conversation_id" resp = requests.get(f"{base_url}/messages", params={"user": user_id, "conversation_id": conversation_id}, headers=headers) print(resp.json()) ``` Make sure the user has the necessary permissions and that you use the correct API key. [Reference: API endpoints and permissions](https://github.com/langgenius/dify/blob/15fbedfcadd46f0e78a165adf3b8047eba2de94f/api/controllers/console/app/message.py#L30-L130) If you need to filter by session or end user, use the `user` parameter (which maps to `from_end_user_id` or `from_account_id` in the database). The data model and API are designed for this use case. Let me know if you need help with user IDs or conversation IDs! <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/54c4aef5-0836-4002-b41a-7ba84c9f5178?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/54c4aef5-0836-4002-b41a-7ba84c9f5178?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/54c4aef5-0836-4002-b41a-7ba84c9f5178?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/54c4aef5-0836-4002-b41a-7ba84c9f5178?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/54c4aef5-0836-4002-b41a-7ba84c9f5178?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/54c4aef5-0836-4002-b41a-7ba84c9f5178?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/54c4aef5-0836-4002-b41a-7ba84c9f5178?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/6088a4f4-073a-43f3-b3d4-4f06fb0c05a0/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/langgenius/dify/issues/28220)
Author
Owner

@lhxxrds commented on GitHub (Nov 14, 2025):

I want to implement the acquisition of the current user's historical records in the dify data stream, using the code execution node in the data stream. Could you please tell me exactly how to write it?

@lhxxrds commented on GitHub (Nov 14, 2025): I want to implement the acquisition of the current user's historical records in the dify data stream, using the code execution node in the data stream. Could you please tell me exactly how to write it?
Author
Owner

@lhxxrds commented on GitHub (Nov 14, 2025):

I want to implement the acquisition of the current user's historical records in the dify data stream, using the code execution node in the data stream. Could you please tell me exactly how to write it?n @dosu.

@lhxxrds commented on GitHub (Nov 14, 2025): I want to implement the acquisition of the current user's historical records in the dify data stream, using the code execution node in the data stream. Could you please tell me exactly how to write it?n [@dosu](https://go.dosu.dev/dosubot).
Author
Owner

@dosubot[bot] commented on GitHub (Nov 14, 2025):

To fetch the current user's historical conversation records in a Dify data stream using a code execution node, you need to:

  1. Pass the user_id (and optionally conversation_id or session_id) into the code execution node as a variable from your workflow.
  2. Write Python code in the node that makes an authenticated HTTP request to Dify's API to retrieve the records.

Here’s a template for the code execution node (Python):

import requests

# These variables should be mapped from your workflow context
api_key = "YOUR_DIFY_API_KEY"  # Store securely, e.g., as an environment variable
base_url = "http://your-dify-server/api/v1"
user_id = inputs.get("user_id")  # 'inputs' is the variable mapping from workflow
conversation_id = inputs.get("conversation_id")  # Optional, if available

headers = {"Authorization": f"Bearer {api_key}"}

# Get all conversations for the user
resp = requests.get(f"{base_url}/conversations", params={"user": user_id}, headers=headers)
conversations = resp.json()

# If you want messages from a specific conversation:
if conversation_id:
    resp = requests.get(
        f"{base_url}/messages",
        params={"user": user_id, "conversation_id": conversation_id},
        headers=headers
    )
    messages = resp.json()
else:
    messages = None

# Output the result (adapt as needed for your workflow)
return {
    "conversations": conversations,
    "messages": messages
}

Make sure your workflow passes the correct user/session context into the node. The code execution node runs in a sandbox, so only mapped variables and standard Python libraries are available. If you encounter issues with the /messages endpoint, try /chat-messages as an alternative, especially if you're on Dify v1.2.0 and have seen related errors source.

If your workflow doesn't provide conversation_id, you can list all conversations for the user and select the relevant one. Always ensure your API key and permissions are set correctly.

Let me know if you need help with variable mapping or handling authentication!

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

@dosubot[bot] commented on GitHub (Nov 14, 2025): <!-- Answer --> To fetch the current user's historical conversation records in a Dify data stream using a code execution node, you need to: 1. Pass the `user_id` (and optionally `conversation_id` or `session_id`) into the code execution node as a variable from your workflow. 2. Write Python code in the node that makes an authenticated HTTP request to Dify's API to retrieve the records. Here’s a template for the code execution node (Python): ```python import requests # These variables should be mapped from your workflow context api_key = "YOUR_DIFY_API_KEY" # Store securely, e.g., as an environment variable base_url = "http://your-dify-server/api/v1" user_id = inputs.get("user_id") # 'inputs' is the variable mapping from workflow conversation_id = inputs.get("conversation_id") # Optional, if available headers = {"Authorization": f"Bearer {api_key}"} # Get all conversations for the user resp = requests.get(f"{base_url}/conversations", params={"user": user_id}, headers=headers) conversations = resp.json() # If you want messages from a specific conversation: if conversation_id: resp = requests.get( f"{base_url}/messages", params={"user": user_id, "conversation_id": conversation_id}, headers=headers ) messages = resp.json() else: messages = None # Output the result (adapt as needed for your workflow) return { "conversations": conversations, "messages": messages } ``` Make sure your workflow passes the correct user/session context into the node. The code execution node runs in a sandbox, so only mapped variables and standard Python libraries are available. If you encounter issues with the `/messages` endpoint, try `/chat-messages` as an alternative, especially if you're on Dify v1.2.0 and have seen related errors [source](https://github.com/langgenius/dify/issues/18368). If your workflow doesn't provide `conversation_id`, you can list all conversations for the user and select the relevant one. Always ensure your API key and permissions are set correctly. Let me know if you need help with variable mapping or handling authentication! <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/ce4d5a75-0f20-451c-8573-238561b41d0f?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/ce4d5a75-0f20-451c-8573-238561b41d0f?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/ce4d5a75-0f20-451c-8573-238561b41d0f?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/ce4d5a75-0f20-451c-8573-238561b41d0f?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/ce4d5a75-0f20-451c-8573-238561b41d0f?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/ce4d5a75-0f20-451c-8573-238561b41d0f?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/ce4d5a75-0f20-451c-8573-238561b41d0f?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/6088a4f4-073a-43f3-b3d4-4f06fb0c05a0/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/langgenius/dify/issues/28220)
Author
Owner

@AuditAIH commented on GitHub (Nov 14, 2025):

@lhxxrds :SELECT id, app_id, model_provider, model_id, override_model_configs, conversation_id, inputs, query, message, message_tokens, message_unit_price, answer, answer_tokens, answer_unit_price, provider_response_latency, total_price, currency, from_source, from_end_user_id, from_account_id, created_at, updated_at, agent_based, message_price_unit, answer_price_unit, workflow_run_id, status, error, message_metadata, invoke_from, parent_message_id, app_mode
FROM public.messages;
where from_account_id = {{#sys.conversation_id#}}

Image
@AuditAIH commented on GitHub (Nov 14, 2025): @lhxxrds :SELECT id, app_id, model_provider, model_id, override_model_configs, conversation_id, inputs, query, message, message_tokens, message_unit_price, answer, answer_tokens, answer_unit_price, provider_response_latency, total_price, currency, from_source, from_end_user_id, from_account_id, created_at, updated_at, agent_based, message_price_unit, answer_price_unit, workflow_run_id, status, error, message_metadata, invoke_from, parent_message_id, app_mode FROM public.messages; where from_account_id = {{#sys.conversation_id#}} <img width="2446" height="994" alt="Image" src="https://github.com/user-attachments/assets/e896e5a9-db65-4205-8307-8e3dba126f40" />
Author
Owner

@lhxxrds commented on GitHub (Nov 14, 2025):

@AuditAIH Do you mean it must be obtained through sql statements?I want to implement multi-round dialogues in dify, and when building the data stream, obtain the last question raised by the user or the questions raised in the first five times.mention @dosu.

@lhxxrds commented on GitHub (Nov 14, 2025): @AuditAIH Do you mean it must be obtained through sql statements?I want to implement multi-round dialogues in dify, and when building the data stream, obtain the last question raised by the user or the questions raised in the first five times.mention [@dosu](https://go.dosu.dev/dosubot).
Author
Owner

@AuditAIH commented on GitHub (Nov 14, 2025):

@AuditAIH Do you mean it must be obtained through sql statements?I want to implement multi-round dialogues in dify, and when building the data stream, obtain the last question raised by the user or the questions raised in the first five times.mention @dosu.
@lhxxrds
Dify会在发布为/chat页面的时候,可以开启多个对话窗口提问,如果你想跨对话窗口,跨工作流的时候,可以用SQL的方式,如果你想仅获取当前工作流的对话的时候,你可以开启历史对话(这里的历史对话会附带工具的输出)或者用变量赋值,获取你想要的对话。增加一个code节点,提取你想要的前5次或者最后3次。抱歉,我用英文很难描述清楚,你参考下。

Image Image

测试历史对话.yaml

@AuditAIH commented on GitHub (Nov 14, 2025): > [@AuditAIH](https://github.com/AuditAIH) Do you mean it must be obtained through sql statements?I want to implement multi-round dialogues in dify, and when building the data stream, obtain the last question raised by the user or the questions raised in the first five times.mention [@dosu](https://go.dosu.dev/dosubot). @lhxxrds Dify会在发布为/chat页面的时候,可以开启多个对话窗口提问,如果你想跨对话窗口,跨工作流的时候,可以用SQL的方式,如果你想仅获取当前工作流的对话的时候,你可以开启历史对话(这里的历史对话会附带工具的输出)或者用变量赋值,获取你想要的对话。增加一个code节点,提取你想要的前5次或者最后3次。抱歉,我用英文很难描述清楚,你参考下。 <img width="2446" height="908" alt="Image" src="https://github.com/user-attachments/assets/d101e527-4500-49e7-a0c5-f33ceed05b9b" /> <img width="2173" height="966" alt="Image" src="https://github.com/user-attachments/assets/0509c10b-7618-44df-b36a-c3fcbf0fe8b6" /> [测试历史对话.yaml](https://github.com/user-attachments/files/23542880/default.yaml)
Author
Owner

@lhxxrds commented on GitHub (Nov 14, 2025):

@AuditAIH 使用中文也可以回答,我知道记忆部分记忆窗口,但是不是我想要的,我想直接在数据流中获得对应的历史记录(仅仅用户问题)

@lhxxrds commented on GitHub (Nov 14, 2025): @AuditAIH 使用中文也可以回答,我知道记忆部分记忆窗口,但是不是我想要的,我想直接在数据流中获得对应的历史记录(仅仅用户问题)
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: langgenius/dify#20322