Skip to content
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

gr.load_chat: Allow loading any openai-compatible server immediately as a ChatInterface #10222

Merged
merged 9 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/thick-dingos-help.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"gradio": minor
---

feat:gr.load_chat: Allow loading any openai chatbot immediately as a ChatInterface
2 changes: 1 addition & 1 deletion gradio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
on,
)
from gradio.exceptions import Error
from gradio.external import load
from gradio.external import load, load_chat
from gradio.flagging import (
CSVLogger,
FlaggingCallback,
Expand Down
5 changes: 4 additions & 1 deletion gradio/chat_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,10 @@ def __init__(
self.type = type
self.multimodal = multimodal
self.concurrency_limit = concurrency_limit
self.fn = fn
if isinstance(fn, ChatInterface):
self.fn = fn.fn
else:
self.fn = fn
self.is_async = inspect.iscoroutinefunction(
self.fn
) or inspect.isasyncgenfunction(self.fn)
Expand Down
75 changes: 74 additions & 1 deletion gradio/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import re
import tempfile
import warnings
from collections.abc import Callable
from collections.abc import Callable, Generator
from pathlib import Path
from typing import TYPE_CHECKING, Literal

Expand All @@ -30,6 +30,7 @@

if TYPE_CHECKING:
from gradio.blocks import Blocks
from gradio.chat_interface import ChatInterface
from gradio.interface import Interface


Expand Down Expand Up @@ -581,3 +582,75 @@ def fn(*data):
kwargs["_api_mode"] = True
interface = gradio.Interface(**kwargs)
return interface


def load_chat(
aliabid94 marked this conversation as resolved.
Show resolved Hide resolved
base_url: str,
model: str,
token: str | None = None,
*,
system_message: str | None = None,
streaming: bool = True,
) -> ChatInterface:
"""
Load a chat interface from an OpenAI API chat compatible endpoint.
Parameters:
base_url: The base URL of the endpoint.
model: The model name.
token: The API token.
system_message: The system message for the conversation, if any.
streaming: Whether the response should be streamed.
"""
try:
from openai import OpenAI
except ImportError as e:
raise ImportError(
"To use OpenAI API Client, you must install the `openai` package. You can install it with `pip install openai`."
) from e
from gradio.chat_interface import ChatInterface

client = OpenAI(api_key=token, base_url=base_url)
start_message = (
[{"role": "system", "content": system_message}] if system_message else []
)

def open_api(message: str, history: list | None) -> str:
history = history or start_message
history = format_tuples_if_needed(history)
aliabid94 marked this conversation as resolved.
Show resolved Hide resolved
return (
client.chat.completions.create(
model=model,
messages=history + [{"role": "user", "content": message}],
)
.choices[0]
.message.content
)

def open_api_stream(
message: str, history: list | None
) -> Generator[str, None, None]:
history = history or start_message
history = format_tuples_if_needed(history)
stream = client.chat.completions.create(
model=model,
messages=history + [{"role": "user", "content": message}],
stream=True,
)
response = ""
for chunk in stream:
response += chunk.choices[0].delta.content
yield response

return ChatInterface(open_api_stream if streaming else open_api, type="messages")


def format_tuples_if_needed(history: list) -> list[dict]:
if len(history) == 0 or not isinstance(history[0], list):
aliabid94 marked this conversation as resolved.
Show resolved Hide resolved
return history
messages = []
for user, assistant in history:
aliabid94 marked this conversation as resolved.
Show resolved Hide resolved
if user:
messages.append({"role": "user", "content": user})
if assistant:
messages.append({"role": "assistant", "content": assistant})
return messages
Loading