rusticai-langchain 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.1
2
+ Name: rusticai-langchain
3
+ Version: 0.0.1
4
+ Summary: Rustic AI module with LangChain integrations
5
+ Home-page: https://www.rustic.ai/
6
+ License: Apache-2.0
7
+ Author: Dragonscale Industries Inc.
8
+ Author-email: dev@dragonscale.ai
9
+ Requires-Python: >=3.12,<4.0
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Provides-Extra: test
15
+ Requires-Dist: langchain-core (>=0.3.51,<0.4.0)
16
+ Requires-Dist: langchain-openai (>=0.3.12,<0.4.0)
17
+ Requires-Dist: langchain-text-splitters (>=0.3.8,<0.4.0)
18
+ Requires-Dist: rusticai-core (>=0.0.5,<0.1.0)
19
+ Project-URL: Repository, https://github.com/rustic-ai/python-framework
20
+ Project-URL: Rustic AI Core, https://pypi.org/project/rusticai-core/
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Rustic AI LangChain
24
+
25
+ Rustic AI module with [LangChain](https://www.langchain.com/) integrations.
26
+
27
+ ## Installing
28
+
29
+ ```shell
30
+ pip install rusticai-langchain
31
+ ```
32
+ **Note:** It depends on [rusticai-core](https://pypi.org/project/rusticai-core/).
33
+
34
+
35
+ ## Building from Source
36
+
37
+ ```shell
38
+ poetry install --with dev
39
+ poetry build
40
+ ```
41
+
@@ -0,0 +1,18 @@
1
+ # Rustic AI LangChain
2
+
3
+ Rustic AI module with [LangChain](https://www.langchain.com/) integrations.
4
+
5
+ ## Installing
6
+
7
+ ```shell
8
+ pip install rusticai-langchain
9
+ ```
10
+ **Note:** It depends on [rusticai-core](https://pypi.org/project/rusticai-core/).
11
+
12
+
13
+ ## Building from Source
14
+
15
+ ```shell
16
+ poetry install --with dev
17
+ poetry build
18
+ ```
@@ -0,0 +1,72 @@
1
+ [build-system]
2
+ requires = ["poetry-core"]
3
+ build-backend = "poetry.core.masonry.api"
4
+
5
+ [tool.poetry]
6
+ name = "rusticai-langchain"
7
+ version = "0.0.1"
8
+ description = "Rustic AI module with LangChain integrations"
9
+ authors = ["Dragonscale Industries Inc. <dev@dragonscale.ai>"]
10
+ license = "Apache-2.0"
11
+ readme = "README.md"
12
+ homepage = "https://www.rustic.ai/"
13
+ repository = "https://github.com/rustic-ai/python-framework"
14
+ packages = [{ include = "rustic_ai", from = "src" }]
15
+
16
+ [tool.poetry.urls]
17
+ "Rustic AI Core" = "https://pypi.org/project/rusticai-core/"
18
+
19
+ [tool.poetry.dependencies]
20
+ python = "^3.12"
21
+ rusticai-core = { version = "0.0.5"}
22
+ langchain-core = "^0.3.51"
23
+ langchain-openai = "^0.3.12"
24
+ langchain-text-splitters = "^0.3.8"
25
+
26
+ [tool.poetry-monorepo.deps]
27
+
28
+
29
+ [tool.poetry.group.dev]
30
+ optional = true
31
+
32
+ [tool.poetry.group.dev.dependencies]
33
+ pytest = "^8.3.4"
34
+ black = { version = "^24.2.0", extras = ["jupyter"] }
35
+ flake8 = "^7.1.2"
36
+ tox = "^4.24.1"
37
+ isort = "^6.0.0"
38
+ mypy = "^1.15.0"
39
+
40
+ [tool.poetry.extras]
41
+ test = ["pytest"]
42
+
43
+ [tool.black]
44
+ line-length = 120
45
+ target-version = ['py312']
46
+ include = '\.pyi?$'
47
+ exclude = '''
48
+ /(
49
+ \.git
50
+ | \.mypy_cache
51
+ | \.tox
52
+ | \.venv
53
+ | _build
54
+ | buck-out
55
+ | build
56
+ | dist
57
+ )/
58
+ '''
59
+
60
+ [tool.mypy]
61
+ python_version = "3.12"
62
+ ignore_missing_imports = true
63
+ check_untyped_defs = true
64
+ plugins = "pydantic.mypy"
65
+ explicit_package_bases = true
66
+
67
+
68
+ [tool.isort]
69
+ profile = "black"
70
+ known_third_party = ["pydantic"]
71
+ known_first_party = ["rustic_ai.core", "rustic_ai.langchain"]
72
+
@@ -0,0 +1,72 @@
1
+ from typing import List, Optional
2
+
3
+ from langchain_core.embeddings import Embeddings as LangchainEmbeddings
4
+ from langchain_openai import OpenAIEmbeddings as LangchainOAIE
5
+ from pydantic import BaseModel, Field
6
+
7
+ from rustic_ai.core.guild.agent_ext.depends import DependencyResolver
8
+ from rustic_ai.core.guild.agent_ext.depends.embeddings import Embeddings
9
+ from rustic_ai.core.utils import JsonDict
10
+
11
+ DEFAULT_MODEL: str = "text-embedding-ada-002"
12
+
13
+
14
+ class OpenAIEmbeddingConf(BaseModel):
15
+ openai_api_version: Optional[str] = Field(default=None)
16
+ """Automatically inferred from env var `OPENAI_API_VERSION` if not provided."""
17
+ # to support Azure OpenAI Service custom endpoints
18
+ openai_api_base: Optional[str] = Field(default=None)
19
+ """Base URL path for API requests, leave blank if not using a proxy or service
20
+ emulator."""
21
+ # to support Azure OpenAI Service custom endpoints
22
+ openai_api_type: Optional[str] = None
23
+ # to support explicit proxy for OpenAI
24
+ openai_proxy: Optional[str] = None
25
+ embedding_ctx_length: int = 8191
26
+ """The maximum number of tokens to embed at once."""
27
+ openai_api_key: Optional[str] = Field(default=None)
28
+ """Automatically inferred from env var `OPENAI_API_KEY` if not provided."""
29
+ openai_organization: Optional[str] = Field(default=None)
30
+ """Automatically inferred from env var `OPENAI_ORG_ID` if not provided."""
31
+
32
+
33
+ class OpenAIEmbeddings(Embeddings):
34
+ """
35
+ Embeddings backed by Open AI.
36
+ """
37
+
38
+ def __init__(self, model: str, deployment: str, conf: OpenAIEmbeddingConf):
39
+ self.oaie = LangchainOAIE(
40
+ model=model,
41
+ deployment=deployment,
42
+ **conf.model_dump(exclude_none=True, exclude_unset=True),
43
+ )
44
+
45
+ def embed(self, text: List[str]) -> List[List[float]]:
46
+ return self.oaie.embed_documents(text)
47
+
48
+ @property
49
+ def langchain_embeddings(self) -> LangchainEmbeddings:
50
+ return self.oaie
51
+
52
+
53
+ class OpenAIEmbeddingsResolver(DependencyResolver[Embeddings]):
54
+ memoize_resolution: bool = False
55
+
56
+ def __init__(
57
+ self,
58
+ model_name: str = DEFAULT_MODEL,
59
+ deployment: Optional[str] = None,
60
+ model_conf: JsonDict = {},
61
+ ):
62
+ super().__init__()
63
+ mconf = OpenAIEmbeddingConf.model_validate(model_conf)
64
+
65
+ self.embedding = OpenAIEmbeddings(
66
+ model=model_name,
67
+ deployment=deployment or model_name,
68
+ conf=mconf,
69
+ )
70
+
71
+ def resolve(self, guild_id: str, agent_id: str) -> Embeddings:
72
+ return self.embedding
@@ -0,0 +1,51 @@
1
+ from typing import Callable, Literal, Union
2
+
3
+ from langchain_text_splitters import CharacterTextSplitter
4
+ from pydantic import BaseModel
5
+
6
+ from rustic_ai.core.guild.agent_ext.depends import DependencyResolver
7
+ from rustic_ai.core.guild.agent_ext.depends.text_splitter import TextSplitter
8
+ from rustic_ai.core.utils import JsonDict
9
+
10
+
11
+ class CharacterSplitterConf(BaseModel):
12
+ """
13
+ Configuration for the CharacterSplitter.
14
+ """
15
+
16
+ chunk_size: int = 1000
17
+ chunk_overlap: int = 100
18
+ length_function: Callable[[str], int] = len
19
+ keep_separator: Union[bool, Literal["start", "end"]] = False
20
+ add_start_index: bool = False
21
+ strip_whitespace: bool = True
22
+ separator: str = "\n\n"
23
+ is_separator_regex: bool = False
24
+
25
+
26
+ class CharacterSplitter(TextSplitter):
27
+ """
28
+ Character text splitter that splits text into chunks of a specified size.
29
+ """
30
+
31
+ def __init__(self, conf: CharacterSplitterConf):
32
+ self.splitter = CharacterTextSplitter(
33
+ separator=conf.separator,
34
+ is_separator_regex=conf.is_separator_regex,
35
+ **conf.model_dump(exclude={"separator", "is_separator_regex"}),
36
+ )
37
+
38
+ def split(self, text: str) -> list[str]:
39
+ return self.splitter.split_text(text)
40
+
41
+
42
+ class CharacterSplitterResolver(DependencyResolver[TextSplitter]):
43
+ memoize_resolution: bool = False
44
+
45
+ def __init__(self, conf: JsonDict = {}):
46
+ super().__init__()
47
+ splitter_conf = CharacterSplitterConf.model_validate(conf)
48
+ self.splitter = CharacterSplitter(splitter_conf)
49
+
50
+ def resolve(self, guild_id: str, agent_id: str) -> TextSplitter:
51
+ return self.splitter
@@ -0,0 +1,27 @@
1
+ import shortuuid
2
+ from langchain_core.documents import Document as LCDocument
3
+
4
+ from rustic_ai.core.agents.commons.media import Document
5
+
6
+
7
+ class DocUtils:
8
+ @staticmethod
9
+ def from_langchain(langchain_document: LCDocument) -> Document:
10
+ return Document(
11
+ id=langchain_document.id or shortuuid.uuid(),
12
+ metadata=langchain_document.metadata,
13
+ content=langchain_document.page_content,
14
+ )
15
+
16
+ @staticmethod
17
+ def to_langchain(document: Document) -> LCDocument:
18
+ metadata = document.metadata or {}
19
+ metadata["name"] = document.name
20
+ metadata["mime"] = document.mimetype
21
+ metadata["encoding"] = document.encoding
22
+
23
+ return LCDocument(
24
+ page_content=document.content,
25
+ id=document.id,
26
+ metadata=metadata,
27
+ )
@@ -0,0 +1,34 @@
1
+ from typing import List, Tuple
2
+
3
+ from langchain_core.documents import Document as LCDocument
4
+ from langchain_core.indexing import UpsertResponse as LCUpsertResponse
5
+
6
+ from rustic_ai.core.guild.agent_ext.depends.vectorstore.vectorstore import (
7
+ UpsertResponse,
8
+ VectorSearchResult,
9
+ VectorSearchResults,
10
+ )
11
+ from rustic_ai.langchain.utils.doc_utils import DocUtils
12
+
13
+
14
+ class VectorSearchUtils:
15
+ @staticmethod
16
+ def from_langchain_response(langchain_response: Tuple[LCDocument, float]) -> VectorSearchResult: # pragma: no cover
17
+ langchain_doc, score = langchain_response
18
+ return VectorSearchResult(document=DocUtils.from_langchain(langchain_doc), score=score)
19
+
20
+ @staticmethod
21
+ def from_langchain_responses(
22
+ query: str, langchain_responses: List[Tuple[LCDocument, float]]
23
+ ) -> VectorSearchResults:
24
+ results = [
25
+ VectorSearchResult(document=DocUtils.from_langchain(langchain_doc), score=score)
26
+ for langchain_doc, score in langchain_responses
27
+ ]
28
+ return VectorSearchResults(query=query, results=results)
29
+
30
+
31
+ class UpsertResponseUtils:
32
+ @staticmethod
33
+ def from_langchain(langchain_response: LCUpsertResponse) -> UpsertResponse: # pragma: no cover
34
+ return UpsertResponse(succeeded=langchain_response["succeeded"], failed=langchain_response["failed"])