地平線まで行ってくる。

記録あるいは忘備録。時には検討事項。

メモ:ollamaのstructured outputsでのエラーハンドリング

ollamaでstructured outputsに対応したので試します。すでに良記事が存在するので一読して、気になった出力の安定性とその時のエラー処理の味見をしました。ollamaでローカルLLMで大量のテキストを処理したい。データセットをちょっと加工したり、論文からデータを取り出したり・・・です。そのために、エラーのパターンや頻度を確認しておきます。素人プログラムでLLMの処理のメンドイのは想定外の出力の想定でしょうか。

 

Gemma2-2BのチューニングGUFFモデル(ezo-gemma-2-jpn:2b-instruct-q8_0)をありがたく使います。このモデルで以前実施したギャル語変換をトライします。データは、kunishou/databricks-dolly-15k-ja · Datasets at Hugging Face を使わせていただきました。

 

ざっくり1%程度の発生率で「Unterminated string starting at: line X column XX (char XX)」のようなJSONフォーマットに従わない出力によるエラーが出ました。頻度はこんなものかな。予想通り。エラーをどんな風にハンドリングしようかと悩んで、 json.loadsで一度パースしてみるのが良さそうでした。答えがピンボケだったとしてもLLMの性能ですが、エラーになったときにどうリカバーするかは、悩みどころですね。tempuratureを上げてエラーがなくまるまで生成するのがよいのでしょうか。

 

自分のためのメモとして。

 

note.com

 

用いた生成部分関数です。

import json

import ollama

 

def gal_phrase(query):
  class convert(BaseModel):
    converted_words: str


  query = (
  f"""以下の文章をギャル風に変更してください。日本語で答えます。JSON形式で返答してください。

  # 文章
  {query}
  """)
  response = ollama.chat(
      model=model_name,
      format=convert.model_json_schema(),
      messages=[
    {
      'role': 'user',
      'content': query,
    },
  ])

  # Try to parse the response as JSON, handling potential errors
  try:
    # Assuming response.message.content is a string containing JSON
    data = json.loads(response.message.content)
    return convert.model_validate(data).converted_words # Validate and extract
  except (json.JSONDecodeError, KeyError, TypeError) as e:
    print(f"Error processing response: {e}")
    print(f"Raw response: {response.message.content}")
    return "JSON_ERROR"

 

 

参考と使わせていただいたモデル:

ollama.com

 

ollama.com