This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 736
feat: OpenAI Image Generation Tool #628
Merged
anoopshrma
merged 10 commits into
run-llama:main
from
EmanuelCampos:feat/openai-image-generation
Nov 18, 2023
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
b69b557
feat: dall-e-3
EmanuelCampos d8f2d72
Merge branch 'main' of github.com:emptycrown/llama-hub into feat/open…
EmanuelCampos 6ac6b7d
chore: remove checkpoints
EmanuelCampos e21d247
lint
EmanuelCampos fb7891d
cr
EmanuelCampos 304297b
chore: use multi-modal as an example
EmanuelCampos 2a878e5
chore: delete checkpoint
EmanuelCampos 2c098d7
chore: fix tests and lint
EmanuelCampos 605a5a2
cr
EmanuelCampos 7f82485
lint
EmanuelCampos 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 |
---|---|---|
|
@@ -8,3 +8,4 @@ | |
.idea/ | ||
llama-hub.iml | ||
llamahub/ | ||
img_cache/ |
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
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
138 changes: 138 additions & 0 deletions
138
llama_hub/tools/notebooks/multimodal_openai_image.ipynb
Large diffs are not rendered by default.
Oops, something went wrong.
125 changes: 125 additions & 0 deletions
125
llama_hub/tools/notebooks/openai_image_generation_agent.ipynb
Large diffs are not rendered by default.
Oops, something went wrong.
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 |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# OpenAI Image Generation Tool | ||
|
||
This tool allows Agents to generate images using OpenAI's DALL-E model. To see more and get started, visit https://openai.com/blog/dall-e/ | ||
|
||
## Usage | ||
|
||
This tool has a more extensive example usage documented in a Jupyter notebook [here](https://github.com/emptycrown/llama-hub/tree/main/llama_hub/tools/notebooks/openai_image_generation.ipynb) | ||
|
||
### Usage with Agent | ||
```python | ||
from llama_hub.tools.openai.image_generation import OpenAIImageGenerationToolSpec | ||
|
||
image_generation_tool = OpenAIImageGenerationToolSpec(api_key=os.environ["OPENAI_API_KEY"]) | ||
|
||
agent = OpenAIAgent.from_tools( | ||
[*image_generation_tool.to_tool_list()], | ||
verbose=True, | ||
) | ||
|
||
response = agent.query('A pink and blue llama in a black background with the output') | ||
|
||
print(response) | ||
``` | ||
|
||
### Usage directly | ||
```python | ||
from llama_hub.tools.openai.image_generation import OpenAIImageGenerationToolSpec | ||
|
||
image_generation_tool = OpenAIImageGenerationToolSpec(api_key=os.environ["OPENAI_API_KEY"]) | ||
|
||
image_data = image_generation_tool.image_generation( | ||
text="A pink and blue llama with a black background", | ||
response_format="b64_json" | ||
) | ||
|
||
image_bytes = base64.b64decode(image_data) | ||
|
||
img = Image.open(BytesIO(image_bytes)) | ||
|
||
display(img) | ||
``` | ||
|
||
`image_generation`: Takes an text input and generates an image | ||
|
||
This loader is designed to be used as a way to load data as a Tool in a Agent. See [here](https://github.com/emptycrown/llama-hub/tree/main) for examples. |
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,6 @@ | ||
## init file | ||
from llama_hub.tools.openai.image_generation.base import ( | ||
OpenAIImageGenerationToolSpec, | ||
) | ||
|
||
__all__ = ["OpenAIImageGenerationToolSpec"] |
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,90 @@ | ||
"""OpenAI Image Generation tool sppec..""" | ||
|
||
import os | ||
import base64 | ||
import time | ||
|
||
from typing import Optional | ||
from llama_index.tools.tool_spec.base import BaseToolSpec | ||
|
||
DEFAULT_CACHE_DIR = "../../../img_cache" | ||
DEFAULT_SIZE = "1024x1024" # Dall-e-3 only supports 1024x1024 | ||
|
||
|
||
class OpenAIImageGenerationToolSpec(BaseToolSpec): | ||
"""OpenAI Image Generation tool spec.""" | ||
|
||
spec_functions = ["image_generation"] | ||
|
||
def __init__(self, api_key: str, cache_dir: Optional[str] = None) -> None: | ||
try: | ||
from openai import OpenAI | ||
except ImportError: | ||
raise ImportError( | ||
"Please install openai with `pip install openai` to use this tool" | ||
) | ||
|
||
"""Initialize with parameters.""" | ||
self.client = OpenAI(api_key=api_key) | ||
self.cache_dir = cache_dir or DEFAULT_CACHE_DIR | ||
|
||
def get_cache_dir(self): | ||
return self.cache_dir | ||
|
||
def save_base64_image(self, base64_str, image_name): | ||
try: | ||
from PIL import Image | ||
from io import BytesIO | ||
except ImportError: | ||
raise ImportError( | ||
"Please install Pillow with `pip install Pillow` to use this tool" | ||
) | ||
cache_dir = self.cache_dir | ||
|
||
# Create cache directory if it doesn't exist | ||
if not os.path.exists(cache_dir): | ||
os.makedirs(cache_dir) | ||
|
||
# Decode the base64 string | ||
image_data = base64.b64decode(base64_str) | ||
|
||
# Create an image from the decoded bytes and save it | ||
image_path = os.path.join(cache_dir, image_name) | ||
with Image.open(BytesIO(image_data)) as img: | ||
img.save(image_path) | ||
|
||
return image_path | ||
|
||
def image_generation( | ||
self, | ||
text: str, | ||
model: Optional[str] = "dall-e-3", | ||
quality: Optional[str] = "standard", | ||
num_images: Optional[int] = 1, | ||
) -> str: | ||
""" | ||
This tool accepts a natural language string and will use OpenAI's DALL-E model to generate an image. | ||
|
||
args: | ||
text (str): The text to generate an image from. | ||
size (str): The size of the image to generate (1024x1024, 256x256, 512x512). | ||
model (str): The model to use to generate the image (dall-e-3, dall-e-2). | ||
quality (str): The quality of the image to generate (standard, hd). | ||
num_images (int): The number of images to generate. | ||
""" | ||
response = self.client.images.generate( | ||
model=model, | ||
prompt=text, | ||
size=DEFAULT_SIZE, | ||
quality=quality, | ||
n=num_images, | ||
response_format="b64_json", | ||
) | ||
|
||
image_bytes = response.data[0].b64_json | ||
|
||
filename = f"{time.time()}.jpg" | ||
|
||
saved_image_path = self.save_base64_image(image_bytes, filename) | ||
|
||
return saved_image_path |
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
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.
api_key should probably be optional, since it could be in os.environ