-
Notifications
You must be signed in to change notification settings - Fork 219
Add Structured Output #1443
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
Merged
Merged
Add Structured Output #1443
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
81e522f
Add Structured Output functionality
collindutter 3f79bb5
Don't use JsonSchemaRules
collindutter 2990f2e
PR feedback
collindutter 10b9ba7
Remove use_native_structured_output toggle
collindutter b9b8dac
Update dogs
collindutter 188ba44
Revert removal of use_native_structured_output, add fallback to JsonS…
collindutter fdd1924
Drop "native" from structured output fields
collindutter b35c5e1
Remove redundant doc
collindutter 4f8819b
Rename method for clarity
collindutter b37394f
Move logic from driver to task, remove flag
collindutter 247be54
Move logic from task to base prompt driver
collindutter 930f343
Remove response_format in docs
collindutter 8ab92dc
PR cleanup
collindutter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 32 additions & 0 deletions
32
docs/griptape-framework/drivers/src/prompt_drivers_structured_output.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import schema | ||
| from rich.pretty import pprint | ||
|
|
||
| from griptape.drivers import OpenAiChatPromptDriver | ||
| from griptape.rules import Rule | ||
| from griptape.structures import Pipeline | ||
| from griptape.tasks import PromptTask | ||
|
|
||
| pipeline = Pipeline( | ||
| tasks=[ | ||
| PromptTask( | ||
| prompt_driver=OpenAiChatPromptDriver( | ||
| model="gpt-4o", | ||
| structured_output_strategy="native", # optional | ||
| ), | ||
| output_schema=schema.Schema( | ||
| { | ||
| "steps": [schema.Schema({"explanation": str, "output": str})], | ||
| "final_answer": str, | ||
| } | ||
| ), | ||
| rules=[ | ||
| Rule("You are a helpful math tutor. Guide the user through the solution step by step."), | ||
| ], | ||
| ) | ||
| ] | ||
| ) | ||
|
|
||
| output = pipeline.run("How can I solve 8x + 7 = -23").output.value | ||
|
|
||
|
|
||
| pprint(output) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,11 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from abc import ABC, abstractmethod | ||
| from typing import TYPE_CHECKING, Optional | ||
| from typing import TYPE_CHECKING, Literal, Optional | ||
|
|
||
| from attrs import Factory, define, field | ||
|
|
||
| from griptape.artifacts.base_artifact import BaseArtifact | ||
| from griptape.artifacts import BaseArtifact, TextArtifact | ||
| from griptape.common import ( | ||
| ActionCallDeltaMessageContent, | ||
| ActionCallMessageContent, | ||
|
|
@@ -26,12 +26,15 @@ | |
| ) | ||
| from griptape.mixins.exponential_backoff_mixin import ExponentialBackoffMixin | ||
| from griptape.mixins.serializable_mixin import SerializableMixin | ||
| from griptape.rules.json_schema_rule import JsonSchemaRule | ||
|
|
||
| if TYPE_CHECKING: | ||
| from collections.abc import Iterator | ||
|
|
||
| from griptape.tokenizers import BaseTokenizer | ||
|
|
||
| StructuredOutputStrategy = Literal["native", "tool", "rule"] | ||
|
|
||
|
|
||
| @define(kw_only=True) | ||
| class BasePromptDriver(SerializableMixin, ExponentialBackoffMixin, ABC): | ||
|
|
@@ -56,9 +59,13 @@ class BasePromptDriver(SerializableMixin, ExponentialBackoffMixin, ABC): | |
| tokenizer: BaseTokenizer | ||
| stream: bool = field(default=False, kw_only=True, metadata={"serializable": True}) | ||
| use_native_tools: bool = field(default=False, kw_only=True, metadata={"serializable": True}) | ||
| structured_output_strategy: StructuredOutputStrategy = field( | ||
| default="rule", kw_only=True, metadata={"serializable": True} | ||
| ) | ||
| extra_params: dict = field(factory=dict, kw_only=True, metadata={"serializable": True}) | ||
|
|
||
| def before_run(self, prompt_stack: PromptStack) -> None: | ||
| self._init_structured_output(prompt_stack) | ||
| EventBus.publish_event(StartPromptEvent(model=self.model, prompt_stack=prompt_stack)) | ||
|
|
||
| def after_run(self, result: Message) -> None: | ||
|
|
@@ -122,6 +129,34 @@ def try_run(self, prompt_stack: PromptStack) -> Message: ... | |
| @abstractmethod | ||
| def try_stream(self, prompt_stack: PromptStack) -> Iterator[DeltaMessage]: ... | ||
|
|
||
| def _init_structured_output(self, prompt_stack: PromptStack) -> None: | ||
| from griptape.tools import StructuredOutputTool | ||
|
|
||
| if (output_schema := prompt_stack.output_schema) is not None: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Optional, but I think avoiding nesting is cleaner: output_schema = prompt_stack.output_schema
if output_schema is None:
return
... |
||
| if self.structured_output_strategy == "tool": | ||
| structured_output_tool = StructuredOutputTool(output_schema=output_schema) | ||
| if structured_output_tool not in prompt_stack.tools: | ||
| prompt_stack.tools.append(structured_output_tool) | ||
| elif self.structured_output_strategy == "rule": | ||
| output_artifact = TextArtifact(JsonSchemaRule(output_schema.json_schema("Output Schema")).to_text()) | ||
| system_messages = prompt_stack.system_messages | ||
| if system_messages: | ||
| last_system_message = prompt_stack.system_messages[-1] | ||
| last_system_message.content.extend( | ||
vachillo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| [ | ||
| TextMessageContent(TextArtifact("\n\n")), | ||
| TextMessageContent(output_artifact), | ||
| ] | ||
| ) | ||
| else: | ||
| prompt_stack.messages.insert( | ||
| 0, | ||
| Message( | ||
| content=[TextMessageContent(output_artifact)], | ||
| role=Message.SYSTEM_ROLE, | ||
| ), | ||
| ) | ||
|
|
||
| def __process_run(self, prompt_stack: PromptStack) -> Message: | ||
| return self.try_run(prompt_stack) | ||
|
|
||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.