kotaemon/knowledgehub/llms/chats/base.py
Tuan Anh Nguyen Dang (Tadashi_Cin) 3cceec63ef [AUR-431] Add ReAct Agent (#34)
* add base Tool

* minor update test_tool

* update test dependency

* update test dependency

* Fix namespace conflict

* update test

* add base Agent Interface, add ReWoo Agent

* minor update

* update test

* fix typo

* remove unneeded print

* update rewoo agent

* add LLMTool

* update BaseAgent type

* add ReAct agent

* add ReAct agent

* minor update

* minor update

* minor update

* minor update

* update docstring

* fix max_iteration

---------

Co-authored-by: trducng <trungduc1992@gmail.com>
2023-10-02 11:29:12 +07:00

83 lines
2.7 KiB
Python

from typing import List, Type, TypeVar
from langchain.schema.language_model import BaseLanguageModel
from langchain.schema.messages import BaseMessage, HumanMessage
from theflow.base import Param
from ...base import BaseComponent
from ..base import LLMInterface
Message = TypeVar("Message", bound=BaseMessage)
class ChatLLM(BaseComponent):
...
class LangchainChatLLM(ChatLLM):
_lc_class: Type[BaseLanguageModel]
def __init__(self, **params):
if self._lc_class is None:
raise AttributeError(
"Should set _lc_class attribute to the LLM class from Langchain "
"if using LLM from Langchain"
)
self._kwargs: dict = {}
for param in list(params.keys()):
if param in self._lc_class.__fields__:
self._kwargs[param] = params.pop(param)
super().__init__(**params)
@Param.decorate(no_cache=True)
def agent(self) -> BaseLanguageModel:
return self._lc_class(**self._kwargs)
def run_raw(self, text: str, **kwargs) -> LLMInterface:
message = HumanMessage(content=text)
return self.run_document([message], **kwargs)
def run_batch_raw(self, text: List[str], **kwargs) -> List[LLMInterface]:
inputs = [[HumanMessage(content=each)] for each in text]
return self.run_batch_document(inputs, **kwargs)
def run_document(self, text: List[Message], **kwargs) -> LLMInterface:
pred = self.agent.generate([text], **kwargs) # type: ignore
return LLMInterface(
text=[each.text for each in pred.generations[0]],
completion_tokens=pred.llm_output["token_usage"]["completion_tokens"],
total_tokens=pred.llm_output["token_usage"]["total_tokens"],
prompt_tokens=pred.llm_output["token_usage"]["prompt_tokens"],
logits=[],
)
def run_batch_document(
self, text: List[List[Message]], **kwargs
) -> List[LLMInterface]:
outputs = []
for each_text in text:
outputs.append(self.run_document(each_text, **kwargs))
return outputs
def is_document(self, text, **kwargs) -> bool:
if isinstance(text, str):
return False
elif isinstance(text, List) and isinstance(text[0], str):
return False
return True
def is_batch(self, text, **kwargs) -> bool:
if isinstance(text, str):
return False
elif isinstance(text, List):
if isinstance(text[0], BaseMessage):
return False
return True
def __setattr__(self, name, value):
if name in self._lc_class.__fields__:
setattr(self.agent, name, value)
else:
super().__setattr__(name, value)