Zenn
🙌

[Dify]イテレーション・配列ループ処理でハマったポイントメモ

2025/01/26に公開

Difyのイテレーション処理組むときにハマった内容と改善内容をメモ

イテレーションの出力設定漏れ

エラー文章

iteration output selector not found

修正内容


イテレーションブロック内で出力変数を選択

前工程でのパース処理のミス

イテレーションに渡す前のパース処理でDifyの受取形式の配列に変換できていなかった
Array[Object]の形式への変更メモ

前回実装していたパース処理

https://zenn.dev/kayato/articles/96fde23704706d

パース処理のコード実行部分で起こったエラー

エラー1

Output result is not an array, got <class 'dict'> instead.

エラー2

result must be a dict

ChatGPTさんの解釈

失礼しました。要件として、出力が配列である必要があるが、resultはdictであるべきという指摘に対して、誤解があったようです。実際には、resultは辞書型(dict)で、その中のitemsがリスト型である必要があるということですね。
このエラーメッセージから察するに、resultを辞書型で返すことは変わらず、ただしそのresultの中に格納されるitemsがリスト型でなければならないということです。
そのため、以下の修正を行います:
resultは辞書型で保持し、itemsの値としてリスト型のデータを格納します。
result自体が配列ではなく、itemsがリストでなければなりません。

修正後のコード

import json

def main(arg1: str) -> dict:  # 関数の戻り値はdictのまま
    try:
        # 文字列をJSONとしてデコード
        response_data = json.loads(arg1)
        
        # itemsが含まれているか確認
        if "items" in response_data:
            # items内の各エントリから必要な要素を抽出
            extracted_items = []
            for item in response_data["items"]:
                # title、link、snippetを取得
                title = item.get("title", "")
                link = item.get("link", "")
                snippet = item.get("snippet", "")
                
                # 抽出したデータをリストに追加
                extracted_items.append({
                    "title": title,
                    "link": link,
                    "snippet": snippet
                })
            
            # 結果を辞書として返す(itemsのリストを含む)
            return {"result": extracted_items}  # result内にリストを格納
        else:
            return {"result": [{"error": "No 'items' found in the response"}]}  # itemsがない場合はリストを返す
    
    except json.JSONDecodeError as e:
        # JSONデコードエラーの場合のエラーハンドリング
        return {"result": [{"error": f"JSONDecodeError: {str(e)}"}]}  # エラーもリストとして返す
    except Exception as e:
        # その他のエラーをキャッチ
        return {"result": [{"error": f"Unexpected error: {str(e)}"}]}  # エラーもリストとして返す

if __name__ == "__main__":
    # Example API response for testing
    api_response_body = '''{
        "items": [
            {
                "title": "Solana: Web3 Infrastructure for Everyone",
                "link": "https://solana.com/",
                "snippet": "Solana is a fast, secure, and censorship-resistant blockchain providing open infrastructure required for global adoption.",
                "pagemap": {
                    "metatags": [
                        {
                            "og:title": "Solana: Web3 Infrastructure",
                            "og:description": "Bring blockchain to the people."
                        }
                    ]
                }
            },
            {
                "title": "Solana price today, SOL to USD live price, marketcap and chart ...",
                "link": "https://coinmarketcap.com/currencies/solana/",
                "snippet": "Get the latest Solana price, SOL market cap, trading pairs, charts and data today from the world’s number one cryptocurrency price-tracking website.",
                "pagemap": {
                    "metatags": [
                        {
                            "og:title": "Solana Price",
                            "og:description": "The live Solana price today."
                        }
                    ]
                }
            }
        ]
    }'''

    # Call the main function and print the result
    result = main(api_response_body)
    print(json.dumps(result, indent=2, ensure_ascii=False))

イテレーション内のJSON Parseの設定

今回受け取った配列サンプル

      "link": "https://cypto.com/",
      "snippet": "See relevant content for cypto.com."
    },
    {
      "title": "Incorporate NFT and cypto and make COH the game it was ...",
      "link": "https://forums.homecomingservers.com/topic/34139-incorporate-nft-and-cypto-and-make-coh-the-game-it-was/",
      "snippet": "Jan 28, 2022 ... So i know this will get a bad gut reaction from many of you. But as someone who had an entire life in city of heroes back in the day."
    }
  ]
}

設定内容メモ

参考

【Dify超完全攻略講座 Vol.13】イテレーションブロック 反復処理と並列処理と
https://www.youtube.com/watch?v=e7FuMCgfRM4

DifyでQ&Aアプリを作ったらJSONの取り扱いとイテレーションでハマった話 #dify #ai
https://www.creationline.com/tech-blog/chatgpt-ai/ai/75366

Difyユーザー必見!JSON Parseツールで面倒な整形作業から解放
https://blog.generative-agents.co.jp/entry/2024/08/09/081902

Discussion

ログインするとコメントできます