Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guardrails output parser: Pass LLM api for reasking #6089

Merged
merged 3 commits into from
Jun 18, 2023
Merged
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
37 changes: 31 additions & 6 deletions langchain/output_parsers/rail_parser.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,51 @@
from __future__ import annotations

from typing import Any, Dict
from typing import Any, Callable, Dict, Optional

from langchain.schema import BaseOutputParser


class GuardrailsOutputParser(BaseOutputParser):
guard: Any
api: Optional[Callable]
args: Any
kwargs: Any

@property
def _type(self) -> str:
return "guardrails"

@classmethod
def from_rail(cls, rail_file: str, num_reasks: int = 1) -> GuardrailsOutputParser:
def from_rail(
cls,
rail_file: str,
num_reasks: int = 1,
api: Optional[Callable] = None,
*args: Any,
**kwargs: Any,
) -> GuardrailsOutputParser:
try:
from guardrails import Guard
except ImportError:
raise ValueError(
"guardrails-ai package not installed. "
"Install it by running `pip install guardrails-ai`."
)
return cls(guard=Guard.from_rail(rail_file, num_reasks=num_reasks))
return cls(
guard=Guard.from_rail(rail_file, num_reasks=num_reasks),
api=api,
args=args,
kwargs=kwargs,
)

@classmethod
def from_rail_string(
cls, rail_str: str, num_reasks: int = 1
cls,
rail_str: str,
num_reasks: int = 1,
api: Optional[Callable] = None,
*args: Any,
**kwargs: Any,
) -> GuardrailsOutputParser:
try:
from guardrails import Guard
Expand All @@ -34,10 +54,15 @@ def from_rail_string(
"guardrails-ai package not installed. "
"Install it by running `pip install guardrails-ai`."
)
return cls(guard=Guard.from_rail_string(rail_str, num_reasks=num_reasks))
return cls(
guard=Guard.from_rail_string(rail_str, num_reasks=num_reasks),
api=api,
args=args,
kwargs=kwargs,
)

def get_format_instructions(self) -> str:
return self.guard.raw_prompt.format_instructions

def parse(self, text: str) -> Dict:
return self.guard.parse(text)
return self.guard.parse(text, llm_api=self.api, *self.args, **self.kwargs)