-
Notifications
You must be signed in to change notification settings - Fork 95
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
Open-source LLM from HuggingFace Agent Support for json output parsing #130
Open
tugrulguner
wants to merge
8
commits into
Forethought-Technologies:main
Choose a base branch
from
tugrulguner:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f833dbf
load_json_output modified for general llm
tugrulguner b7ed9c2
json correction generalized with max_retry
tugrulguner d8bab2c
passing llm into parse
tugrulguner 1aeb323
Corrections made for message
tugrulguner be7d5ed
more debugging for json correction
tugrulguner c761556
comment and to do added
tugrulguner a2afbf1
clearing prints and modifying initial llm gen
tugrulguner 4ccfbdd
reversing back the llm gen parameter
tugrulguner 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 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 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 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,16 +1,15 @@ | ||
import json | ||
import re | ||
from abc import abstractmethod | ||
from typing import Union, Any, Dict, List | ||
from colorama import Fore | ||
|
||
from autochain.models.base import Generation | ||
|
||
from autochain.models.chat_openai import ChatOpenAI | ||
from autochain.models.base import BaseLanguageModel | ||
from pydantic import BaseModel | ||
|
||
from autochain.models.base import Generation | ||
from autochain.agent.message import BaseMessage, UserMessage | ||
from autochain.chain import constants | ||
from autochain.errors import OutputParserException | ||
from autochain.utils import print_with_color | ||
|
||
|
||
class AgentAction(BaseModel): | ||
|
@@ -55,30 +54,94 @@ def format_output(self) -> Dict[str, Any]: | |
|
||
|
||
class AgentOutputParser(BaseModel): | ||
@staticmethod | ||
def load_json_output(message: BaseMessage) -> Dict[str, Any]: | ||
"""If the message contains a json response, try to parse it into dictionary""" | ||
|
||
def load_json_output( | ||
self, | ||
message: BaseMessage, | ||
llm: BaseLanguageModel, | ||
max_retry=3 | ||
) -> Dict[str, Any]: | ||
"""Try to parse JSON response from the message content.""" | ||
text = message.content | ||
clean_text = "" | ||
clean_text = self._extract_json_text(text) | ||
|
||
try: | ||
clean_text = text[text.index("{") : text.rindex("}") + 1].strip() | ||
response = json.loads(clean_text) | ||
except Exception: | ||
llm = ChatOpenAI(temperature=0) | ||
message = [ | ||
UserMessage( | ||
content=f"""Fix the following json into correct format | ||
```json | ||
{clean_text} | ||
``` | ||
""" | ||
) | ||
] | ||
full_output: Generation = llm.generate(message).generations[0] | ||
response = json.loads(full_output.message.content) | ||
print_with_color( | ||
'Generating JSON format attempt FAILED! Trying Again...', | ||
Fore.RED | ||
) | ||
message = self._fix_message(clean_text) | ||
response = self._attempt_fix_and_generate( | ||
message, | ||
llm, | ||
max_retry, | ||
attempt=0 | ||
) | ||
|
||
return response | ||
|
||
@staticmethod | ||
def _fix_message(clean_text: str) -> UserMessage: | ||
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. can you make this is a helper function inside of |
||
''' | ||
If the response from model is not proper, this function should | ||
iteratively construct better response until response becomes json parseable | ||
''' | ||
|
||
# TO DO | ||
# Construct this message better in order to make it better iteratively by | ||
# _attempt_fix_and_generate recursive function | ||
message = UserMessage( | ||
content=f""" | ||
Fix the following json into correct format | ||
```json | ||
{clean_text} | ||
``` | ||
""" | ||
) | ||
return message | ||
|
||
@staticmethod | ||
def _extract_json_text(text: str) -> str: | ||
"""Extract JSON text from the input string.""" | ||
clean_text = "" | ||
try: | ||
clean_text = text[text.index("{") : text.rindex("}") + 1].strip() | ||
except Exception: | ||
clean_text = text | ||
return clean_text | ||
|
||
def _attempt_fix_and_generate( | ||
self, | ||
message: BaseMessage, | ||
llm: BaseLanguageModel, | ||
max_retry: int, | ||
attempt: int | ||
) -> Dict[str, Any]: | ||
|
||
"""Attempt to fix JSON format using model generation recursively.""" | ||
if attempt >= max_retry: | ||
raise ValueError( | ||
""" | ||
Max retry reached. Model is unable to generate proper JSON output. | ||
Try with another Model! | ||
""" | ||
) | ||
|
||
full_output: Generation = llm.generate([message]).generations[0] | ||
|
||
try: | ||
response = json.loads(full_output.message.content) | ||
return response | ||
except Exception: | ||
print_with_color( | ||
'Generating JSON format attempt FAILED! Trying Again...', | ||
Fore.RED | ||
) | ||
clean_text = self._extract_json_text(full_output.message.content) | ||
message = self._fix_message(clean_text) | ||
return self._attempt_fix_and_generate(message, llm, max_retry, attempt=attempt + 1) | ||
|
||
@abstractmethod | ||
def parse(self, message: BaseMessage) -> Union[AgentAction, AgentFinish]: | ||
|
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i think there is a way to simplify this logics inside of this function
first json load, if run into exception, fix and generate, format into message for
load_json_output
, decrease retry, call load_json_output again,if no exception, just return