> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agnost.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Dify

> Capture Dify app, chatflow, and agent traces with Dify's built-in OpenTelemetry tracing

## Choose a setup method

| Method | Use it when |
| - | - |
| **Agnost AI skill** | You want your coding agent to inspect the app, make the change, and verify it. |
| **Agnost AI SDK** | You want explicit control over the interaction boundaries and fields. |
| **OpenTelemetry** | The framework already emits useful spans or you operate an OTel pipeline. |

Start with one method for a call path. Combining SDK tracking with framework
OpenTelemetry on the same call can create duplicate interactions.

## Recommended: Agnost AI skill

> [!NOTE]
>
> **Recommended.** Choose this path when you want your coding agent to inspect the
> project, select a supported transport, make the smallest instrumentation change,
> send a test event, and verify that it reached Agnost AI.

Install the skill once in your coding-agent environment:

```bash theme={null}
npx skills add AgnostAI/skills --skill agnost-ai
```

Run the framework-specific prompt below from the application root. Review the
resulting diff before deploying it.

```text theme={null}
Use the agnost-ai skill to add Agnost AI analytics to this Dify integration.
Org ID: your-org-id
Instrument the real Dify chat-messages call and verify one fresh interaction.
```

Dify can send traces to Agnost AI in two ways:

* **OpenTelemetry (recommended):** Dify's built-in **OpenTelemetry** tracing provider sends every run of an app to Agnost AI. No code is needed, and it covers Dify's own web app, the API, and the embedded chat widget.
* **Agnost AI SDK:** wrap the calls your backend makes to the Dify Service API. Use this when you can't change the app's tracing settings.

## Manual setup: Agnost AI SDK

Use this when your own backend calls Dify's [Send Chat Message](https://docs.dify.ai/en/api-reference/chat-messages/send-chat-message) endpoint. It records one event per turn. Traffic from Dify's own web app doesn't go through your backend, so it isn't recorded this way.

```bash theme={null}
pip install agnost requests
```

```python theme={null}
import os
import requests
import agnost

agnost.init("your-org-id")

DIFY_BASE_URL = os.environ.get("DIFY_BASE_URL", "https://api.dify.ai/v1")
DIFY_API_KEY = os.environ["DIFY_API_KEY"]  # the app's API key


def ask_dify(chat_id: str, user_id: str, query: str, dify_conversation_id: str = "") -> dict:
    interaction = agnost.begin(
        user_id=user_id,
        agent_name="dify-chatbot",
        input=query,
        conversation_id=chat_id,  # your own ID for this chat, the same on every turn
    )
    if interaction is None:
        raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")
    try:
        response = requests.post(
            f"{DIFY_BASE_URL}/chat-messages",
            headers={"Authorization": f"Bearer {DIFY_API_KEY}"},
            json={
                "inputs": {},
                "query": query,
                "response_mode": "blocking",
                "conversation_id": dify_conversation_id,
                "user": user_id,
            },
            timeout=120,
        )
        response.raise_for_status()
        data = response.json()
        interaction.set_properties({
            "dify_conversation_id": data["conversation_id"],
            "dify_message_id": data["message_id"],
        })
        interaction.end(output=data["answer"])
        return data
    except Exception as exc:
        interaction.end(output=str(exc), success=False)
        raise
```

Pass the `conversation_id` that Dify returns on the next turn so Dify keeps the chat history. Blocking mode works for Chatbot and Chatflow apps. Legacy Agent apps only support streaming mode, so collect the `answer` text from the stream before calling `interaction.end()`.

Call `agnost.shutdown()` once when the application exits, not after each request.

## Manual setup: OpenTelemetry

Dify 1.20.0 added an **OpenTelemetry** tracing provider. It sends each run to any OTLP/HTTP collector. Its spans follow the OpenTelemetry GenAI conventions, and Agnost AI reads them directly:

* `gen_ai.session.id` is the Dify conversation ID, so every turn of a chat lands in one conversation.
* `gen_ai.user.id` is the `user` value your API calls send, or Dify's web app user.
* `input.value` and `output.value` carry the user's query and the app's answer.
* LLM spans carry the model, provider, and token counts. Tool spans carry the tool name, arguments, and result.

### Install

Self-hosted Dify: upgrade to 1.20.0 or later. The provider is part of the `trace-all` dependency group, which the official Docker image installs, so no extra install is needed. If you build the API yourself without the default groups, run `uv sync --group trace-otel` in `api/`.

Dify Cloud: if **OpenTelemetry** appears in the tracing list (step 2 below), it is available to you.

### Setup

1. Open the app you want to monitor and select **Monitoring** in the side menu.
2. Under **Tracing app performance**, click **Config** on **OpenTelemetry**.
3. Fill in the fields:

| Field | Value |
| - | - |
| **Endpoint** | `https://otel.agnost.ai/v1/traces` |
| **HTTP headers (JSON)** | `{"X-Agnost-Org-ID": "your-org-id"}` |
| **Service name** | Optional. Defaults to `dify`. |
| **Resource attributes (JSON)** | Optional, for example `{"deployment.environment.name": "production"}` |

4. Save. Dify checks the endpoint with an empty OTLP request before it saves. Agnost AI answers it with `200`.
5. Turn tracing on for the app if it isn't already in use.
6. For a Dify Agent, open **Agent data capture** and turn on **Capture content**. It is off by default, and without it the Agent's internal model and tool calls arrive with no inputs or outputs. **Capture Agent internals** is on by default; leave it on to get those spans.

Repeat this for each app. Dify stores the headers encrypted and never shows them again. If you change the endpoint later, enter the headers again.

To pass your own user IDs, send the `user` field on every [Service API](https://docs.dify.ai/en/api-reference/guides/end-user-identity) call. To keep a multi-turn chat in one conversation, pass the `conversation_id` Dify returned on the previous turn.

### What appears in Agnost AI

* **Conversations** grouped by the Dify conversation ID. A Workflow app run has no conversation, so each run is its own conversation.
* **User-level analytics** grouped by the `user` you send to the Dify API.
* **Events** for the message, each LLM call, each tool call, and each workflow node, with their parent links.

### Verify

Send two messages to the app in one conversation, from the app's web page or the API with a `user` value. After about 30 seconds, open **Conversations** in Agnost AI. Confirm that both turns appear in one conversation, the user ID matches, and the `message` event shows the question and the answer. For an Agent app that used a tool, confirm the tool event appears under the message.

### Troubleshooting

* **No OpenTelemetry option in the tracing list:** the Dify version is older than 1.20.0, or the API was built without the `trace-otel` group.
* **Save fails with an endpoint or connection error:** use `https://otel.agnost.ai/v1/traces` exactly, with no query string. On self-hosted Dify, outbound requests go through Dify's SSRF proxy, so the proxy must allow `otel.agnost.ai`.
* **Save succeeds but nothing appears:** check that the headers field is valid JSON and the key is spelled `X-Agnost-Org-ID`. A wrong org ID is accepted but the data goes nowhere.
* **Each turn is its own conversation:** pass the previous `conversation_id` on each Service API call. Workflow apps have no conversation, so each run is separate by design.
* **No user ID:** send the `user` field on every Service API call.
* **Agent model or tool events have no text:** turn on **Capture content** under **Agent data capture**.
* **Traces stopped after the endpoint changed:** Dify clears saved headers when the endpoint changes. Enter the headers again.

### References

* [Dify OpenTelemetry tracing provider](https://github.com/langgenius/dify/blob/1.20.0/api/providers/trace/trace-otel/README.md)
* [Dify 1.20.0 release notes](https://github.com/langgenius/dify/releases/tag/1.20.0)
* [Dify tracing integrations](https://docs.dify.ai/en/cloud/use-dify/monitor/integrations/integrate-phoenix)
* [Dify end user identity](https://docs.dify.ai/en/api-reference/guides/end-user-identity)
* [Agnost AI OpenTelemetry endpoint](https://docs.agnost.ai/otel.md)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review each Dify chat turn by turn.
* [Events](https://docs.agnost.ai/using-events.md): inspect messages, LLM calls, and tool calls.
* [Patterns](https://docs.agnost.ai/using-patterns.md): organize production conversations by what users wanted.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.