-
Notifications
You must be signed in to change notification settings - Fork 2.4k
feat: Add support for async modules and async bootstrap #161
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
Closed
Closed
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
622caf7
support async bootstrap few shot
sjiang2019 91de54e
Merge pull request #1 from harbinger-labs/steve/async-bootstrap
sjiang2019 5fb5702
Add support for Async Module
sjiang2019 299e1b4
Merge pull request #2 from harbinger-labs/steve/async-module
sjiang2019 fcd163c
add async lm
sjiang2019 a95765e
Merge pull request #3 from harbinger-labs/steve/async-lm
sjiang2019 053e632
refactor common logic
sjiang2019 0215cb8
Merge pull request #4 from harbinger-labs/steve/refactor-redundant-code
sjiang2019 c8bc34f
refactor gpt3 and async gpt3
sjiang2019 e51469a
Merge pull request #5 from harbinger-labs/steve/remove-redundant-asyn…
sjiang2019 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| import json | ||
| from typing import Any, cast | ||
|
|
||
| import backoff | ||
| import openai | ||
| import openai.error | ||
| from openai.openai_object import OpenAIObject | ||
|
|
||
|
|
||
| from dsp.modules.gpt3 import GPT3, backoff_hdlr | ||
|
|
||
|
|
||
| class AsyncGPT3(GPT3): | ||
| """Wrapper around OpenAI's GPT API. Supports both the OpenAI and Azure APIs. | ||
|
|
||
| Args: | ||
| model (str, optional): OpenAI or Azure supported LLM model to use. Defaults to "text-davinci-002". | ||
| api_key (Optional[str], optional): API provider Authentication token. use Defaults to None. | ||
| api_provider (Literal["openai", "azure"], optional): The API provider to use. Defaults to "openai". | ||
| model_type (Literal["chat", "text"], optional): The type of model that was specified. Mainly to decide the optimal prompting strategy. Defaults to "text". | ||
| **kwargs: Additional arguments to pass to the API provider. | ||
| """ | ||
|
|
||
| async def basic_request(self, prompt: str, **kwargs) -> OpenAIObject: | ||
| raw_kwargs = kwargs | ||
|
|
||
| kwargs = {**self.kwargs, **kwargs} | ||
| if self.model_type == "chat": | ||
| # caching mechanism requires hashable kwargs | ||
| kwargs["messages"] = [{"role": "user", "content": prompt}] | ||
| kwargs = {"stringify_request": json.dumps(kwargs)} | ||
| response = await _a_gpt3_chat_request(**kwargs) | ||
|
|
||
| else: | ||
| kwargs["prompt"] = prompt | ||
| response = await _a_gpt3_completion_request(**kwargs) | ||
|
|
||
| self._add_to_history(prompt, response, kwargs, raw_kwargs) | ||
|
|
||
| return response | ||
|
|
||
| @backoff.on_exception( | ||
| backoff.expo, | ||
| (openai.error.RateLimitError, openai.error.ServiceUnavailableError), | ||
| max_time=1000, | ||
| on_backoff=backoff_hdlr, | ||
| ) | ||
| async def request(self, prompt: str, **kwargs) -> OpenAIObject: | ||
| """Handles retreival of GPT-3 completions whilst handling rate limiting and caching.""" | ||
| if "model_type" in kwargs: | ||
| del kwargs["model_type"] | ||
|
|
||
| return await self.basic_request(prompt, **kwargs) | ||
|
|
||
| async def __call__( | ||
| self, | ||
| prompt: str, | ||
| only_completed: bool = True, | ||
| return_sorted: bool = False, | ||
| **kwargs, | ||
| ) -> list[dict[str, Any]]: | ||
| """Retrieves completions from GPT-3. | ||
|
|
||
| Args: | ||
| prompt (str): prompt to send to GPT-3 | ||
| only_completed (bool, optional): return only completed responses and ignores completion due to length. Defaults to True. | ||
| return_sorted (bool, optional): sort the completion choices using the returned probabilities. Defaults to False. | ||
|
|
||
| Returns: | ||
| list[dict[str, Any]]: list of completion choices | ||
| """ | ||
|
|
||
| assert only_completed, "for now" | ||
| assert return_sorted is False, "for now" | ||
|
|
||
| response = await self.request(prompt, **kwargs) | ||
| completions = self._get_completions_from_response( | ||
| response=response, | ||
| only_completed=only_completed, | ||
| return_sorted=return_sorted, | ||
| **kwargs, | ||
| ) | ||
| return completions | ||
|
|
||
|
|
||
| async def _a_gpt3_completion_request(**kwargs): | ||
| return await openai.Completion.acreate(**kwargs) | ||
|
|
||
|
|
||
| async def _a_gpt3_chat_request(**kwargs) -> OpenAIObject: | ||
| if "stringify_request" in kwargs: | ||
| kwargs = json.loads(kwargs["stringify_request"]) | ||
| res = await openai.ChatCompletion.acreate(**kwargs) | ||
| return cast(OpenAIObject, res) |
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
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.
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.
Will this actually work and become truly async? The call to the LLM is still completely synchronous/blocking.
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.
Thanks for engaging! It depends on how you define
forward(). The goal is just to allow you to do async ops, which could be LM-related or not (e.g. async db reads), in the module. For example,You're right in that it doesn't solve async for the current Predict and Retrieve abstractions, which use a sync LLM completion api call. Those would require a larger refactor to make async, but I think this is a reasonable escape hatch in the meantime.
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.
This is very reasonable. I can merge a very small change like this for sure but right now it's affecting a lot of lines of code