How do I get the contents of the "usage" in the json string output under the LLM node? #5305

Closed
opened 2026-02-21 18:10:20 -05:00 by yindo · 10 comments
Owner

Originally created by @Alickx on GitHub (Aug 29, 2024).

Self Checks

  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report (我已阅读并同意 Language Policy).
  • [FOR CHINESE USERS] 请务必使用英文提交 Issue,否则会被关闭。谢谢!:)
  • Please do not modify this template :) and fill in all the required fields.

1. Is this request related to a challenge you're experiencing? Tell me about your story.

{
  "text": "xxxxx",
  "usage": {
    "prompt_tokens": 1974,
    "prompt_unit_price": "5.00",
    "prompt_price_unit": "0.000001",
    "prompt_price": "0.0098700",
    "completion_tokens": 60,
    "completion_unit_price": "15.00",
    "completion_price_unit": "0.000001",
    "completion_price": "0.0009000",
    "total_tokens": 2034,
    "total_price": "0.0107700",
    "currency": "USD",
    "latency": 2.0280010253190994
  }
}

I want to extract the total_price of usage to the next node for processing, but I found that there seems to be no way to get it?

2. Additional context or comments

No response

3. Can you help us with this feature?

  • I am interested in contributing to this feature.
Originally created by @Alickx on GitHub (Aug 29, 2024). ### Self Checks - [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 (我已阅读并同意 [Language Policy](https://github.com/langgenius/dify/issues/1542)). - [X] [FOR CHINESE USERS] 请务必使用英文提交 Issue,否则会被关闭。谢谢!:) - [X] Please do not modify this template :) and fill in all the required fields. ### 1. Is this request related to a challenge you're experiencing? Tell me about your story. ```json { "text": "xxxxx", "usage": { "prompt_tokens": 1974, "prompt_unit_price": "5.00", "prompt_price_unit": "0.000001", "prompt_price": "0.0098700", "completion_tokens": 60, "completion_unit_price": "15.00", "completion_price_unit": "0.000001", "completion_price": "0.0009000", "total_tokens": 2034, "total_price": "0.0107700", "currency": "USD", "latency": 2.0280010253190994 } } ``` I want to extract the total_price of usage to the next node for processing, but I found that there seems to be no way to get it? ### 2. Additional context or comments _No response_ ### 3. Can you help us with this feature? - [ ] I am interested in contributing to this feature.
yindo added the 💪 enhancement label 2026-02-21 18:10:20 -05:00
yindo closed this issue 2026-02-21 18:10:20 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Aug 29, 2024):

I found two similar discussions that might be relevant to your question:

  1. How do I get the contents of the "usage" in the json string output under the LLM node? [1]
  2. Add Usage Information Output to LLM Node in Workflow [2]

To get the contents of the "usage" in the JSON string output under the LLM node, you can access it from the LLMResult object returned by the _handle_generate_response method. Here is the relevant part of the code that shows how the "usage" is calculated and included in the LLMResult:

def _handle_generate_response(
    self,
    model: str,
    credentials: dict,
    completion_type: LLMMode,
    response: requests.Response,
    prompt_messages: list[PromptMessage],
) -> LLMResult:
    response_json = response.json()

    if completion_type is LLMMode.CHAT:
        message = response_json.get("message", {})
        response_content = message.get("content", "")
    else:
        response_content = response_json["response"]

    assistant_message = AssistantPromptMessage(content=response_content)

    if "prompt_eval_count" in response_json and "eval_count" in response_json:
        prompt_tokens = response_json["prompt_eval_count"]
        completion_tokens = response_json["eval_count"]
    else:
        prompt_tokens = self._get_num_tokens_by_gpt2(prompt_messages[0].content)
        completion_tokens = self._get_num_tokens_by_gpt2(assistant_message.content)

    usage = self._calc_response_usage(
        model, credentials, prompt_tokens, completion_tokens
    )

    result = LLMResult(
        model=response_json["model"],
        prompt_messages=prompt_messages,
        message=assistant_message,
        usage=usage,
    )

    return result

In this method, the usage is calculated and included in the LLMResult object. To access the "usage" contents, you would retrieve it from the LLMResult object like this:

llm_result = self._handle_generate_response(model, credentials, completion_type, response, prompt_messages)
usage_contents = llm_result.usage
total_price = usage_contents.total_price

This total_price will contain the total price from the usage information in the JSON string output under the LLM node [3].

To continue talking to Dosu, mention @dosu.

@dosubot[bot] commented on GitHub (Aug 29, 2024): <!-- Answer --> I found two similar discussions that might be relevant to your question: 1. [How do I get the contents of the "usage" in the json string output under the LLM node?](https://github.com/langgenius/dify/discussions/7794) <sup>[[1]](https://github.com/langgenius/dify/discussions/7794)</sup> 2. [Add Usage Information Output to LLM Node in Workflow](https://github.com/langgenius/dify/discussions/3775) <sup>[[2]](https://github.com/langgenius/dify/discussions/3775)</sup> To get the contents of the "usage" in the JSON string output under the LLM node, you can access it from the `LLMResult` object returned by the `_handle_generate_response` method. Here is the relevant part of the code that shows how the "usage" is calculated and included in the `LLMResult`: ```python def _handle_generate_response( self, model: str, credentials: dict, completion_type: LLMMode, response: requests.Response, prompt_messages: list[PromptMessage], ) -> LLMResult: response_json = response.json() if completion_type is LLMMode.CHAT: message = response_json.get("message", {}) response_content = message.get("content", "") else: response_content = response_json["response"] assistant_message = AssistantPromptMessage(content=response_content) if "prompt_eval_count" in response_json and "eval_count" in response_json: prompt_tokens = response_json["prompt_eval_count"] completion_tokens = response_json["eval_count"] else: prompt_tokens = self._get_num_tokens_by_gpt2(prompt_messages[0].content) completion_tokens = self._get_num_tokens_by_gpt2(assistant_message.content) usage = self._calc_response_usage( model, credentials, prompt_tokens, completion_tokens ) result = LLMResult( model=response_json["model"], prompt_messages=prompt_messages, message=assistant_message, usage=usage, ) return result ``` In this method, the `usage` is calculated and included in the `LLMResult` object. To access the "usage" contents, you would retrieve it from the `LLMResult` object like this: ```python llm_result = self._handle_generate_response(model, credentials, completion_type, response, prompt_messages) usage_contents = llm_result.usage total_price = usage_contents.total_price ``` This `total_price` will contain the total price from the usage information in the JSON string output under the LLM node <sup>[[3]](https://github.com/langgenius/dify/blob/main/api/core/model_runtime/model_providers/ollama/llm/llm.py)</sup>. <!-- Dosu Comment Footer --> *To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
Author
Owner

@dosubot[bot] commented on GitHub (Aug 29, 2024):

Currently, the existing web interface does not provide a direct way to extract the total_price from the usage section of the JSON output under the LLM node. You would need to modify the backend code to expose this information or handle it programmatically as described earlier. If you need this feature, consider submitting a feature request or contributing to the repository.

To continue talking to Dosu, mention @dosu.

@dosubot[bot] commented on GitHub (Aug 29, 2024): <!-- Answer --> Currently, the existing web interface does not provide a direct way to extract the `total_price` from the `usage` section of the JSON output under the LLM node. You would need to modify the backend code to expose this information or handle it programmatically as described earlier. If you need this feature, consider submitting a feature request or contributing to the repository. <!-- Dosu Comment Footer --> *To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
Author
Owner

@Alickx commented on GitHub (Aug 29, 2024):

我发现了两个可能与您的问题相关的类似讨论:

  1. 如何获取LLM节点下输出的json字符串中“usage”的内容? [1]
  2. 在工作流中添加使用信息输出到LLM节点 [2]

要获取 LLM 节点下 JSON 字符串输出中的“使用情况”内容,可以从LLMResult_handle_generate_response方法返回的对象中访问它。以下是代码的相关部分,显示了如何计算“使用情况”并将其包含在内LLMResult

def _handle_generate_response(
    self,
    model: str,
    credentials: dict,
    completion_type: LLMMode,
    response: requests.Response,
    prompt_messages: list[PromptMessage],
) -> LLMResult:
    response_json = response.json()

    if completion_type is LLMMode.CHAT:
        message = response_json.get("message", {})
        response_content = message.get("content", "")
    else:
        response_content = response_json["response"]

    assistant_message = AssistantPromptMessage(content=response_content)

    if "prompt_eval_count" in response_json and "eval_count" in response_json:
        prompt_tokens = response_json["prompt_eval_count"]
        completion_tokens = response_json["eval_count"]
    else:
        prompt_tokens = self._get_num_tokens_by_gpt2(prompt_messages[0].content)
        completion_tokens = self._get_num_tokens_by_gpt2(assistant_message.content)

    usage = self._calc_response_usage(
        model, credentials, prompt_tokens, completion_tokens
    )

    result = LLMResult(
        model=response_json["model"],
        prompt_messages=prompt_messages,
        message=assistant_message,
        usage=usage,
    )

    return result

在此方法中,usage计算并包含在LLMResult对象中。要访问“使用情况”内容,您可以LLMResult像这样从对象中检索它:

llm_result = self._handle_generate_response(model, credentials, completion_type, response, prompt_messages)
usage_contents = llm_result.usage
total_price = usage_contents.total_price

这将包含 LLM 节点[3]total_price下的 JSON 字符串输出中的使用信息的总价格。

要继续与Dosu交谈,请提及@dosu。

Is it available on the existing web interface?

@Alickx commented on GitHub (Aug 29, 2024): > 我发现了两个可能与您的问题相关的类似讨论: > > 1. [如何获取LLM节点下输出的json字符串中“usage”的内容?](https://github.com/langgenius/dify/discussions/7794) [[1]](https://github.com/langgenius/dify/discussions/7794) > 2. [在工作流中添加使用信息输出到LLM节点](https://github.com/langgenius/dify/discussions/3775) [[2]](https://github.com/langgenius/dify/discussions/3775) > > 要获取 LLM 节点下 JSON 字符串输出中的“使用情况”内容,可以从`LLMResult`该`_handle_generate_response`方法返回的对象中访问它。以下是代码的相关部分,显示了如何计算“使用情况”并将其包含在内`LLMResult`: > > ```python > def _handle_generate_response( > self, > model: str, > credentials: dict, > completion_type: LLMMode, > response: requests.Response, > prompt_messages: list[PromptMessage], > ) -> LLMResult: > response_json = response.json() > > if completion_type is LLMMode.CHAT: > message = response_json.get("message", {}) > response_content = message.get("content", "") > else: > response_content = response_json["response"] > > assistant_message = AssistantPromptMessage(content=response_content) > > if "prompt_eval_count" in response_json and "eval_count" in response_json: > prompt_tokens = response_json["prompt_eval_count"] > completion_tokens = response_json["eval_count"] > else: > prompt_tokens = self._get_num_tokens_by_gpt2(prompt_messages[0].content) > completion_tokens = self._get_num_tokens_by_gpt2(assistant_message.content) > > usage = self._calc_response_usage( > model, credentials, prompt_tokens, completion_tokens > ) > > result = LLMResult( > model=response_json["model"], > prompt_messages=prompt_messages, > message=assistant_message, > usage=usage, > ) > > return result > ``` > > 在此方法中,`usage`计算并包含在`LLMResult`对象中。要访问“使用情况”内容,您可以`LLMResult`像这样从对象中检索它: > > ```python > llm_result = self._handle_generate_response(model, credentials, completion_type, response, prompt_messages) > usage_contents = llm_result.usage > total_price = usage_contents.total_price > ``` > > 这将包含 LLM 节点[[3]](https://github.com/langgenius/dify/blob/main/api/core/model_runtime/model_providers/ollama/llm/llm.py)`total_price`下的 JSON 字符串输出中的使用信息的总价格。[](https://github.com/langgenius/dify/blob/main/api/core/model_runtime/model_providers/ollama/llm/llm.py) > > _要继续与[Dosu](https://dosu.dev)交谈,请提及@dosu。_ Is it available on the existing web interface?
Author
Owner

@dosubot[bot] commented on GitHub (Aug 29, 2024):

Yes, the usage information is exposed through the Usage component in the web/app/components/billing/annotation-full/usage.tsx file. This component uses the UsageInfo component to display the usage and total values from the plan object provided by the useProviderContext hook.

Here is the relevant code snippet:

const {
  usage,
  total,
} = plan;

return (
  <UsageInfo
    className={className}
    Icon={MessageFastPlus}
    name={t('billing.annotatedResponse.quotaTitle')}
    usage={usage.annotatedResponse}
    total={total.annotatedResponse}
  />
);

This component displays the usage information, including the total_price, on the web interface [1].

To continue talking to Dosu, mention @dosu.

@dosubot[bot] commented on GitHub (Aug 29, 2024): <!-- Answer --> Yes, the `usage` information is exposed through the `Usage` component in the `web/app/components/billing/annotation-full/usage.tsx` file. This component uses the `UsageInfo` component to display the `usage` and `total` values from the `plan` object provided by the `useProviderContext` hook. Here is the relevant code snippet: ```tsx const { usage, total, } = plan; return ( <UsageInfo className={className} Icon={MessageFastPlus} name={t('billing.annotatedResponse.quotaTitle')} usage={usage.annotatedResponse} total={total.annotatedResponse} /> ); ``` This component displays the `usage` information, including the `total_price`, on the web interface <sup>[[1]](https://github.com/langgenius/dify/blob/main/web/app/components/billing/annotation-full/usage.tsx)</sup>. <!-- Dosu Comment Footer --> *To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
Author
Owner

@Alickx commented on GitHub (Aug 29, 2024):

I'm not sure I understand, but I'm wondering if it's possible to get the usage data returned under the LLM node in some way directly from the web interface, rather than modifying the source code.

@Alickx commented on GitHub (Aug 29, 2024): I'm not sure I understand, but I'm wondering if it's possible to get the usage data returned under the LLM node in some way directly from the web interface, rather than modifying the source code.
Author
Owner

@dosubot[bot] commented on GitHub (Aug 29, 2024):

Yes, there is an existing API endpoint in the Dify web interface that provides the usage data directly from the LLM node. The _run method in the LLMNode class returns the usage data as part of the outputs in the NodeRunResult [1].

Here is the relevant code snippet:

outputs = {
    'text': result_text,
    'usage': jsonable_encoder(usage),
    'finish_reason': finish_reason
}

return NodeRunResult(
    status=WorkflowNodeExecutionStatus.SUCCEEDED,
    inputs=node_inputs,
    process_data=process_data,
    outputs=outputs,
    metadata={
        NodeRunMetadataKey.TOTAL_TOKENS: usage.total_tokens,
        NodeRunMetadataKey.TOTAL_PRICE: usage.total_price,
        NodeRunMetadataKey.CURRENCY: usage.currency
    }
)

This indicates that the usage data is included in the outputs of the NodeRunResult. You can access this data through the API without modifying the source code.

To continue talking to Dosu, mention @dosu.

@dosubot[bot] commented on GitHub (Aug 29, 2024): <!-- Answer --> Yes, there is an existing API endpoint in the Dify web interface that provides the `usage` data directly from the LLM node. The `_run` method in the `LLMNode` class returns the `usage` data as part of the `outputs` in the `NodeRunResult` <sup>[[1]](https://github.com/langgenius/dify/blob/main/api/core/workflow/nodes/llm/llm_node.py)</sup>. Here is the relevant code snippet: ```python outputs = { 'text': result_text, 'usage': jsonable_encoder(usage), 'finish_reason': finish_reason } return NodeRunResult( status=WorkflowNodeExecutionStatus.SUCCEEDED, inputs=node_inputs, process_data=process_data, outputs=outputs, metadata={ NodeRunMetadataKey.TOTAL_TOKENS: usage.total_tokens, NodeRunMetadataKey.TOTAL_PRICE: usage.total_price, NodeRunMetadataKey.CURRENCY: usage.currency } ) ``` This indicates that the `usage` data is included in the `outputs` of the `NodeRunResult`. You can access this data through the API without modifying the source code. <!-- Dosu Comment Footer --> *To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
Author
Owner

@Alickx commented on GitHub (Aug 29, 2024):

Yes, there is an existing API endpoint in the Dify web interface that provides the usage data directly from the LLM node. The _run method in the LLMNode class returns the usage data as part of the outputs in the NodeRunResult [1].

Here is the relevant code snippet:

outputs = {
    'text': result_text,
    'usage': jsonable_encoder(usage),
    'finish_reason': finish_reason
}

return NodeRunResult(
    status=WorkflowNodeExecutionStatus.SUCCEEDED,
    inputs=node_inputs,
    process_data=process_data,
    outputs=outputs,
    metadata={
        NodeRunMetadataKey.TOTAL_TOKENS: usage.total_tokens,
        NodeRunMetadataKey.TOTAL_PRICE: usage.total_price,
        NodeRunMetadataKey.CURRENCY: usage.currency
    }
)

This indicates that the usage data is included in the outputs of the NodeRunResult. You can access this data through the API without modifying the source code.

To continue talking to Dosu, mention @dosu.

I want to know what API endpoint

@Alickx commented on GitHub (Aug 29, 2024): > Yes, there is an existing API endpoint in the Dify web interface that provides the `usage` data directly from the LLM node. The `_run` method in the `LLMNode` class returns the `usage` data as part of the `outputs` in the `NodeRunResult` [[1]](https://github.com/langgenius/dify/blob/main/api/core/workflow/nodes/llm/llm_node.py). > > Here is the relevant code snippet: > > ```python > outputs = { > 'text': result_text, > 'usage': jsonable_encoder(usage), > 'finish_reason': finish_reason > } > > return NodeRunResult( > status=WorkflowNodeExecutionStatus.SUCCEEDED, > inputs=node_inputs, > process_data=process_data, > outputs=outputs, > metadata={ > NodeRunMetadataKey.TOTAL_TOKENS: usage.total_tokens, > NodeRunMetadataKey.TOTAL_PRICE: usage.total_price, > NodeRunMetadataKey.CURRENCY: usage.currency > } > ) > ``` > > This indicates that the `usage` data is included in the `outputs` of the `NodeRunResult`. You can access this data through the API without modifying the source code. > > _To continue talking to [Dosu](https://dosu.dev), mention @dosu._ I want to know what API endpoint
Author
Owner

@dosubot[bot] commented on GitHub (Aug 29, 2024):

The exact URL path for the API endpoint that returns the NodeRunResult including the usage data is:

/apps/<uuid:app_id>/workflow-runs/<uuid:run_id>/node-executions

This is defined in the WorkflowRunNodeExecutionListApi class [1].

To continue talking to Dosu, mention @dosu.

@dosubot[bot] commented on GitHub (Aug 29, 2024): <!-- Answer --> The exact URL path for the API endpoint that returns the `NodeRunResult` including the `usage` data is: ``` /apps/<uuid:app_id>/workflow-runs/<uuid:run_id>/node-executions ``` This is defined in the `WorkflowRunNodeExecutionListApi` class <sup>[[1]](https://github.com/langgenius/dify/blob/main/api/controllers/console/app/workflow_run.py)</sup>. <!-- Dosu Comment Footer --> *To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
Author
Owner

@Alickx commented on GitHub (Aug 29, 2024):

The exact URL path for the API endpoint that returns the NodeRunResult including the usage data is:

/apps/<uuid:app_id>/workflow-runs/<uuid:run_id>/node-executions

This is defined in the WorkflowRunNodeExecutionListApi class [1].

To continue talking to Dosu, mention @dosu.

How do I call this api endpoint in a workflow to get the data? How to get the value uuid:run_id in workflow?

@Alickx commented on GitHub (Aug 29, 2024): > The exact URL path for the API endpoint that returns the `NodeRunResult` including the `usage` data is: > > ``` > /apps/<uuid:app_id>/workflow-runs/<uuid:run_id>/node-executions > ``` > > This is defined in the `WorkflowRunNodeExecutionListApi` class [[1]](https://github.com/langgenius/dify/blob/main/api/controllers/console/app/workflow_run.py). > > _To continue talking to [Dosu](https://dosu.dev), mention @dosu._ How do I call this api endpoint in a workflow to get the data? How to get the value <uuid:run_id> in workflow?
Author
Owner

@dosubot[bot] commented on GitHub (Aug 29, 2024):

To call the /apps/<uuid:app_id>/workflow-runs/<uuid:run_id>/node-executions API endpoint in a workflow and get the value <uuid:run_id>, you can follow these steps:

  1. Get the Workflow Run List: First, you need to get the list of workflow runs to obtain the run_id. You can do this by calling the /apps/<uuid:app_id>/workflow-runs endpoint.

  2. Extract the run_id: From the response of the workflow run list, extract the run_id you need.

  3. Call the Node Executions Endpoint: Use the extracted run_id to call the /apps/<uuid:app_id>/workflow-runs/<uuid:run_id>/node-executions endpoint.

Here is an example of how you can achieve this in Python using the requests library:

import requests

# Define the base URL and app_id
base_url = "https://your-dify-instance.com"
app_id = "your-app-id"

# Step 1: Get the workflow run list
workflow_runs_url = f"{base_url}/apps/{app_id}/workflow-runs"
response = requests.get(workflow_runs_url, headers={"Authorization": "Bearer your-access-token"})
workflow_runs = response.json()

# Step 2: Extract the run_id (assuming you want the first run_id in the list)
run_id = workflow_runs['data'][0]['id']

# Step 3: Call the node executions endpoint
node_executions_url = f"{base_url}/apps/{app_id}/workflow-runs/{run_id}/node-executions"
response = requests.get(node_executions_url, headers={"Authorization": "Bearer your-access-token"})
node_executions = response.json()

# Print the node executions data
print(node_executions)

In this example:

  • Replace your-dify-instance.com with the actual base URL of your Dify instance.
  • Replace your-app-id with the actual app_id of your application.
  • Replace your-access-token with the actual access token for authentication.

This code will first fetch the list of workflow runs, extract the run_id from the first workflow run in the list, and then use that run_id to fetch the node executions.

Additionally, if you are using the Dify platform's internal services, you can utilize the WorkflowRunService class to get the workflow run details and node executions programmatically. Here is an example of how you can use the WorkflowRunService class:

from models.model import App
from services.workflow_run_service import WorkflowRunService

# Initialize the app model and service
app_model = App(id="your-app-id", tenant_id="your-tenant-id")
workflow_run_service = WorkflowRunService()

# Step 1: Get the workflow run list
args = {"limit": 1}  # Adjust the limit as needed
pagination = workflow_run_service.get_paginate_workflow_runs(app_model, args)
workflow_runs = pagination.data

# Step 2: Extract the run_id (assuming you want the first run_id in the list)
run_id = workflow_runs[0].id

# Step 3: Get the node executions
node_executions = workflow_run_service.get_workflow_run_node_executions(app_model, run_id)

# Print the node executions data
for node_execution in node_executions:
    print(node_execution)

In this example:

  • Replace your-app-id and your-tenant-id with the actual app_id and tenant_id of your application.
  • The WorkflowRunService class methods are used to fetch the workflow runs and node executions directly from the database.

The WorkflowRun and WorkflowNodeExecution classes in the Dify platform contain attributes such as id, tenant_id, app_id, workflow_id, status, created_at, and finished_at, which are essential for managing and querying workflow runs and node executions. The WorkflowRunStatus and WorkflowNodeExecutionStatus enums define the possible statuses for workflow runs and node executions, respectively [1][2][3].

To continue talking to Dosu, mention @dosu.

@dosubot[bot] commented on GitHub (Aug 29, 2024): <!-- Answer --> To call the `/apps/<uuid:app_id>/workflow-runs/<uuid:run_id>/node-executions` API endpoint in a workflow and get the value `<uuid:run_id>`, you can follow these steps: 1. **Get the Workflow Run List**: First, you need to get the list of workflow runs to obtain the `run_id`. You can do this by calling the `/apps/<uuid:app_id>/workflow-runs` endpoint. 2. **Extract the `run_id`**: From the response of the workflow run list, extract the `run_id` you need. 3. **Call the Node Executions Endpoint**: Use the extracted `run_id` to call the `/apps/<uuid:app_id>/workflow-runs/<uuid:run_id>/node-executions` endpoint. Here is an example of how you can achieve this in Python using the `requests` library: ```python import requests # Define the base URL and app_id base_url = "https://your-dify-instance.com" app_id = "your-app-id" # Step 1: Get the workflow run list workflow_runs_url = f"{base_url}/apps/{app_id}/workflow-runs" response = requests.get(workflow_runs_url, headers={"Authorization": "Bearer your-access-token"}) workflow_runs = response.json() # Step 2: Extract the run_id (assuming you want the first run_id in the list) run_id = workflow_runs['data'][0]['id'] # Step 3: Call the node executions endpoint node_executions_url = f"{base_url}/apps/{app_id}/workflow-runs/{run_id}/node-executions" response = requests.get(node_executions_url, headers={"Authorization": "Bearer your-access-token"}) node_executions = response.json() # Print the node executions data print(node_executions) ``` In this example: - Replace `your-dify-instance.com` with the actual base URL of your Dify instance. - Replace `your-app-id` with the actual `app_id` of your application. - Replace `your-access-token` with the actual access token for authentication. This code will first fetch the list of workflow runs, extract the `run_id` from the first workflow run in the list, and then use that `run_id` to fetch the node executions. Additionally, if you are using the Dify platform's internal services, you can utilize the `WorkflowRunService` class to get the workflow run details and node executions programmatically. Here is an example of how you can use the `WorkflowRunService` class: ```python from models.model import App from services.workflow_run_service import WorkflowRunService # Initialize the app model and service app_model = App(id="your-app-id", tenant_id="your-tenant-id") workflow_run_service = WorkflowRunService() # Step 1: Get the workflow run list args = {"limit": 1} # Adjust the limit as needed pagination = workflow_run_service.get_paginate_workflow_runs(app_model, args) workflow_runs = pagination.data # Step 2: Extract the run_id (assuming you want the first run_id in the list) run_id = workflow_runs[0].id # Step 3: Get the node executions node_executions = workflow_run_service.get_workflow_run_node_executions(app_model, run_id) # Print the node executions data for node_execution in node_executions: print(node_execution) ``` In this example: - Replace `your-app-id` and `your-tenant-id` with the actual `app_id` and `tenant_id` of your application. - The `WorkflowRunService` class methods are used to fetch the workflow runs and node executions directly from the database. The `WorkflowRun` and `WorkflowNodeExecution` classes in the Dify platform contain attributes such as `id`, `tenant_id`, `app_id`, `workflow_id`, `status`, `created_at`, and `finished_at`, which are essential for managing and querying workflow runs and node executions. The `WorkflowRunStatus` and `WorkflowNodeExecutionStatus` enums define the possible statuses for workflow runs and node executions, respectively <sup>[[1]](https://github.com/langgenius/dify/blob/main/api/controllers/console/app/workflow_run.py)</sup><sup>[[2]](https://github.com/langgenius/dify/blob/main/api/services/workflow_run_service.py)</sup><sup>[[3]](https://github.com/langgenius/dify/blob/main/api/models/workflow.py)</sup>. <!-- Dosu Comment Footer --> *To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: langgenius/dify#5305