-
Notifications
You must be signed in to change notification settings - Fork 1k
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
adding support for baidu qianfan and Ernie #823
Open
Dobiichi-Origami
wants to merge
12
commits into
guidance-ai:main
Choose a base branch
from
Dobiichi-Origami: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
12 commits
Select commit
Hold shift + click to select a range
8617190
adding support for baidu qianfan and Ernie
Dobiichi-Origami 414edc4
Merge remote-tracking branch 'upstream/HEAD'
Dobiichi-Origami 574bb93
refactor
Dobiichi-Origami 08af3e6
fix mypy issue
Dobiichi-Origami ef58953
Merge branch 'main' into main
riedgar-ms 7ae2f52
Allow generating arbitrary (schemaless) JSON (#892)
hudson-ai c796eeb
[Bug] Exclude llama-cpp-python version (#915)
riedgar-ms 2261d23
[Bug] Update Mistral chat template (#918)
riedgar-ms a06ba63
Fixing update to mistral chat template (#919)
Harsha-Nori edbe094
Merge branch 'main' into main
riedgar-ms d4cfe04
Merge branch 'main' into main
riedgar-ms f12320b
Merge branch 'main' into main
riedgar-ms 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
import copy | ||
|
||
import typing | ||
|
||
from ._grammarless import Grammarless, GrammarlessEngine | ||
|
||
|
||
try: | ||
import qianfan # type: ignore | ||
|
||
client_class: typing.Optional[typing.Type[qianfan.ChatCompletion]] = qianfan.ChatCompletion | ||
except ImportError: | ||
client_class = None | ||
|
||
|
||
class ClassUnavailableException(Exception): | ||
pass | ||
|
||
|
||
class QianfanAI(Grammarless): | ||
def __init__( | ||
self, | ||
model=None, | ||
echo=True, | ||
max_streaming_tokens=None, | ||
timeout=0.5, | ||
compute_log_probs=False, | ||
is_chat_model=True, | ||
**kwargs, | ||
): | ||
"""Build a new QianfanAI model object that represents a model in a given state.""" | ||
|
||
if client_class is None: | ||
raise ClassUnavailableException("Please execute `pip install qianfan` before using QianfanAI component") | ||
|
||
super().__init__( | ||
engine=QianfanAIEngine( | ||
model=model, | ||
max_streaming_tokens=max_streaming_tokens, | ||
timeout=timeout, | ||
compute_log_probs=compute_log_probs, | ||
is_chat_model=is_chat_model, | ||
**kwargs, | ||
), | ||
echo=echo, | ||
) | ||
|
||
|
||
class QianfanAIEngine(GrammarlessEngine): | ||
|
||
def __init__( | ||
self, | ||
model, | ||
max_streaming_tokens, | ||
timeout, | ||
compute_log_probs, | ||
is_chat_model=True, | ||
**kwargs, | ||
): | ||
if client_class is None: | ||
raise ClassUnavailableException("Please execute `pip install qianfan` before using QianfanAI component") | ||
|
||
assert ( | ||
not compute_log_probs | ||
), "We don't support compute_log_probs=True yet for QianfanAIEngine!" | ||
|
||
self.model_name = model | ||
|
||
self.is_chat_model = is_chat_model | ||
self.model_obj = qianfan.ChatCompletion(model=model, **kwargs) if self.is_chat_model else qianfan.Completion(model=model, **kwargs) | ||
|
||
self.extra_arguments = copy.deepcopy(kwargs) | ||
self.extra_arguments.pop("endpoint") if "endpoint" in kwargs else None | ||
|
||
super().__init__(None, max_streaming_tokens, timeout, compute_log_probs) | ||
|
||
def _generator(self, prompt, temperature): | ||
if self.is_chat_model: | ||
return self._chat_generator(prompt, temperature) | ||
|
||
return self._completion_generator(prompt, temperature) | ||
|
||
def _chat_generator(self, prompt, temperature): | ||
|
||
# find the system text | ||
pos = 0 | ||
|
||
system_start = b"<|im_start|>system\n" | ||
user_start = b"<|im_start|>user\n" | ||
assistant_start = b"<|im_start|>assistant\n" | ||
role_end = b"<|im_end|>" | ||
|
||
# find the system text | ||
system_text = "" | ||
if prompt.startswith(system_start): | ||
pos += len(system_start) | ||
system_end_pos = prompt.find(role_end) | ||
system_text = prompt[pos:system_end_pos].decode("utf8") | ||
pos = system_end_pos + len(role_end) | ||
|
||
# find the user/assistant pairs | ||
messages = [] | ||
valid_end = False | ||
while True: | ||
|
||
# find the user text | ||
if prompt[pos:].startswith(user_start): | ||
pos += len(user_start) | ||
end_pos = prompt[pos:].find(role_end) | ||
if end_pos < 0: | ||
break | ||
messages.append( | ||
dict( | ||
role="user", | ||
content=prompt[pos: pos + end_pos].decode("utf8"), | ||
) | ||
) | ||
pos += end_pos + len(role_end) | ||
elif prompt[pos:].startswith(assistant_start): | ||
pos += len(assistant_start) | ||
end_pos = prompt[pos:].find(role_end) | ||
if end_pos < 0: | ||
valid_end = True | ||
break | ||
messages.append( | ||
dict( | ||
role="assistant", | ||
content=prompt[pos: pos + end_pos].decode("utf8"), | ||
) | ||
) | ||
pos += end_pos + len(role_end) | ||
else: | ||
raise Exception( | ||
"It looks like your prompt is not a well formed chat prompt! Please enclose all model state appends inside chat role blocks like `user()` or `assistant()`." | ||
) | ||
|
||
self._data = prompt[:pos] | ||
|
||
assert len(messages) > 0, "Bad chat format! No chat blocks were defined." | ||
assert ( | ||
messages[-1]["role"] == "user" | ||
), "Bad chat format! There must be a user() role before the last assistant() role." | ||
assert valid_end, "Bad chat format! You must generate inside assistant() roles." | ||
|
||
if temperature == 0.0: | ||
temperature = 0.0001 | ||
|
||
input_kwargs = {"temperature": temperature} | ||
input_kwargs.update(self.extra_arguments) | ||
|
||
if system_text: | ||
input_kwargs["system"] = system_text | ||
|
||
input_kwargs["stream"] = True | ||
|
||
result_iter = self.model_obj.do(messages, **input_kwargs) | ||
for response in result_iter: | ||
yield response.body["result"].encode("utf8") | ||
|
||
def _completion_generator(self, prompt, temperature): | ||
if temperature == 0.0: | ||
temperature = 0.0001 | ||
|
||
input_kwargs = {"temperature": temperature} | ||
input_kwargs.update(self.extra_arguments) | ||
input_kwargs["stream"] = True | ||
|
||
self._data = prompt | ||
|
||
result_iter = self.model_obj.do(prompt.decode("utf8"), **input_kwargs) | ||
for response in result_iter: | ||
yield response.body["result"].encode("utf8") |
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'm guessing that credentials go into the
**kwargs
?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.
Yes, but normally It's passed through environment variable or
.env
.