Skip to content

Commit e62f2c0

Browse files
liuxukun2000Satan
and
Satan
authored
remove langchain (#42)
* add log mode, refine doc * fix react * remove langchain --------- Co-authored-by: Satan <liuxk2019@mail.sustech.edu.cn>
1 parent 99e27e2 commit e62f2c0

File tree

10 files changed

+574
-36
lines changed

10 files changed

+574
-36
lines changed

gentopia/tools/calculator.py

+25-7
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,31 @@
11
from typing import AnyStr
2-
3-
from langchain import OpenAI, LLMMathChain
4-
2+
import re
3+
import numexpr
54
from .basetool import *
5+
import math
66

77
class CalculatorArgs(BaseModel):
88
expression: str = Field(..., description="A mathematical expression.")
99

10+
def _evaluate_expression(expression: str) -> str:
11+
try:
12+
local_dict = {"pi": math.pi, "e": math.e}
13+
output = str(
14+
numexpr.evaluate(
15+
expression.strip(),
16+
global_dict={}, # restrict access to globals
17+
local_dict=local_dict, # add common mathematical functions
18+
)
19+
)
20+
except Exception as e:
21+
raise ValueError(
22+
f'LLMMathChain._evaluate("{expression}") raised error: {e}.'
23+
" Please try again with a valid numerical expression"
24+
)
25+
26+
# Remove any leading and trailing brackets from the output
27+
return re.sub(r"^\[|\]$", "", output)
28+
1029
class Calculator(BaseTool):
1130
"""docstring for Calculator"""
1231
name = "calculator"
@@ -15,10 +34,9 @@ class Calculator(BaseTool):
1534
args_schema: Optional[Type[BaseModel]] = CalculatorArgs
1635

1736
def _run(self, expression: AnyStr) -> Any:
18-
llm = OpenAI(temperature=0)
19-
tool = LLMMathChain(llm=llm, verbose=self.verbose)
20-
response = tool(expression)
21-
evidence = response["answer"].replace("Answer:", "").strip()
37+
38+
response = _evaluate_expression(expression)
39+
evidence = response.strip()
2240
return evidence
2341

2442
async def _arun(self, *args: Any, **kwargs: Any) -> Any:

gentopia/tools/gradio_tools/tools/gradio_tool.py

-20
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,6 @@
99
from gradio_client.client import Job
1010
from gradio_client.utils import QueueError
1111

12-
try:
13-
import langchain as lc
14-
15-
LANGCHAIN_INSTALLED = True
16-
except (ModuleNotFoundError, ImportError):
17-
LANGCHAIN_INSTALLED = False
18-
19-
2012
class GradioTool:
2113
def __init__(
2214
self,
@@ -110,17 +102,5 @@ def block(self):
110102
self._block = gr.load(name=self.src, src="spaces")
111103
return self._block
112104

113-
# Optional langchain functionalities
114-
@property
115-
def langchain(self) -> "langchain.agents.Tool": # type: ignore
116-
if not LANGCHAIN_INSTALLED:
117-
raise ModuleNotFoundError(
118-
"langchain must be installed to access langchain tool"
119-
)
120-
121-
return lc.agents.Tool( # type: ignore
122-
name=self.name, func=self.run, description=self.description
123-
)
124-
125105
def __repr__(self) -> str:
126106
return f"GradioTool(name={self.name}, src={self.src})"

gentopia/tools/search_doc.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
from typing import AnyStr
2-
3-
from langchain.document_loaders import TextLoader
4-
from langchain.indexes import VectorstoreIndexCreator
5-
62
from .basetool import *
3+
from .utils.document_loaders.text_loader import TextLoader
4+
from .utils.vector_store import VectorstoreIndexCreator
75

86

97
class SearchDoc(BaseTool):
@@ -16,7 +14,7 @@ class SearchDoc(BaseTool):
1614

1715
def _run(self, query: AnyStr) -> AnyStr:
1816
loader = TextLoader(self.doc_path)
19-
vector_store = VectorstoreIndexCreator().from_loaders([loader]).vectorstore
17+
vector_store = VectorstoreIndexCreator().from_loaders([loader])
2018
evidence = vector_store.similarity_search(query, k=1)[0].page_content
2119
return evidence
2220

gentopia/tools/utils/document_loaders/__init__.py

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from abc import abstractmethod, ABC
2+
from typing import Optional, List, Iterator, Sequence, Any, Callable
3+
4+
from gentopia.tools.utils import Document
5+
from gentopia.tools.utils.document_loaders.text_splitter import TextSplitter, RecursiveCharacterTextSplitter
6+
7+
8+
class BaseLoader(ABC):
9+
"""Interface for loading documents.
10+
11+
Implementations should implement the lazy-loading method using generators
12+
to avoid loading all documents into memory at once.
13+
14+
The `load` method will remain as is for backwards compatibility, but it's
15+
implementation should be just `list(self.lazy_load())`.
16+
"""
17+
18+
# Sub-classes should implement this method
19+
# as return list(self.lazy_load()).
20+
# This method returns a List which is materialized in memory.
21+
@abstractmethod
22+
def load(self) -> List[Document]:
23+
"""Load data into document objects."""
24+
25+
def load_and_split(
26+
self, text_splitter: Optional[TextSplitter] = None
27+
) -> List[Document]:
28+
"""Load documents and split into chunks."""
29+
if text_splitter is None:
30+
_text_splitter: TextSplitter = RecursiveCharacterTextSplitter()
31+
else:
32+
_text_splitter = text_splitter
33+
docs = self.load()
34+
return _text_splitter.split_documents(docs)
35+
36+
# Attention: This method will be upgraded into an abstractmethod once it's
37+
# implemented in all the existing subclasses.
38+
def lazy_load(
39+
self,
40+
) -> Iterator[Document]:
41+
"""A lazy loader for document content."""
42+
raise NotImplementedError(
43+
f"{self.__class__.__name__} does not implement lazy_load()"
44+
)

gentopia/tools/utils/document_loaders.py gentopia/tools/utils/document_loaders/text_loader.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
from typing import Optional, List, Iterator, Sequence, Any, Callable
33

44
from gentopia.tools.utils import Document
5+
from gentopia.tools.utils.document_loaders.base_loader import BaseLoader
56

6-
class TextLoader:
7+
8+
class TextLoader(BaseLoader):
79
"""Load text files."""
810

911
def __init__(self, file_path: str, encoding: Optional[str] = None):

0 commit comments

Comments
 (0)