{"code":"invalid_param","message":"Query cannot exceed 250 characters","status":400} #21060

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

Originally created by @KkHu-Kistch on GitHub (Dec 15, 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.11

Cloud or Self Hosted

Cloud

Steps to reproduce

please tell me why? why i cant exceed 250 characters? its not Reasonable

✔️ Expected Behavior

i can use > 250 characters to search

Actual Behavior

i cant use > 250 characters to search

Originally created by @KkHu-Kistch on GitHub (Dec 15, 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.11 ### Cloud or Self Hosted Cloud ### Steps to reproduce please tell me why? why i cant exceed 250 characters? its not Reasonable ### ✔️ Expected Behavior i can use > 250 characters to search ### ❌ Actual Behavior i cant use > 250 characters to search
yindo added the 🌚 invalid label 2026-02-21 20:10:29 -05:00
yindo closed this issue 2026-02-21 20:10:29 -05:00
Author
Owner

@KkHu-Kistch commented on GitHub (Dec 15, 2025):

import requests
import json
import re

================= 配置区域 =================

DIFY_API_KEY = "xxxxxxxxxxxxxxxxx" # 必须是【知识库】的 API Key
DIFY_BASE_URL = "https://api.dify.ai/v1" # 私有部署请换成你的域名
DATASET_ID = "xxxxxxxxxxxxxxxxxx" # 你的 Dify 数据集 ID

def retrieve_triton_code(query_text):
"""
核心召回函数:
输入 Torch 代码/描述 -> 返回对应的 Triton 代码
"""
url = f"{DIFY_BASE_URL}/datasets/{DATASET_ID}/retrieve"
headers = {
"Authorization": f"Bearer {DIFY_API_KEY}",
"Content-Type": "application/json"
}

# 检索配置:为兼容不同 Dify 版本,补齐可能的必填字段
payload = {
    "query": query_text,
    "retrieval_model": {
        # QA 知识库一般用语义检索就够稳;先跑通再谈 hybrid
        "search_method": "semantic_search",
        "reranking_enable": False,
        "reranking_mode": None,
        "reranking_model": {
            "reranking_provider_name": "",
            "reranking_model_name": ""
        },
        "weights": None,
        "top_k": 4,

        # 关键:不传这个字段,部分 Dify 版本会直接 500
        "score_threshold_enabled": False,
        "score_threshold": None,

        "metadata_filtering_conditions": None
    }
}


try:
    response = requests.post(url, headers=headers, json=payload, timeout=60)
    response.raise_for_status()
    data = response.json()
    
    records = data.get('records', [])
    if not records:
        print("⚠️ 未找到匹配的文档块。")
        return None

    # 获取命中得分最高的那个片段
    best_match = records[0]
    segment = best_match.get("segment", {}) or {}
    score = best_match.get("score", 0.0)

    # QA 知识库:Q/A 可能分别在不同字段里
    question_text = (
        segment.get("content")
        or segment.get("question")
        or best_match.get("question")
        or ""
    )
    answer_text = (
        segment.get("answer")
        or segment.get("qa_answer")
        or segment.get("answer_content")
        or segment.get("response")
        or best_match.get("answer")
        or ""
    )
    question_text = question_text.strip() if isinstance(question_text, str) else ""
    answer_text = answer_text.strip() if isinstance(answer_text, str) else ""
    
    print(f"✅ 召回成功! 相似度得分: {score:.4f}")
    
    # ================= 解析逻辑 =================
    # 目标:优先拿到 QA 的 Answer(Triton);同时把 Q/A 都打印出来,方便你核对
    # 如果 retrieve 没直接给 answer,我们再用 document_id 拉完整 segments(常见:第 1 段是 Q,后续段是 A)
    doc_id = segment.get("document_id")
    if (not answer_text) and doc_id:
        try:
            doc_url = f"{DIFY_BASE_URL}/datasets/{DATASET_ID}/documents/{doc_id}/segments"
            doc_resp = requests.get(doc_url, headers=headers, timeout=60)
            if doc_resp.ok:
                doc_json = doc_resp.json()
                doc_segments = doc_json.get("data") or []
                contents = []
                for s in doc_segments:
                    if isinstance(s, dict):
                        c = s.get("content")
                        if isinstance(c, str) and c.strip():
                            contents.append(c.strip())

                if contents:
                    # 尽量用 segments 的第 1 段作为 Q(如果 retrieve 没给到)
                    if not question_text:
                        question_text = contents[0]
                    # 经验:后续段拼起来通常就是 Answer(比如 Triton 代码)
                    if len(contents) >= 2:
                        answer_text = "\n\n".join(contents[1:]).strip()
        except Exception:
            # 拉 segments 失败不影响主流程
            pass

    print("\n================ 命中内容 (Q/A) ================\n")
    print("【Q】")
    print(question_text if question_text else "(空)")
    print("\n【A】")
    print(answer_text if answer_text else "(空)")
    print("\n================================================\n")

    # 最终返回:优先返回 Answer;取不到才退化为 Q
    text_to_return = answer_text if answer_text else question_text
    if not text_to_return:
        return None

    # 兼容老数据:同一段里用 marker 分隔 Torch/Triton
    marker = "### Triton Implementation (Target)"
    if marker in text_to_return:
        text_to_return = text_to_return.split(marker, 1)[1].strip()

    # 如果 Answer 用 ``` ``` 包起来,优先抽出代码块内容
    m = re.search(r"```(?:python|triton)?\s*([\s\S]*?)```", text_to_return, flags=re.IGNORECASE)
    if m:
        return m.group(1).strip()

    return text_to_return.strip()

except Exception as e:
    print(f"❌ 请求出错: {e}")
    if 'response' in locals():
        print(response.text)
    return None

================= 测试用例 =================

if name == "main":

# 模拟场景:Agent 手里有一段 Torch 代码,想找 Triton 实现
# 这里截取你 JSON 里的 TimeDistributed 的一部分 Torch 代码作为查询
test_query = """
def __init__(self, module, batch_first=False):
    if not isinstance(module, nn.Module):
        raise ValueError(f'Please initialize `TimeDistributed` with a `torch.nn.Module` instance.')
    super(TimeDistributed, self).__init__()
    self.module = module
    self.batch_first = batch_first

def forward(self, x):
    orig_x = x
    if isinstance(x, PackedSequence):
        (x, lens_x) = pad_packed_sequence(x, batch_first=self.batch_first)
"""

print("--- 开始测试召回 ---")
print(f"输入 Query (PyTorch 片段):\n{test_query.strip()[:100]}...\n")

result = retrieve_triton_code(test_query)

if result:
    print("\n🎉 === 提取到的 Answer(优先)/ Triton 内容 === 🎉")
    print(result)
    
    # 简单的验证逻辑
    if "@triton.jit" in result or "import triton" in result:
        print("\n✅ 验证通过:检测到 Triton 关键字。")
    else:
        print("\n⚠️ 验证警告:提取的内容似乎不是 Triton 代码,请检查。")

its my python code,you can use this to reproduce it

@KkHu-Kistch commented on GitHub (Dec 15, 2025): import requests import json import re # ================= 配置区域 ================= DIFY_API_KEY = "xxxxxxxxxxxxxxxxx" # 必须是【知识库】的 API Key DIFY_BASE_URL = "https://api.dify.ai/v1" # 私有部署请换成你的域名 DATASET_ID = "xxxxxxxxxxxxxxxxxx" # 你的 Dify 数据集 ID def retrieve_triton_code(query_text): """ 核心召回函数: 输入 Torch 代码/描述 -> 返回对应的 Triton 代码 """ url = f"{DIFY_BASE_URL}/datasets/{DATASET_ID}/retrieve" headers = { "Authorization": f"Bearer {DIFY_API_KEY}", "Content-Type": "application/json" } # 检索配置:为兼容不同 Dify 版本,补齐可能的必填字段 payload = { "query": query_text, "retrieval_model": { # QA 知识库一般用语义检索就够稳;先跑通再谈 hybrid "search_method": "semantic_search", "reranking_enable": False, "reranking_mode": None, "reranking_model": { "reranking_provider_name": "", "reranking_model_name": "" }, "weights": None, "top_k": 4, # 关键:不传这个字段,部分 Dify 版本会直接 500 "score_threshold_enabled": False, "score_threshold": None, "metadata_filtering_conditions": None } } try: response = requests.post(url, headers=headers, json=payload, timeout=60) response.raise_for_status() data = response.json() records = data.get('records', []) if not records: print("⚠️ 未找到匹配的文档块。") return None # 获取命中得分最高的那个片段 best_match = records[0] segment = best_match.get("segment", {}) or {} score = best_match.get("score", 0.0) # QA 知识库:Q/A 可能分别在不同字段里 question_text = ( segment.get("content") or segment.get("question") or best_match.get("question") or "" ) answer_text = ( segment.get("answer") or segment.get("qa_answer") or segment.get("answer_content") or segment.get("response") or best_match.get("answer") or "" ) question_text = question_text.strip() if isinstance(question_text, str) else "" answer_text = answer_text.strip() if isinstance(answer_text, str) else "" print(f"✅ 召回成功! 相似度得分: {score:.4f}") # ================= 解析逻辑 ================= # 目标:优先拿到 QA 的 Answer(Triton);同时把 Q/A 都打印出来,方便你核对 # 如果 retrieve 没直接给 answer,我们再用 document_id 拉完整 segments(常见:第 1 段是 Q,后续段是 A) doc_id = segment.get("document_id") if (not answer_text) and doc_id: try: doc_url = f"{DIFY_BASE_URL}/datasets/{DATASET_ID}/documents/{doc_id}/segments" doc_resp = requests.get(doc_url, headers=headers, timeout=60) if doc_resp.ok: doc_json = doc_resp.json() doc_segments = doc_json.get("data") or [] contents = [] for s in doc_segments: if isinstance(s, dict): c = s.get("content") if isinstance(c, str) and c.strip(): contents.append(c.strip()) if contents: # 尽量用 segments 的第 1 段作为 Q(如果 retrieve 没给到) if not question_text: question_text = contents[0] # 经验:后续段拼起来通常就是 Answer(比如 Triton 代码) if len(contents) >= 2: answer_text = "\n\n".join(contents[1:]).strip() except Exception: # 拉 segments 失败不影响主流程 pass print("\n================ 命中内容 (Q/A) ================\n") print("【Q】") print(question_text if question_text else "(空)") print("\n【A】") print(answer_text if answer_text else "(空)") print("\n================================================\n") # 最终返回:优先返回 Answer;取不到才退化为 Q text_to_return = answer_text if answer_text else question_text if not text_to_return: return None # 兼容老数据:同一段里用 marker 分隔 Torch/Triton marker = "### Triton Implementation (Target)" if marker in text_to_return: text_to_return = text_to_return.split(marker, 1)[1].strip() # 如果 Answer 用 ``` ``` 包起来,优先抽出代码块内容 m = re.search(r"```(?:python|triton)?\s*([\s\S]*?)```", text_to_return, flags=re.IGNORECASE) if m: return m.group(1).strip() return text_to_return.strip() except Exception as e: print(f"❌ 请求出错: {e}") if 'response' in locals(): print(response.text) return None # ================= 测试用例 ================= if __name__ == "__main__": # 模拟场景:Agent 手里有一段 Torch 代码,想找 Triton 实现 # 这里截取你 JSON 里的 TimeDistributed 的一部分 Torch 代码作为查询 test_query = """ def __init__(self, module, batch_first=False): if not isinstance(module, nn.Module): raise ValueError(f'Please initialize `TimeDistributed` with a `torch.nn.Module` instance.') super(TimeDistributed, self).__init__() self.module = module self.batch_first = batch_first def forward(self, x): orig_x = x if isinstance(x, PackedSequence): (x, lens_x) = pad_packed_sequence(x, batch_first=self.batch_first) """ print("--- 开始测试召回 ---") print(f"输入 Query (PyTorch 片段):\n{test_query.strip()[:100]}...\n") result = retrieve_triton_code(test_query) if result: print("\n🎉 === 提取到的 Answer(优先)/ Triton 内容 === 🎉") print(result) # 简单的验证逻辑 if "@triton.jit" in result or "import triton" in result: print("\n✅ 验证通过:检测到 Triton 关键字。") else: print("\n⚠️ 验证警告:提取的内容似乎不是 Triton 代码,请检查。") its my python code,you can use this to reproduce it
Author
Owner

@dosubot[bot] commented on GitHub (Dec 15, 2025):

The 250-character query limit is enforced by Dify's backend validation. Specifically, the API expects the query field to be no longer than 250 characters, as defined in the Pydantic model for the retrieval payload (see code). The service logic also checks this and raises an error if the limit is exceeded (see code). This restriction is hardcoded and not configurable in the current version.

If you need to submit longer queries, you could try splitting your input into smaller chunks or, if your use case allows, use the attachment_ids field to upload content and reference it in your query. There are currently no official workarounds or plans announced to increase this limit. The validation is intentional and covered by unit tests (see PR #28668).

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other

Chat with Dosu Open in Cursor Join Discord Share on X

@dosubot[bot] commented on GitHub (Dec 15, 2025): <!-- Answer --> The 250-character query limit is enforced by Dify's backend validation. Specifically, the API expects the `query` field to be no longer than 250 characters, as defined in the Pydantic model for the retrieval payload ([see code](https://github.com/langgenius/dify/blob/09982a1c95e1ce65981cfeef2c6da852b74678a2/api/controllers/console/datasets/hit_testing_base.py#L32-L36)). The service logic also checks this and raises an error if the limit is exceeded ([see code](https://github.com/langgenius/dify/blob/09982a1c95e1ce65981cfeef2c6da852b74678a2/api/services/hit_testing_service.py#L28-L189)). This restriction is hardcoded and not configurable in the current version. If you need to submit longer queries, you could try splitting your input into smaller chunks or, if your use case allows, use the `attachment_ids` field to upload content and reference it in your query. There are currently no official workarounds or plans announced to increase this limit. The validation is intentional and covered by unit tests ([see PR #28668](https://github.com/langgenius/dify/pull/28668)). <!-- 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/ab651e73-8c35-4b4f-9d3a-66f4020dbde2?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/ab651e73-8c35-4b4f-9d3a-66f4020dbde2?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/ab651e73-8c35-4b4f-9d3a-66f4020dbde2?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/ab651e73-8c35-4b4f-9d3a-66f4020dbde2?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/ab651e73-8c35-4b4f-9d3a-66f4020dbde2?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/ab651e73-8c35-4b4f-9d3a-66f4020dbde2?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/ab651e73-8c35-4b4f-9d3a-66f4020dbde2?feedback_type=other)</sup> [![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/6088a4f4-073a-43f3-b3d4-4f06fb0c05a0/ask?utm_source=github)&nbsp;[![Open in Cursor](https://dosu.dev/dosu-in-cursor.svg)](https://cursor.com/link/prompt?text=The%20250-character%20query%20limit%20is%20enforced%20by%20Dify%27s%20backend%20validation.%20Specifically%2C%20the%20API%20expects%20the%20%60query%60%20field%20to%20be%20no%20longer%20than%20250%20characters%2C%20as%20defined%20in%20the%20Pydantic%20model%20for%20the%20retrieval%20payload%20%28%5Bsee%20code%5D%28https%3A//github.com/langgenius/dify/blob/09982a1c95e1ce65981cfeef2c6da852b74678a2/api/controllers/console/datasets/hit_testing_base.py%23L32-L36%29%29.%20The%20service%20logic%20also%20checks%20this%20and%20raises%20an%20error%20if%20the%20limit%20is%20exceeded%20%28%5Bsee%20code%5D%28https%3A//github.com/langgenius/dify/blob/09982a1c95e1ce65981cfeef2c6da852b74678a2/api/services/hit_testing_service.py%23L28-L189%29%29.%20This%20restriction%20is%20hardcoded%20and%20not%20configurable%20in%20the%20current%20version.%0A%0AIf%20you%20need%20to%20submit%20longer%20queries%2C%20you%20could%20try%20splitting%20your%20input%20into%20smaller%20chunks%20or%2C%20if%20your%20use%20case%20allows%2C%20use%20the%20%60attachment_ids%60%20field%20to%20upload%20content%20and%20reference%20it%20in%20your%20query.%20There%20are%20currently%20no%20official%20workarounds%20or%20plans%20announced%20to%20increase%20this%20limit.%20The%20validation%20is%20intentional%20and%20covered%20by%20unit%20tests%20%28%5Bsee%20PR%20%2328668%5D%28https%3A//github.com/langgenius/dify/pull/28668%29%29.)&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/29689)
Author
Owner

@crazywoola commented on GitHub (Dec 15, 2025):

This is only for bug report, if you would like to ask a question, please head to Discussions.

We can moderately relax some length restrictions, but no matter the length, there will always be people questioning why there are any limits at all.
Because this is not the search method we want; it is recall testing, not intended for retrieval.

@crazywoola commented on GitHub (Dec 15, 2025): 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). We can moderately relax some length restrictions, but no matter the length, there will always be people questioning why there are any limits at all. Because this is not the search method we want; it is recall testing, not intended for retrieval.
Author
Owner

@KkHu-Kistch commented on GitHub (Dec 15, 2025):

This is only for bug report, if you would like to ask a question, please head to Discussions.

We can moderately relax some length restrictions, but no matter the length, there will always be people questioning why there are any limits at all. Because this is not the search method we want; it is recall testing, not intended for retrieval.

As a paid Team user, we chose Dify for its more powerful features. The 250-character API response limit is severely impacting the effectiveness of our RAG application. Could you please:
Provide paid expansion options?
Or at least allow Team users to customize this limit?
Regarding the statement "it is recall testing, not intended for retrieval," we are confused:
Unclear feature positioning: If this functionality is only for testing purposes, why isn't it clearly indicated in the documentation and feature descriptions?
Mismatch with paid features: As paying users, we need production-level retrieval functionality, not just testing tools.
Actual requirements: We need to achieve efficient retrieval in the RAG workflow, returning complete and useful context.
Please clarify:
Does this mean the current functionality is unsuitable for production environments?
If so, does Dify offer a formal production-grade retrieval solution?
How can we upgrade or switch to the proper retrieval functionality?

@KkHu-Kistch commented on GitHub (Dec 15, 2025): > 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). > > We can moderately relax some length restrictions, but no matter the length, there will always be people questioning why there are any limits at all. Because this is not the search method we want; it is recall testing, not intended for retrieval. As a paid Team user, we chose Dify for its more powerful features. The 250-character API response limit is severely impacting the effectiveness of our RAG application. Could you please: Provide paid expansion options? Or at least allow Team users to customize this limit? Regarding the statement "it is recall testing, not intended for retrieval," we are confused: Unclear feature positioning: If this functionality is only for testing purposes, why isn't it clearly indicated in the documentation and feature descriptions? Mismatch with paid features: As paying users, we need production-level retrieval functionality, not just testing tools. Actual requirements: We need to achieve efficient retrieval in the RAG workflow, returning complete and useful context. Please clarify: Does this mean the current functionality is unsuitable for production environments? If so, does Dify offer a formal production-grade retrieval solution? How can we upgrade or switch to the proper retrieval functionality?
Author
Owner

@KkHu-Kistch commented on GitHub (Dec 15, 2025):

Moreover, please explain: I noticed that this issue was mentioned in the discussion area, yet there was no response from your side, which is why I’m reaching out here on GitHub. https://github.com/langgenius/dify/discussions/21147

At the same time, I have also contacted customer support, but so far, no one has responded to me, even you guys label this question as invalid. Don’t you think it is actually your arrogance that is causing users frustration?

Do you even care whether it’s a case of users not using the feature correctly, or a failure in the functionality design?

@KkHu-Kistch commented on GitHub (Dec 15, 2025): Moreover, please explain: I noticed that this issue was mentioned in the discussion area, yet there was no response from your side, which is why I’m reaching out here on GitHub. https://github.com/langgenius/dify/discussions/21147 At the same time, I have also contacted customer support, but so far, no one has responded to me, even you guys label this question as invalid. Don’t you think it is actually your arrogance that is causing users frustration? Do you even care whether it’s a case of users not using the feature correctly, or a failure in the functionality design?
Author
Owner

@JohnJyong commented on GitHub (Dec 16, 2025):

Excessively long queries dilute semantic focus, causing embedding vectors to lose discriminative power, leading to unstable similarity rankings and decreased recall quality. In RAG systems, this must be addressed through query compression or splitting. @KkHu-Kistch

@JohnJyong commented on GitHub (Dec 16, 2025): Excessively long queries dilute semantic focus, causing embedding vectors to lose discriminative power, leading to unstable similarity rankings and decreased recall quality. In RAG systems, this must be addressed through query compression or splitting. @KkHu-Kistch
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: langgenius/dify#21060