Skip to content

Gradio

LLMChat

Source code in supermat/gradio/__init__.py
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
class LLMChat:
    def __init__(self):
        self.chat_model = None
        self.retriever = None
        self.handler_name = "PyMuPDFParser"

    @property
    def handler(self) -> Handler:
        return FileProcessor.get_handler(self.handler_name)

    def initialize_client(
        self,
        provider: str,
        model: str,
        credentials: str | None = None,
        base_url: str | None = None,
        temperature: float | None = 0.0,
    ) -> str:
        """Initialize the LangChain chat model based on selected provider."""
        gr.Info("Initializaing LLM")
        base_url = base_url if base_url else None
        self.provider = provider
        self.model = model

        if TYPE_CHECKING:
            assert isinstance(credentials, SecretStr)

        try:
            match (provider):
                case LLMProvider.ollama:
                    from langchain_ollama.llms import OllamaLLM  # noqa: I900

                    self.chat_model = OllamaLLM(model=model, temperature=temperature, base_url=base_url)
                case LLMProvider.anthropic:
                    from langchain_anthropic import ChatAnthropic  # noqa: I900

                    self.chat_model = ChatAnthropic(
                        model_name=model,
                        temperature=temperature,
                        timeout=None,
                        api_key=credentials,
                        stop=None,
                        base_url=base_url,
                    )
                case LLMProvider.openai:
                    from langchain_openai import ChatOpenAI  # noqa: I900

                    temperature = 0.7 if temperature is None else temperature
                    self.chat_model = ChatOpenAI(
                        model=model, temperature=temperature, api_key=credentials, base_url=base_url
                    )
                case LLMProvider.azure_openai:
                    from langchain_openai import AzureChatOpenAI

                    if not base_url:
                        raise gr.Error("Azure OpenAI requires API Enpoint")

                    api_version = None
                    api_version_match = re.search(r"[?&]api-version=([^&]+)", base_url)

                    if api_version_match:
                        api_version = api_version_match.group(1)
                    else:
                        raise gr.Error("Pass in `api_version` as query parameter in Azure API Endpoint")

                    self.chat_model = AzureChatOpenAI(
                        api_key=credentials,
                        azure_endpoint=base_url,
                        azure_deployment=model,
                        api_version=api_version,
                        temperature=0,
                    )
                case _:
                    raise gr.Error(f"Invalid LLM Provider {provider}")

            gr.Info(f"{self.chat_model.get_name()} initialized successfully!")
            return f"{self.chat_model.get_name()} initialized successfully!"

        except Exception as e:
            raise gr.Error(f"Error initializing client: {str(e)}")

    def update_handler(self, handler_name: str):
        self.handler_name = handler_name

    def parse_files(self, collection_name: str, pdf_files: Sequence[Path | str]) -> str:
        gr.Info(f"Parsing {len(pdf_files)} files.")
        pdf_files = list(map(Path, pdf_files))
        if TYPE_CHECKING:
            pdf_files = cast(list[Path], pdf_files)

        if not all(f.exists() for f in pdf_files):
            raise gr.Error("Few files do not exist.")
        non_pdf_files = [f.name for f in pdf_files if f.suffix.lower() != ".pdf"]
        if non_pdf_files:
            raise gr.Error(f"Following files are not pdf: \n{'\n'.join(non_pdf_files)}")

        parsed_files = Parallel(n_jobs=-1, backend="threading")(
            delayed(self.handler.parse_file)(path) for path in pdf_files
        )

        if TYPE_CHECKING:
            parsed_files = cast(list[ParsedDocumentType], parsed_files)

        documents = list(chain.from_iterable(parsed_docs for parsed_docs in parsed_files))

        if TYPE_CHECKING:
            documents = cast(ParsedDocumentType, documents)

        retriever = SupermatRetriever(
            parsed_docs=documents,
            vector_store=Chroma(
                embedding_function=HuggingFaceEmbeddings(
                    model_name="thenlper/gte-base",
                ),
                persist_directory="./chromadb",
                collection_name=collection_name,
            ),
        )
        self.retriever = retriever
        gr.Info("Files parsed successfully.")
        return "Files parsed successfully."

    def convert_history_to_messages(self, history: list[dict]) -> list[HumanMessage | AIMessage]:
        """Convert Gradio chat history to LangChain message format."""

        return [
            HumanMessage(content=msg["content"]) if msg["role"] == "user" else AIMessage(content=msg["content"])
            for msg in history
        ]

    @property
    def chain(self) -> RunnableSerializable:
        assert self.chat_model and self.retriever
        chain = get_default_chain(self.retriever, self.chat_model, substitute_references=False, return_context=False)
        return chain

    def chat(self, message: str, _history):
        """Process chat message using LangChain chat model."""
        if not self.chat_model:
            raise gr.Error("Please initialize an LLM provider first!")

        if not self.retriever:
            raise gr.Error("Please parse relevant pdf documents!")

        try:
            # history_langchain_format = self.convert_history_to_messages(history)
            # history_langchain_format.append(HumanMessage(content=message))
            gpt_response = self.chain.invoke(message)
            gpt_response = gpt_response if isinstance(gpt_response, str) else gpt_response.content
            gpt_response = re.sub(r"<cite\b[^>]*?/>", r"``\g<0>``", gpt_response)
            return gpt_response

        except Exception as e:
            raise gr.Error(f"Error: {str(e)}\n{traceback.format_exc()}")

    def refresh(self) -> list[str]:
        if not self.retriever:
            raise gr.Error("Parse pdf documents first.")
        return list(self.retriever._document_index_map.keys())

    def get_document(self, document: str) -> list[dict]:
        if not self.retriever:
            raise gr.Error("Parse pdf documents first.")
        if document == "All":
            return ParsedDocument.dump_python(self.retriever.parsed_docs)
        elif document == "None":
            return []
        else:
            filtered_docs = [parsed_doc for parsed_doc in self.retriever.parsed_docs if parsed_doc.document == document]
            return ParsedDocument.dump_python(filtered_docs)

chat(message, _history)

Process chat message using LangChain chat model.

Source code in supermat/gradio/__init__.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def chat(self, message: str, _history):
    """Process chat message using LangChain chat model."""
    if not self.chat_model:
        raise gr.Error("Please initialize an LLM provider first!")

    if not self.retriever:
        raise gr.Error("Please parse relevant pdf documents!")

    try:
        # history_langchain_format = self.convert_history_to_messages(history)
        # history_langchain_format.append(HumanMessage(content=message))
        gpt_response = self.chain.invoke(message)
        gpt_response = gpt_response if isinstance(gpt_response, str) else gpt_response.content
        gpt_response = re.sub(r"<cite\b[^>]*?/>", r"``\g<0>``", gpt_response)
        return gpt_response

    except Exception as e:
        raise gr.Error(f"Error: {str(e)}\n{traceback.format_exc()}")

convert_history_to_messages(history)

Convert Gradio chat history to LangChain message format.

Source code in supermat/gradio/__init__.py
167
168
169
170
171
172
173
def convert_history_to_messages(self, history: list[dict]) -> list[HumanMessage | AIMessage]:
    """Convert Gradio chat history to LangChain message format."""

    return [
        HumanMessage(content=msg["content"]) if msg["role"] == "user" else AIMessage(content=msg["content"])
        for msg in history
    ]

initialize_client(provider, model, credentials=None, base_url=None, temperature=0.0)

Initialize the LangChain chat model based on selected provider.

Source code in supermat/gradio/__init__.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def initialize_client(
    self,
    provider: str,
    model: str,
    credentials: str | None = None,
    base_url: str | None = None,
    temperature: float | None = 0.0,
) -> str:
    """Initialize the LangChain chat model based on selected provider."""
    gr.Info("Initializaing LLM")
    base_url = base_url if base_url else None
    self.provider = provider
    self.model = model

    if TYPE_CHECKING:
        assert isinstance(credentials, SecretStr)

    try:
        match (provider):
            case LLMProvider.ollama:
                from langchain_ollama.llms import OllamaLLM  # noqa: I900

                self.chat_model = OllamaLLM(model=model, temperature=temperature, base_url=base_url)
            case LLMProvider.anthropic:
                from langchain_anthropic import ChatAnthropic  # noqa: I900

                self.chat_model = ChatAnthropic(
                    model_name=model,
                    temperature=temperature,
                    timeout=None,
                    api_key=credentials,
                    stop=None,
                    base_url=base_url,
                )
            case LLMProvider.openai:
                from langchain_openai import ChatOpenAI  # noqa: I900

                temperature = 0.7 if temperature is None else temperature
                self.chat_model = ChatOpenAI(
                    model=model, temperature=temperature, api_key=credentials, base_url=base_url
                )
            case LLMProvider.azure_openai:
                from langchain_openai import AzureChatOpenAI

                if not base_url:
                    raise gr.Error("Azure OpenAI requires API Enpoint")

                api_version = None
                api_version_match = re.search(r"[?&]api-version=([^&]+)", base_url)

                if api_version_match:
                    api_version = api_version_match.group(1)
                else:
                    raise gr.Error("Pass in `api_version` as query parameter in Azure API Endpoint")

                self.chat_model = AzureChatOpenAI(
                    api_key=credentials,
                    azure_endpoint=base_url,
                    azure_deployment=model,
                    api_version=api_version,
                    temperature=0,
                )
            case _:
                raise gr.Error(f"Invalid LLM Provider {provider}")

        gr.Info(f"{self.chat_model.get_name()} initialized successfully!")
        return f"{self.chat_model.get_name()} initialized successfully!"

    except Exception as e:
        raise gr.Error(f"Error initializing client: {str(e)}")