2024.10.29 コラム
Check Grounding API を使ってみた
DataCurrentの金子です。Check Grounding API を使って、生成 AI の回答にインライン引用を追加してみました。
いくつかのドキュメントを生成 AI に読み込ませ、その上で生成された回答のどの部分が根拠に基づいているかを確認するために、インライン引用を追加するケースはよくあります。
従来はシステムプロンプトなどで引用を指示し、回答に引用を含めるよう促していましたが、期待通りに追加されないことがありました。Check Grounding API を使うことで、引用をより正確に挿入できるようになります。
※ こちらの内容は、2024 年 10 月時点の Google Cloud の公式ドキュメント Check grounding with RAG の内容と Python クライアントのソースコードを参考にしています。
Check Grounding API とは
Check Grounding API は、回答候補が提供された事実にどれだけ基づいているかを評価するための API です。
同じような機能として Grounded answer generation がありますが、こちらはプロンプトをリクエストした際に、根拠づけられた回答をそのまま返すことができます。Check Grounding API はあらかじめ回答を生成しておき、その回答の根拠をチェックするのに使われます。
2024 年 10 月現在は Grounded answer generation は、許可リスト付きの GA の位置づけになっています。今回は Check Grounding API を利用することで、生成 AI の回答に対してインライン引用を追加する検証を行いました。
Check Grounding API を利用すると、次のようなことが可能です。
- 引用が必要な箇所を自動で検出する
- 該当箇所が根拠づけられる場合は、根拠となる事実を出力する
- 総合的に提供された事実に対する文章の根拠度を示すスコアを出力する
Check Grounding API を試す
ドキュメント通りの内容になりますが、以下のようなステップで Check Grounding API を試すことができます。
API のレスポンスはコメントアウトで記しました。
# ~~ ドキュメント通りなので省略しています。 ~~ request = discoveryengine.CheckGroundingRequest( grounding_config=grounding_config, answer_candidate= "Titanic was directed by James Cameron. It was released in 1997.", facts=[ discoveryengine.GroundingFact( fact_text= ("Titanic is a 1997 American epic romantic disaster movie. It was directed, written," " and co-produced by James Cameron. The movie is about the 1912 sinking of the" " RMS Titanic. It stars Kate Winslet and Leonardo DiCaprio. The movie was released" " on December 19, 1997. It received positive critical reviews. The movie won 11 Academy" " Awards, and was nominated for fourteen total Academy Awards."), attributes={"author": "Simple Wikipedia"}, ), discoveryengine.GroundingFact( fact_text= ('James Cameron\'s "Titanic" is an epic, action-packed romance' "set against the ill-fated maiden voyage of the R.M.S. Titanic;" "the pride and joy of the White Star Line and, at the time," "the largest moving object ever built. " 'She was the most luxurious liner of her era -- the "ship of dreams" -- ' "which ultimately carried over 1,500 people to their death in the " "ice cold waters of the North Atlantic in the early hours of April 15, 1912." ), attributes={"author": "Simple Wikipedia"}, ), ], grounding_spec=discoveryengine.CheckGroundingSpec(citation_threshold=0.6), ) response = client.check_grounding(request=request) # Handle the response print(response) # 出力された内容 # support_score: 0.984230876 # cited_chunks { # chunk_text: "Titanic is a 1997 American epic romantic disaster movie. It was directed, written, and co-produced by James Cameron. The movie is about the 1912 sinking of the RMS Titanic. It stars Kate Winslet and Leonardo DiCaprio. The movie was released on December 19, 1997. It received positive critical reviews. The movie won 11 Academy Awards, and was nominated for fourteen total Academy Awards." # source: "0" # } # cited_chunks { # chunk_text: "James Cameron\'s \"Titanic\" is an epic, action-packed romanceset against the ill-fated maiden voyage of the R.M.S. Titanic;the pride and joy of the White Star Line and, at the time,the largest moving object ever built. She was the most luxurious liner of her era -- the \"ship of dreams\" -- which ultimately carried over 1,500 people to their death in the ice cold waters of the North Atlantic in the early hours of April 15, 1912." # source: "1" # } # claims { # start_pos: 0 # end_pos: 38 # claim_text: "Titanic was directed by James Cameron." # citation_indices: 0 # citation_indices: 1 # grounding_check_required: true # } # claims { # start_pos: 39 # end_pos: 63 # claim_text: "It was released in 1997." # citation_indices: 0 # grounding_check_required: true # }
リクエストの解説
request に格納されている内容は CheckGroundingRequest クラスとして渡されます。
grounding_config
は、projects/{project_id}/locations/{location}/groundingConfigs/default_grounding_config
の形式で指定します。answer_candidate
は、回答候補のテキストを指定します。facts
は、回答候補に引用される事実を配列で指定します。grounding_spec
は、回答候補内の主張に対して事実を引用すべきかどうかを判断するためのしきい値を 0 ~ 1 で指定します。高い閾値を選ぶと引用は少なくなりますが、非常に強力な引用になります。一方、低い閾値を選ぶと引用は増えますが、やや弱くなる可能性があります。
レスポンスの解説
response に格納されている内容は proto.Message のサブクラスである CheckGroundingResponse クラスとして返されます。出力時に cited_chunks
と claims
は複数表示されていますが、これは配列のように参照することができるという意味です。
support_score
は、入力された回答候補のサポートスコアです。スコアが高いほど、提供された事実によって裏付けられる主張の割合が高くなります。cited_chunks
は、facts で与えられた内容のうち、回答候補に引用された部分を示します。claims
は、インライン引用の情報を返します。start_pos
とend_pos
は、回答候補のテキスト内でのインライン引用の開始位置と終了位置を示します。文字列ベースではなく、バイトベースで指定されます。 上記の例ではend_pos
を +1 すると直後のstart_pos
になりますが、全てのケースでこのようになるわけではないので注意が必要です。claim_text
は、インライン引用のテキスト部分を示します。citation_indices
は、cited_chunks
のインデックスを参照します。このインデックスは、cited_chunks
の配列内での位置を示します。grounding_check_required
は、根拠づけが必要かどうかを示します。
制限
Check Grounding API は、以下の制限があります。
answer_candidates
の文字数はドキュメントでは 4096 トークンまでと記されています。ソースコード上では 1024 文字までと記されています。- 1 つの fact の文字数は 10,000 文字までです。
- fact は 200 件まで指定可能です。
価格
ドキュメントの Check Grounding API pricing によると、回答 1,000 文字あたり$0.00075 と記されています。
インライン引用の方法
Check Grounding API を使って生成 AI の回答にインライン引用を追加する例です。
何度か試しましたが、以下のコードでうまくいきそうです。Unicode 正規化などの処理が必要かどうかを警戒しましたが、特に実装せずとも問題はなさそうでした。実際に開発される際は、総合的によく動作を確認することをお勧めします。
# 生成 AI の回答を raw_answer とします。 raw_answer = "Titanic was directed by James Cameron. It was released in 1997." # インライン引用が追加された回答を grounded_answer とします。 grounded_answer = "" for i, claim in enumerate(response.claims): # ポジションを取得するために、バイトベースに変換 encoded_text = raw_answer.encode('utf-8') start_pos = claim.start_pos if i == len(response.claims) - 1: raw_answer_part = encoded_text[start_pos:].decode("utf-8") else: end_pos = response.claims[i + 1].start_pos raw_answer_part = encoded_text[start_pos:end_pos].decode("utf-8") with_inline = claim.claim_text citation_indices = [] for citation_index in claim.citation_indices: # citation_index は 0 から始まるため、1 から始まるように変換 citation_indices.append(citation_index + 1) if claim.grounding_check_required: if len(citation_indices) > 0: # citation が見つかった場合 with_inline += f" [{','.join(map(str, sorted(citation_indices)))}] " else: # citation が見つからない場合は、`(※)` を追加するようにした with_inline += "(※)" # 念のため raw_answer_part 内に claim.claim_text が含まれることを確認。 if claim.claim_text not in raw_answer_part: raise ValueError( f"claim_text is not in raw_answer_part: {claim.claim_text} not in {raw_answer_part}" ) # raw_answer_part のうち、claim.claim_text 部分をインライン引用にする grounded_answer_part = raw_answer_part.replace(claim.claim_text, with_inline) grounded_answer += grounded_answer_part print(grounded_answer) # Titanic was directed by James Cameron. [1,2] It was released in 1997. [1]
まとめ
今回は Check Grounding API を使って生成 AI の回答にインライン引用を追加する検証をしました。
生成 AI の回答に対してインライン引用を追加する際には、この APIを利用することで、より正確に引用を追加することができるようになります。
また、根拠があいまいな文章を検出することもできるため、ユーザーは生成された回答のどの部分が根拠に基づいているかを理解しやすくなります。
RAG を利用したチャットボットを構築する際は、Check Grounding API を活用して、生成された回答にインライン引用を追加することを検討してみてはいかがでしょうか。
最後に
自社に専門人材がいない、リソースが足りない等の課題をお持ちの方に、エンジニア領域の支援サービス(Data Engineer Hub)をご提供しています。
お困りごとございましたら是非お気軽にご相談ください。
本記事に関するお問い合わせは下記にて承ります。
株式会社DataCurrent
info@datacurrent.co.jp