Module: JsonLLM::Tools
- Defined in:
- lib/json_llm/tools.rb
Overview
Helpers for extracting and validating JSON responses.
Defined Under Namespace
Classes: Error, InvalidPayload, NotJsonFounded
Class Method Summary
collapse
Class Method Details
.prompt_llm(chat_with_llm, prompt) ⇒ Object
24
25
26
|
# File 'lib/json_llm/tools.rb', line 24
def prompt_llm(chat_with_llm, prompt)
to_h(chat_with_llm.call(prompt))
end
|
.prompt_llm_with_expected_payload(chat_with_llm, prompt, expected_payload) ⇒ Object
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/json_llm/tools.rb', line 28
def prompt_llm_with_expected_payload(chat_with_llm, prompt, expected_payload)
hash = prompt_llm(chat_with_llm,
"#{prompt}\n\nExpected payload response in JSON format: #{
JSON.pretty_generate(expected_payload)}")
unless HashValidator.validate(hash, expected_payload).valid?
raise InvalidPayload,
"Invalid payload: #{hash.inspect} does not match expected payload: #{
JSON.pretty_generate(expected_payload)}"
end
hash
end
|
.to_h(input) ⇒ Object
16
17
18
19
20
21
22
|
# File 'lib/json_llm/tools.rb', line 16
def to_h(input)
json_blocks = input.scan(/```json\n(.*?)```/m)
json_string = json_blocks.empty? ? input : json_blocks.last.first
JSON.parse(json_string)
rescue JSON::ParserError
raise NotJsonFounded, "No JSON found in the input #{input}"
end
|