プログラムが読める答え
自由なテキストは人間にはいいものです。でもプログラムがほしいのはデータです。このメールはどのカテゴリーか、どのくらい急ぎか、この文にはどんな名前と年齢が入っているか。モデルに「JSONで答えて」と頼むと、たいていはそうしてくれます。でもときどき、前に説明が付いていたり、項目が抜けていたり、勝手な言葉が入っていたりします。構造化出力(structured output)がこれを解決します。答えの形をスキーマとして記述すると、モデルはまさにその形で答えなければなりません。
RubyLLMはスキーマにSchematist gemを使います。RubyLLMといっしょに入ります。with_schemaでスキーマを設定し、parsedで答えをハッシュとして読みます:
install_gem "ruby_llm"
require "ruby_llm"
require "chunky_llm" # Chunky Mini、このページの中の小さなモデル
class PersonSchema < Schematist::Schema
string :name, description: "The person's first name"
integer :age
string :city, required: false
end
response = RubyLLM.chat.with_schema(PersonSchema).ask("Alice is 30 and lives in Rome.")
puts response.content
response.parsedcontentはモデルが書いたJSONのテキスト、parsedはそこからつくったハッシュです。cityは省略できます(required: false)。都市が出てこない文では"city"がありません。モデルが受け取るのはJSON Schemaで、どのプロバイダーもわかる標準です:
PersonSchema.new.to_json_schema選択肢:enum
意味のある値がいくつかしかないなら、enum:でそれを並べます。モデルはその中から1つを選ばなければなりません。ヘルプデスクは、こうして届いたメールを、だれかが読む前に仕分けます:
class TicketTriage < Schematist::Schema
string :category, enum: %w[billing shipping returns other]
string :priority, enum: %w[low normal urgent]
string :summary, description: "One sentence for the support queue"
end
emails = [
"My parcel still hasn't arrived and I need it for a wedding on Saturday!",
"Could you send me the invoice for my last order?",
"The jacket is too small, I'd like to return it."
]
emails.map do |email|
RubyLLM.chat.with_schema(TicketTriage).ask(email).parsed.values_at("category", "priority")
endメールごとに別のチャットを使います。1つのチャットを共有すると、2つ目のメールは1つ目を履歴としていっしょに運んでしまうからです。エージェントはスキーマを持てるので、エージェントがつくるチャットはどれもその形で答えます:
class TriageAgent < RubyLLM::Agent
instructions "Triage emails sent to the help desk of Chunky's shop."
schema TicketTriage
end
TriageAgent.new.ask("Where is my bacon? I ordered it two weeks ago!").parsedモデルなしでテストする
モデルを使うコードは、どうテストすればいいでしょう? 本物の答えは実行のたびに変わり、何秒もかかり、お金もかかります。RubyLLMにはテスト用のヘルパーが付いています。stub_repliesは、モデルが何と答えるかを決めます。チャットも、エージェントも、そのまわりのあなたのコードも本当に動きますが、リクエストだけは外に出ません。こうしてあなたのコード、つまり返事を受け取って何をするかをテストします。
require "ruby_llm/test_helper"
class TriageTest < Minitest::Test
include RubyLLM::TestHelper
def test_reads_the_category
stub_replies '{"category":"billing","priority":"low","summary":"Wants an invoice."}'
triage = TriageAgent.new.ask("Can I get an invoice?").parsed
assert_equal "billing", triage["category"]
end
def test_tool_call
stub_replies tool_call(:tiny_weather, city: "Bern"), "It is sunny in Bern."
chat = RubyLLM.chat.with_tools(TinyWeather)
assert_equal "It is sunny in Bern.", chat.ask("Weather in Bern?").content
assert_equal "sunny", chat.messages[2].content
end
end
class TinyWeather < RubyLLM::Tool
description "Gets the weather for a city"
parameter :city
def execute(city:) = "sunny"
end
run_tests2つ目のテストは、ツール呼び出しを台本どおりに演じさせます。「モデル」がツールを頼み、RubyLLMは本当にTinyWeather#executeを実行し、テストはツールがチャットに入れたものをチェックします。stub_repliesはテストの終わりまで効きます(after_teardownが消します)。だから次のテストは、また本物のモデルと話します。
require "ruby_llm/test_helper"をtest/test_helper.rbに、include RubyLLM::TestHelperをテストに書きます(RSpecならconfig.include RubyLLM::TestHelper)。本物のモデルがメールをうまく仕分けるかどうかは、また別の問題です。RubyLLMの評価(bin/rails generate ruby_llm:evaluation)は、例のセットをモデルで実行し、どのくらい正しいかを数えます。実行のたびにお金がかかるので、ふだんのテスト実行には入れません。
"bacon"、"berries"、"eggs"のどれかにしかならない項目snackと、整数のcountを持つスキーマSnackOrderを書いてください。このスキーマを持たせたチャットに「Chunky would like 3 eggs, please.」と聞きます。セルの結果はパースした答えです。install_gem "ruby_llm"
require "ruby_llm"
require "chunky_llm" # Chunky Mini、このページの中の小さなモデル
# class SnackOrder < Schematist::Schema
# end