Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions lib/langchain/output_parsers/output_fixing_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,7 @@ def parse(completion)
parser.parse(completion)
rescue OutputParserException => e
new_completion = llm.chat(
messages: [{role: "user",
content: prompt.format(
instructions: parser.get_format_instructions,
completion: completion,
error: e
)}]
messages: chat_messages(completion, e)
).completion
parser.parse(new_completion)
end
Expand All @@ -70,6 +65,38 @@ def self.from_llm(llm:, parser:, prompt: nil)

private

def chat_messages(completion, e)
# For Google LLMs, use the parts format
if llm.is_a?(Langchain::LLM::GoogleGemini) || llm.is_a?(Langchain::LLM::GoogleVertexAI)
return [
{
role: "user",
parts: [
{
text: prompt.format(
instructions: parser.get_format_instructions,
completion: completion,
error: e
)
}
]
}
]
end

# For other LLMs, use the standard content format
[
{
role: "user",
content: prompt.format(
instructions: parser.get_format_instructions,
completion: completion,
error: e
)
}
]
end

private_class_method def self.naive_fix_prompt
Langchain::Prompt.load_from_path(
file_path: Langchain.root.join("langchain/output_parsers/prompts/naive_fix_prompt.yaml")
Expand Down
21 changes: 21 additions & 0 deletions spec/lib/langchain/output_parsers/fix_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -186,5 +186,26 @@
expect { parser.parse("Whoops I don't understand") }.to raise_error(Langchain::OutputParsers::OutputParserException)
expect(parser.llm).to have_received(:chat).once
end

context "with a Gemini based model" do
let(:llm_example) { Langchain::LLM::GoogleGemini.new(api_key: "123") }

it "parses when the llm is a Gemini based model" do
parser = described_class.new(**kwargs_example.merge(prompt: fix_prompt_template_example))
expect(parser.llm).to receive(:chat).with({
messages: [
{
role: "user",
parts: [
{
text: match(fix_prompt_matcher_example)
}
]
}
]
}).and_return(double(completion: json_text_response))
expect(parser.parse("Whoops I don't understand")).to eq(json_response)
end
end
end
end