Skip to content

Commit

Permalink
Merge branch 'main' into playground-error-fixing
Browse files Browse the repository at this point in the history
  • Loading branch information
aliabd authored Dec 27, 2024
2 parents b830241 + aa2eec2 commit 556b805
Show file tree
Hide file tree
Showing 31 changed files with 439 additions and 140 deletions.
6 changes: 6 additions & 0 deletions .changeset/long-months-wave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@gradio/chatbot": minor
"gradio": minor
---

feat:Dataframe support in Chatbot
6 changes: 6 additions & 0 deletions .changeset/solid-moments-mate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@gradio/browserstate": minor
"gradio": minor
---

feat:Add `gr.BrowserState` change event
6 changes: 6 additions & 0 deletions .changeset/young-geckos-brake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"gradio": patch
"gradio_client": patch
---

fix:Declare exports in __all__ for type checking
4 changes: 2 additions & 2 deletions client/python/gradio_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1356,8 +1356,8 @@ def _upload_file(self, f: dict, data_index: int) -> dict[str, str]:
f"File {file_path} exceeds the maximum file size of {max_file_size} bytes "
f"set in {component_config.get('label', '') + ''} component."
)
with open(file_path, "rb") as f:
files = [("files", (orig_name.name, f))]
with open(file_path, "rb") as f_:
files = [("files", (orig_name.name, f_))]
r = httpx.post(
self.client.upload_url,
headers=self.client.headers,
Expand Down
2 changes: 1 addition & 1 deletion demo/agent_chatbot/requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
git+https://github.com/huggingface/transformers.git#egg=transformers[agents]
transformers>=4.47.0
2 changes: 1 addition & 1 deletion demo/agent_chatbot/run.ipynb
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: agent_chatbot"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio git+https://github.com/huggingface/transformers.git#egg=transformers[agents]"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/agent_chatbot/utils.py"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from gradio import ChatMessage\n", "from transformers import load_tool, ReactCodeAgent, HfEngine # type: ignore\n", "from utils import stream_from_transformers_agent\n", "\n", "# Import tool from Hub\n", "image_generation_tool = load_tool(\"m-ric/text-to-image\")\n", "\n", "llm_engine = HfEngine(\"meta-llama/Meta-Llama-3-70B-Instruct\")\n", "# Initialize the agent with both tools\n", "agent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine)\n", "\n", "def interact_with_agent(prompt, messages):\n", " messages.append(ChatMessage(role=\"user\", content=prompt))\n", " yield messages\n", " for msg in stream_from_transformers_agent(agent, prompt):\n", " messages.append(msg)\n", " yield messages\n", " yield messages\n", "\n", "with gr.Blocks() as demo:\n", " stored_message = gr.State([])\n", " chatbot = gr.Chatbot(label=\"Agent\",\n", " type=\"messages\",\n", " avatar_images=(None, \"https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png\"))\n", " text_input = gr.Textbox(lines=1, label=\"Chat Message\")\n", " text_input.submit(lambda s: (s, \"\"), [text_input], [stored_message, text_input]).then(interact_with_agent, [stored_message, chatbot], [chatbot])\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: agent_chatbot"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio transformers>=4.47.0"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from dataclasses import asdict\n", "from transformers import Tool, ReactCodeAgent # type: ignore\n", "from transformers.agents import stream_to_gradio, HfApiEngine # type: ignore\n", "\n", "# Import tool from Hub\n", "image_generation_tool = Tool.from_space( # type: ignore\n", " space_id=\"black-forest-labs/FLUX.1-schnell\",\n", " name=\"image_generator\",\n", " description=\"Generates an image following your prompt. Returns a PIL Image.\",\n", " api_name=\"/infer\",\n", ")\n", "\n", "llm_engine = HfApiEngine(\"Qwen/Qwen2.5-Coder-32B-Instruct\")\n", "# Initialize the agent with both tools and engine\n", "agent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine)\n", "\n", "\n", "def interact_with_agent(prompt, history):\n", " messages = []\n", " yield messages\n", " for msg in stream_to_gradio(agent, prompt):\n", " messages.append(asdict(msg)) # type: ignore\n", " yield messages\n", " yield messages\n", "\n", "\n", "demo = gr.ChatInterface(\n", " interact_with_agent,\n", " chatbot= gr.Chatbot(\n", " label=\"Agent\",\n", " type=\"messages\",\n", " avatar_images=(\n", " None,\n", " \"https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png\",\n", " ),\n", " ),\n", " examples=[\n", " [\"Generate an image of an astronaut riding an alligator\"],\n", " [\"I am writing a children's book for my daughter. Can you help me with some illustrations?\"],\n", " ],\n", " type=\"messages\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
50 changes: 33 additions & 17 deletions demo/agent_chatbot/run.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,46 @@
import gradio as gr
from gradio import ChatMessage
from transformers import load_tool, ReactCodeAgent, HfEngine # type: ignore
from utils import stream_from_transformers_agent
from dataclasses import asdict
from transformers import Tool, ReactCodeAgent # type: ignore
from transformers.agents import stream_to_gradio, HfApiEngine # type: ignore

# Import tool from Hub
image_generation_tool = load_tool("m-ric/text-to-image")
image_generation_tool = Tool.from_space( # type: ignore
space_id="black-forest-labs/FLUX.1-schnell",
name="image_generator",
description="Generates an image following your prompt. Returns a PIL Image.",
api_name="/infer",
)

llm_engine = HfEngine("meta-llama/Meta-Llama-3-70B-Instruct")
# Initialize the agent with both tools
llm_engine = HfApiEngine("Qwen/Qwen2.5-Coder-32B-Instruct")
# Initialize the agent with both tools and engine
agent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine)

def interact_with_agent(prompt, messages):
messages.append(ChatMessage(role="user", content=prompt))

def interact_with_agent(prompt, history):
messages = []
yield messages
for msg in stream_from_transformers_agent(agent, prompt):
messages.append(msg)
for msg in stream_to_gradio(agent, prompt):
messages.append(asdict(msg)) # type: ignore
yield messages
yield messages

with gr.Blocks() as demo:
stored_message = gr.State([])
chatbot = gr.Chatbot(label="Agent",
type="messages",
avatar_images=(None, "https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png"))
text_input = gr.Textbox(lines=1, label="Chat Message")
text_input.submit(lambda s: (s, ""), [text_input], [stored_message, text_input]).then(interact_with_agent, [stored_message, chatbot], [chatbot])

demo = gr.ChatInterface(
interact_with_agent,
chatbot= gr.Chatbot(
label="Agent",
type="messages",
avatar_images=(
None,
"https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png",
),
),
examples=[
["Generate an image of an astronaut riding an alligator"],
["I am writing a children's book for my daughter. Can you help me with some illustrations?"],
],
type="messages",
)

if __name__ == "__main__":
demo.launch()
64 changes: 0 additions & 64 deletions demo/agent_chatbot/utils.py

This file was deleted.

2 changes: 1 addition & 1 deletion demo/browserstate/run.ipynb
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: browserstate"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import random\n", "import string\n", "import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"Your Username and Password will get saved in the browser's local storage. \"\n", " \"If you refresh the page, the values will be retained.\")\n", " username = gr.Textbox(label=\"Username\")\n", " password = gr.Textbox(label=\"Password\", type=\"password\")\n", " btn = gr.Button(\"Generate Randomly\")\n", " local_storage = gr.BrowserState([\"\", \"\"])\n", "\n", " @btn.click(outputs=[username, password])\n", " def generate_randomly():\n", " u = \"\".join(random.choices(string.ascii_letters + string.digits, k=10))\n", " p = \"\".join(random.choices(string.ascii_letters + string.digits, k=10))\n", " return u, p\n", "\n", " @demo.load(inputs=[local_storage], outputs=[username, password])\n", " def load_from_local_storage(saved_values):\n", " print(\"loading from local storage\", saved_values)\n", " return saved_values[0], saved_values[1]\n", "\n", " @gr.on([username.change, password.change], inputs=[username, password], outputs=[local_storage])\n", " def save_to_local_storage(username, password):\n", " return [username, password]\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: browserstate"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import random\n", "import string\n", "import gradio as gr\n", "import time\n", "with gr.Blocks() as demo:\n", " gr.Markdown(\"Your Username and Password will get saved in the browser's local storage. \"\n", " \"If you refresh the page, the values will be retained.\")\n", " username = gr.Textbox(label=\"Username\")\n", " password = gr.Textbox(label=\"Password\", type=\"password\")\n", " btn = gr.Button(\"Generate Randomly\")\n", " local_storage = gr.BrowserState([\"\", \"\"])\n", " saved_message = gr.Markdown(\"\u2705 Saved to local storage\", visible=False)\n", "\n", " @btn.click(outputs=[username, password])\n", " def generate_randomly():\n", " u = \"\".join(random.choices(string.ascii_letters + string.digits, k=10))\n", " p = \"\".join(random.choices(string.ascii_letters + string.digits, k=10))\n", " return u, p\n", "\n", " @demo.load(inputs=[local_storage], outputs=[username, password])\n", " def load_from_local_storage(saved_values):\n", " print(\"loading from local storage\", saved_values)\n", " return saved_values[0], saved_values[1]\n", "\n", " @gr.on([username.change, password.change], inputs=[username, password], outputs=[local_storage])\n", " def save_to_local_storage(username, password):\n", " return [username, password]\n", "\n", " @gr.on(local_storage.change, outputs=[saved_message])\n", " def show_saved_message():\n", " timestamp = time.strftime(\"%I:%M:%S %p\")\n", " return gr.Markdown(\n", " f\"\u2705 Saved to local storage at {timestamp}\",\n", " visible=True\n", " )\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
11 changes: 10 additions & 1 deletion demo/browserstate/run.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import random
import string
import gradio as gr

import time
with gr.Blocks() as demo:
gr.Markdown("Your Username and Password will get saved in the browser's local storage. "
"If you refresh the page, the values will be retained.")
username = gr.Textbox(label="Username")
password = gr.Textbox(label="Password", type="password")
btn = gr.Button("Generate Randomly")
local_storage = gr.BrowserState(["", ""])
saved_message = gr.Markdown("✅ Saved to local storage", visible=False)

@btn.click(outputs=[username, password])
def generate_randomly():
Expand All @@ -25,4 +26,12 @@ def load_from_local_storage(saved_values):
def save_to_local_storage(username, password):
return [username, password]

@gr.on(local_storage.change, outputs=[saved_message])
def show_saved_message():
timestamp = time.strftime("%I:%M:%S %p")
return gr.Markdown(
f"✅ Saved to local storage at {timestamp}",
visible=True
)

demo.launch()
Loading

0 comments on commit 556b805

Please sign in to comment.