codekingpro commited on
Commit
088638e
·
verified ·
1 Parent(s): fb72263

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/__pycache__/__init__.cpython-311.pyc +0 -0
  2. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/__pycache__/llm_requests.cpython-311.pyc +0 -0
  3. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/ernie_functions/__init__.py +17 -0
  4. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/ernie_functions/base.py +553 -0
  5. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/__init__.py +1 -0
  6. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/arangodb.py +273 -0
  7. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/base.py +104 -0
  8. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/cypher.py +421 -0
  9. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/cypher_utils.py +267 -0
  10. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/falkordb.py +189 -0
  11. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/gremlin.py +253 -0
  12. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/hugegraph.py +138 -0
  13. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/kuzu.py +196 -0
  14. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/memgraph.py +316 -0
  15. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/nebulagraph.py +138 -0
  16. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/neptune_cypher.py +254 -0
  17. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/neptune_sparql.py +242 -0
  18. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/ontotext_graphdb.py +222 -0
  19. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/prompts.py +468 -0
  20. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/sparql.py +184 -0
  21. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/natbot/__init__.py +8 -0
  22. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/natbot/base.py +3 -0
  23. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/natbot/crawler.py +7 -0
  24. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/natbot/prompt.py +3 -0
  25. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/__init__.py +0 -0
  26. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/chain.py +230 -0
  27. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/prompts.py +57 -0
  28. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/requests_chain.py +62 -0
  29. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/response_chain.py +57 -0
  30. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__init__.py +0 -0
  31. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__pycache__/base.cpython-311.pyc +0 -0
  32. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__pycache__/enforcement_filters.cpython-311.pyc +0 -0
  33. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__pycache__/models.cpython-311.pyc +0 -0
  34. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__pycache__/utilities.cpython-311.pyc +0 -0
  35. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/base.py +386 -0
  36. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/enforcement_filters.py +532 -0
  37. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/models.py +151 -0
  38. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/utilities.py +542 -0
  39. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/__init__.cpython-311.pyc +0 -0
  40. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/base.cpython-311.pyc +0 -0
  41. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/facebook_messenger.cpython-311.pyc +0 -0
  42. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/gmail.cpython-311.pyc +0 -0
  43. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/imessage.cpython-311.pyc +0 -0
  44. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/langsmith.cpython-311.pyc +0 -0
  45. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/slack.cpython-311.pyc +0 -0
  46. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/telegram.cpython-311.pyc +0 -0
  47. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/utils.cpython-311.pyc +0 -0
  48. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/whatsapp.cpython-311.pyc +0 -0
  49. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/__pycache__/__init__.cpython-311.pyc +0 -0
  50. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/__pycache__/astradb.cpython-311.pyc +0 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.19 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/__pycache__/llm_requests.cpython-311.pyc ADDED
Binary file (5.31 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/ernie_functions/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_classic.chains.ernie_functions.base import (
2
+ convert_to_ernie_function,
3
+ create_ernie_fn_chain,
4
+ create_ernie_fn_runnable,
5
+ create_structured_output_chain,
6
+ create_structured_output_runnable,
7
+ get_ernie_output_parser,
8
+ )
9
+
10
+ __all__ = [
11
+ "convert_to_ernie_function",
12
+ "create_structured_output_chain",
13
+ "create_ernie_fn_chain",
14
+ "create_structured_output_runnable",
15
+ "create_ernie_fn_runnable",
16
+ "get_ernie_output_parser",
17
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/ernie_functions/base.py ADDED
@@ -0,0 +1,553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Methods for creating chains that use Ernie function-calling APIs."""
2
+
3
+ import inspect
4
+ from typing import (
5
+ Any,
6
+ Callable,
7
+ Dict,
8
+ List,
9
+ Optional,
10
+ Sequence,
11
+ Tuple,
12
+ Type,
13
+ Union,
14
+ cast,
15
+ )
16
+
17
+ from langchain_classic.chains import LLMChain
18
+ from langchain_core.language_models import BaseLanguageModel
19
+ from langchain_core.output_parsers import (
20
+ BaseGenerationOutputParser,
21
+ BaseLLMOutputParser,
22
+ BaseOutputParser,
23
+ )
24
+ from langchain_core.prompts import BasePromptTemplate
25
+ from langchain_core.runnables import Runnable
26
+ from langchain_core.utils.pydantic import is_basemodel_subclass
27
+ from pydantic import BaseModel
28
+
29
+ from langchain_community.output_parsers.ernie_functions import (
30
+ JsonOutputFunctionsParser,
31
+ PydanticAttrOutputFunctionsParser,
32
+ PydanticOutputFunctionsParser,
33
+ )
34
+ from langchain_community.utils.ernie_functions import convert_pydantic_to_ernie_function
35
+
36
+ PYTHON_TO_JSON_TYPES = {
37
+ "str": "string",
38
+ "int": "number",
39
+ "float": "number",
40
+ "bool": "boolean",
41
+ }
42
+
43
+
44
+ def _get_python_function_name(function: Callable) -> str:
45
+ """Get the name of a Python function."""
46
+ return function.__name__
47
+
48
+
49
+ def _parse_python_function_docstring(function: Callable) -> Tuple[str, dict]:
50
+ """Parse the function and argument descriptions from the docstring of a function.
51
+
52
+ Assumes the function docstring follows Google Python style guide.
53
+ """
54
+ docstring = inspect.getdoc(function)
55
+ if docstring:
56
+ docstring_blocks = docstring.split("\n\n")
57
+ descriptors = []
58
+ args_block = None
59
+ past_descriptors = False
60
+ for block in docstring_blocks:
61
+ if block.startswith("Args:"):
62
+ args_block = block
63
+ break
64
+ elif block.startswith("Returns:") or block.startswith("Example:"):
65
+ # Don't break in case Args come after
66
+ past_descriptors = True
67
+ elif not past_descriptors:
68
+ descriptors.append(block)
69
+ else:
70
+ continue
71
+ description = " ".join(descriptors)
72
+ else:
73
+ description = ""
74
+ args_block = None
75
+ arg_descriptions = {}
76
+ if args_block:
77
+ arg = None
78
+ for line in args_block.split("\n")[1:]:
79
+ if ":" in line:
80
+ arg, desc = line.split(":")
81
+ arg_descriptions[arg.strip()] = desc.strip()
82
+ elif arg:
83
+ arg_descriptions[arg.strip()] += " " + line.strip()
84
+ return description, arg_descriptions
85
+
86
+
87
+ def _get_python_function_arguments(function: Callable, arg_descriptions: dict) -> dict:
88
+ """Get JsonSchema describing a Python functions arguments.
89
+
90
+ Assumes all function arguments are of primitive types (int, float, str, bool) or
91
+ are subclasses of pydantic.BaseModel.
92
+ """
93
+ properties = {}
94
+ annotations = inspect.getfullargspec(function).annotations
95
+ for arg, arg_type in annotations.items():
96
+ if arg == "return":
97
+ continue
98
+ if isinstance(arg_type, type) and is_basemodel_subclass(arg_type):
99
+ # Mypy error:
100
+ # "type" has no attribute "schema"
101
+ properties[arg] = arg_type.schema() # type: ignore[attr-defined]
102
+ elif arg_type.__name__ in PYTHON_TO_JSON_TYPES:
103
+ properties[arg] = {"type": PYTHON_TO_JSON_TYPES[arg_type.__name__]}
104
+ if arg in arg_descriptions:
105
+ if arg not in properties:
106
+ properties[arg] = {}
107
+ properties[arg]["description"] = arg_descriptions[arg]
108
+ return properties
109
+
110
+
111
+ def _get_python_function_required_args(function: Callable) -> List[str]:
112
+ """Get the required arguments for a Python function."""
113
+ spec = inspect.getfullargspec(function)
114
+ required = spec.args[: -len(spec.defaults)] if spec.defaults else spec.args
115
+ required += [k for k in spec.kwonlyargs if k not in (spec.kwonlydefaults or {})]
116
+
117
+ is_class = type(function) is type
118
+ if is_class and required[0] == "self":
119
+ required = required[1:]
120
+ return required
121
+
122
+
123
+ def convert_python_function_to_ernie_function(
124
+ function: Callable,
125
+ ) -> Dict[str, Any]:
126
+ """Convert a Python function to an Ernie function-calling API compatible dict.
127
+
128
+ Assumes the Python function has type hints and a docstring with a description. If
129
+ the docstring has Google Python style argument descriptions, these will be
130
+ included as well.
131
+ """
132
+ description, arg_descriptions = _parse_python_function_docstring(function)
133
+ return {
134
+ "name": _get_python_function_name(function),
135
+ "description": description,
136
+ "parameters": {
137
+ "type": "object",
138
+ "properties": _get_python_function_arguments(function, arg_descriptions),
139
+ "required": _get_python_function_required_args(function),
140
+ },
141
+ }
142
+
143
+
144
+ def convert_to_ernie_function(
145
+ function: Union[Dict[str, Any], Type[BaseModel], Callable],
146
+ ) -> Dict[str, Any]:
147
+ """Convert a raw function/class to an Ernie function.
148
+
149
+ Args:
150
+ function: Either a dictionary, a pydantic.BaseModel class, or a Python function.
151
+ If a dictionary is passed in, it is assumed to already be a valid Ernie
152
+ function.
153
+
154
+ Returns:
155
+ A dict version of the passed in function which is compatible with the
156
+ Ernie function-calling API.
157
+ """
158
+ if isinstance(function, dict):
159
+ return function
160
+ elif isinstance(function, type) and is_basemodel_subclass(function):
161
+ return cast(Dict, convert_pydantic_to_ernie_function(function))
162
+ elif callable(function):
163
+ return convert_python_function_to_ernie_function(function)
164
+
165
+ else:
166
+ raise ValueError(
167
+ f"Unsupported function type {type(function)}. Functions must be passed in"
168
+ f" as Dict, pydantic.BaseModel, or Callable."
169
+ )
170
+
171
+
172
+ def get_ernie_output_parser(
173
+ functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],
174
+ ) -> Union[BaseOutputParser, BaseGenerationOutputParser]:
175
+ """Get the appropriate function output parser given the user functions.
176
+
177
+ Args:
178
+ functions: Sequence where element is a dictionary, a pydantic.BaseModel class,
179
+ or a Python function. If a dictionary is passed in, it is assumed to
180
+ already be a valid Ernie function.
181
+
182
+ Returns:
183
+ A PydanticOutputFunctionsParser if functions are Pydantic classes, otherwise
184
+ a JsonOutputFunctionsParser. If there's only one function and it is
185
+ not a Pydantic class, then the output parser will automatically extract
186
+ only the function arguments and not the function name.
187
+ """
188
+ function_names = [convert_to_ernie_function(f)["name"] for f in functions]
189
+ if isinstance(functions[0], type) and is_basemodel_subclass(functions[0]):
190
+ if len(functions) > 1:
191
+ pydantic_schema: Union[Dict, Type[BaseModel]] = {
192
+ name: fn for name, fn in zip(function_names, functions)
193
+ }
194
+ else:
195
+ pydantic_schema = functions[0]
196
+ output_parser: Union[BaseOutputParser, BaseGenerationOutputParser] = (
197
+ PydanticOutputFunctionsParser(pydantic_schema=pydantic_schema)
198
+ )
199
+ else:
200
+ output_parser = JsonOutputFunctionsParser(args_only=len(functions) <= 1)
201
+ return output_parser
202
+
203
+
204
+ def create_ernie_fn_runnable(
205
+ functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],
206
+ llm: Runnable,
207
+ prompt: BasePromptTemplate,
208
+ *,
209
+ output_parser: Optional[Union[BaseOutputParser, BaseGenerationOutputParser]] = None,
210
+ **kwargs: Any,
211
+ ) -> Runnable:
212
+ """Create a runnable sequence that uses Ernie functions.
213
+
214
+ Args:
215
+ functions: A sequence of either dictionaries, pydantic.BaseModels classes, or
216
+ Python functions. If dictionaries are passed in, they are assumed to
217
+ already be a valid Ernie functions. If only a single
218
+ function is passed in, then it will be enforced that the model use that
219
+ function. pydantic.BaseModels and Python functions should have docstrings
220
+ describing what the function does. For best results, pydantic.BaseModels
221
+ should have descriptions of the parameters and Python functions should have
222
+ Google Python style args descriptions in the docstring. Additionally,
223
+ Python functions should only use primitive types (str, int, float, bool) or
224
+ pydantic.BaseModels for arguments.
225
+ llm: Language model to use, assumed to support the Ernie function-calling API.
226
+ prompt: BasePromptTemplate to pass to the model.
227
+ output_parser: BaseLLMOutputParser to use for parsing model outputs. By default
228
+ will be inferred from the function types. If pydantic.BaseModels are passed
229
+ in, then the OutputParser will try to parse outputs using those. Otherwise
230
+ model outputs will simply be parsed as JSON. If multiple functions are
231
+ passed in and they are not pydantic.BaseModels, the chain output will
232
+ include both the name of the function that was returned and the arguments
233
+ to pass to the function.
234
+
235
+ Returns:
236
+ A runnable sequence that will pass in the given functions to the model when run.
237
+
238
+ Example:
239
+ .. code-block:: python
240
+
241
+ from typing import Optional
242
+
243
+ from langchain_classic.chains.ernie_functions import create_ernie_fn_chain
244
+ from langchain_community.chat_models import ErnieBotChat
245
+ from langchain_core.prompts import ChatPromptTemplate
246
+ from pydantic import BaseModel, Field
247
+
248
+
249
+ class RecordPerson(BaseModel):
250
+ \"\"\"Record some identifying information about a person.\"\"\"
251
+
252
+ name: str = Field(..., description="The person's name")
253
+ age: int = Field(..., description="The person's age")
254
+ fav_food: Optional[str] = Field(None, description="The person's favorite food")
255
+
256
+
257
+ class RecordDog(BaseModel):
258
+ \"\"\"Record some identifying information about a dog.\"\"\"
259
+
260
+ name: str = Field(..., description="The dog's name")
261
+ color: str = Field(..., description="The dog's color")
262
+ fav_food: Optional[str] = Field(None, description="The dog's favorite food")
263
+
264
+
265
+ llm = ErnieBotChat(model_name="ERNIE-Bot-4")
266
+ prompt = ChatPromptTemplate.from_messages(
267
+ [
268
+ ("user", "Make calls to the relevant function to record the entities in the following input: {input}"),
269
+ ("assistant", "OK!"),
270
+ ("user", "Tip: Make sure to answer in the correct format"),
271
+ ]
272
+ )
273
+ chain = create_ernie_fn_runnable([RecordPerson, RecordDog], llm, prompt)
274
+ chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
275
+ # -> RecordDog(name="Harry", color="brown", fav_food="chicken")
276
+ """ # noqa: E501
277
+ if not functions:
278
+ raise ValueError("Need to pass in at least one function. Received zero.")
279
+ ernie_functions = [convert_to_ernie_function(f) for f in functions]
280
+ llm_kwargs: Dict[str, Any] = {"functions": ernie_functions, **kwargs}
281
+ if len(ernie_functions) == 1:
282
+ llm_kwargs["function_call"] = {"name": ernie_functions[0]["name"]}
283
+ output_parser = output_parser or get_ernie_output_parser(functions)
284
+ return prompt | llm.bind(**llm_kwargs) | output_parser
285
+
286
+
287
+ def create_structured_output_runnable(
288
+ output_schema: Union[Dict[str, Any], Type[BaseModel]],
289
+ llm: Runnable,
290
+ prompt: BasePromptTemplate,
291
+ *,
292
+ output_parser: Optional[Union[BaseOutputParser, BaseGenerationOutputParser]] = None,
293
+ **kwargs: Any,
294
+ ) -> Runnable:
295
+ """Create a runnable that uses an Ernie function to get a structured output.
296
+
297
+ Args:
298
+ output_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary
299
+ is passed in, it's assumed to already be a valid JsonSchema.
300
+ For best results, pydantic.BaseModels should have docstrings describing what
301
+ the schema represents and descriptions for the parameters.
302
+ llm: Language model to use, assumed to support the Ernie function-calling API.
303
+ prompt: BasePromptTemplate to pass to the model.
304
+ output_parser: BaseLLMOutputParser to use for parsing model outputs. By default
305
+ will be inferred from the function types. If pydantic.BaseModels are passed
306
+ in, then the OutputParser will try to parse outputs using those. Otherwise
307
+ model outputs will simply be parsed as JSON.
308
+
309
+ Returns:
310
+ A runnable sequence that will pass the given function to the model when run.
311
+
312
+ Example:
313
+ .. code-block:: python
314
+
315
+ from typing import Optional
316
+
317
+ from langchain_classic.chains.ernie_functions import create_structured_output_chain
318
+ from langchain_community.chat_models import ErnieBotChat
319
+ from langchain_core.prompts import ChatPromptTemplate
320
+ from pydantic import BaseModel, Field
321
+
322
+ class Dog(BaseModel):
323
+ \"\"\"Identifying information about a dog.\"\"\"
324
+
325
+ name: str = Field(..., description="The dog's name")
326
+ color: str = Field(..., description="The dog's color")
327
+ fav_food: Optional[str] = Field(None, description="The dog's favorite food")
328
+
329
+ llm = ErnieBotChat(model_name="ERNIE-Bot-4")
330
+ prompt = ChatPromptTemplate.from_messages(
331
+ [
332
+ ("user", "Use the given format to extract information from the following input: {input}"),
333
+ ("assistant", "OK!"),
334
+ ("user", "Tip: Make sure to answer in the correct format"),
335
+ ]
336
+ )
337
+ chain = create_structured_output_chain(Dog, llm, prompt)
338
+ chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
339
+ # -> Dog(name="Harry", color="brown", fav_food="chicken")
340
+ """ # noqa: E501
341
+ if isinstance(output_schema, dict):
342
+ function: Any = {
343
+ "name": "output_formatter",
344
+ "description": (
345
+ "Output formatter. Should always be used to format your response to the"
346
+ " user."
347
+ ),
348
+ "parameters": output_schema,
349
+ }
350
+ else:
351
+
352
+ class _OutputFormatter(BaseModel):
353
+ """Output formatter. Should always be used to format your response to the user.""" # noqa: E501
354
+
355
+ output: output_schema # type: ignore[valid-type]
356
+
357
+ function = _OutputFormatter
358
+ output_parser = output_parser or PydanticAttrOutputFunctionsParser(
359
+ pydantic_schema=_OutputFormatter, attr_name="output"
360
+ )
361
+ return create_ernie_fn_runnable(
362
+ [function],
363
+ llm,
364
+ prompt,
365
+ output_parser=output_parser,
366
+ **kwargs,
367
+ )
368
+
369
+
370
+ """ --- Legacy --- """
371
+
372
+
373
+ def create_ernie_fn_chain(
374
+ functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],
375
+ llm: BaseLanguageModel,
376
+ prompt: BasePromptTemplate,
377
+ *,
378
+ output_key: str = "function",
379
+ output_parser: Optional[BaseLLMOutputParser] = None,
380
+ **kwargs: Any,
381
+ ) -> LLMChain:
382
+ """[Legacy] Create an LLM chain that uses Ernie functions.
383
+
384
+ Args:
385
+ functions: A sequence of either dictionaries, pydantic.BaseModels classes, or
386
+ Python functions. If dictionaries are passed in, they are assumed to
387
+ already be a valid Ernie functions. If only a single
388
+ function is passed in, then it will be enforced that the model use that
389
+ function. pydantic.BaseModels and Python functions should have docstrings
390
+ describing what the function does. For best results, pydantic.BaseModels
391
+ should have descriptions of the parameters and Python functions should have
392
+ Google Python style args descriptions in the docstring. Additionally,
393
+ Python functions should only use primitive types (str, int, float, bool) or
394
+ pydantic.BaseModels for arguments.
395
+ llm: Language model to use, assumed to support the Ernie function-calling API.
396
+ prompt: BasePromptTemplate to pass to the model.
397
+ output_key: The key to use when returning the output in LLMChain.__call__.
398
+ output_parser: BaseLLMOutputParser to use for parsing model outputs. By default
399
+ will be inferred from the function types. If pydantic.BaseModels are passed
400
+ in, then the OutputParser will try to parse outputs using those. Otherwise
401
+ model outputs will simply be parsed as JSON. If multiple functions are
402
+ passed in and they are not pydantic.BaseModels, the chain output will
403
+ include both the name of the function that was returned and the arguments
404
+ to pass to the function.
405
+
406
+ Returns:
407
+ An LLMChain that will pass in the given functions to the model when run.
408
+
409
+ Example:
410
+ .. code-block:: python
411
+
412
+ from typing import Optional
413
+
414
+ from langchain_classic.chains.ernie_functions import create_ernie_fn_chain
415
+ from langchain_community.chat_models import ErnieBotChat
416
+ from langchain_core.prompts import ChatPromptTemplate
417
+
418
+ from pydantic import BaseModel, Field
419
+
420
+
421
+ class RecordPerson(BaseModel):
422
+ \"\"\"Record some identifying information about a person.\"\"\"
423
+
424
+ name: str = Field(..., description="The person's name")
425
+ age: int = Field(..., description="The person's age")
426
+ fav_food: Optional[str] = Field(None, description="The person's favorite food")
427
+
428
+
429
+ class RecordDog(BaseModel):
430
+ \"\"\"Record some identifying information about a dog.\"\"\"
431
+
432
+ name: str = Field(..., description="The dog's name")
433
+ color: str = Field(..., description="The dog's color")
434
+ fav_food: Optional[str] = Field(None, description="The dog's favorite food")
435
+
436
+
437
+ llm = ErnieBotChat(model_name="ERNIE-Bot-4")
438
+ prompt = ChatPromptTemplate.from_messages(
439
+ [
440
+ ("user", "Make calls to the relevant function to record the entities in the following input: {input}"),
441
+ ("assistant", "OK!"),
442
+ ("user", "Tip: Make sure to answer in the correct format"),
443
+ ]
444
+ )
445
+ chain = create_ernie_fn_chain([RecordPerson, RecordDog], llm, prompt)
446
+ chain.run("Harry was a chubby brown beagle who loved chicken")
447
+ # -> RecordDog(name="Harry", color="brown", fav_food="chicken")
448
+ """ # noqa: E501
449
+ if not functions:
450
+ raise ValueError("Need to pass in at least one function. Received zero.")
451
+ ernie_functions = [convert_to_ernie_function(f) for f in functions]
452
+ output_parser = output_parser or get_ernie_output_parser(functions)
453
+ llm_kwargs: Dict[str, Any] = {
454
+ "functions": ernie_functions,
455
+ }
456
+ if len(ernie_functions) == 1:
457
+ llm_kwargs["function_call"] = {"name": ernie_functions[0]["name"]}
458
+ llm_chain = LLMChain(
459
+ llm=llm,
460
+ prompt=prompt,
461
+ output_parser=output_parser,
462
+ llm_kwargs=llm_kwargs,
463
+ output_key=output_key,
464
+ **kwargs,
465
+ )
466
+ return llm_chain
467
+
468
+
469
+ def create_structured_output_chain(
470
+ output_schema: Union[Dict[str, Any], Type[BaseModel]],
471
+ llm: BaseLanguageModel,
472
+ prompt: BasePromptTemplate,
473
+ *,
474
+ output_key: str = "function",
475
+ output_parser: Optional[BaseLLMOutputParser] = None,
476
+ **kwargs: Any,
477
+ ) -> LLMChain:
478
+ """[Legacy] Create an LLMChain that uses an Ernie function to get a structured output.
479
+
480
+ Args:
481
+ output_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary
482
+ is passed in, it's assumed to already be a valid JsonSchema.
483
+ For best results, pydantic.BaseModels should have docstrings describing what
484
+ the schema represents and descriptions for the parameters.
485
+ llm: Language model to use, assumed to support the Ernie function-calling API.
486
+ prompt: BasePromptTemplate to pass to the model.
487
+ output_key: The key to use when returning the output in LLMChain.__call__.
488
+ output_parser: BaseLLMOutputParser to use for parsing model outputs. By default
489
+ will be inferred from the function types. If pydantic.BaseModels are passed
490
+ in, then the OutputParser will try to parse outputs using those. Otherwise
491
+ model outputs will simply be parsed as JSON.
492
+
493
+ Returns:
494
+ An LLMChain that will pass the given function to the model.
495
+
496
+ Example:
497
+ .. code-block:: python
498
+
499
+ from typing import Optional
500
+
501
+ from langchain_classic.chains.ernie_functions import create_structured_output_chain
502
+ from langchain_community.chat_models import ErnieBotChat
503
+ from langchain_core.prompts import ChatPromptTemplate
504
+
505
+ from pydantic import BaseModel, Field
506
+
507
+ class Dog(BaseModel):
508
+ \"\"\"Identifying information about a dog.\"\"\"
509
+
510
+ name: str = Field(..., description="The dog's name")
511
+ color: str = Field(..., description="The dog's color")
512
+ fav_food: Optional[str] = Field(None, description="The dog's favorite food")
513
+
514
+ llm = ErnieBotChat(model_name="ERNIE-Bot-4")
515
+ prompt = ChatPromptTemplate.from_messages(
516
+ [
517
+ ("user", "Use the given format to extract information from the following input: {input}"),
518
+ ("assistant", "OK!"),
519
+ ("user", "Tip: Make sure to answer in the correct format"),
520
+ ]
521
+ )
522
+ chain = create_structured_output_chain(Dog, llm, prompt)
523
+ chain.run("Harry was a chubby brown beagle who loved chicken")
524
+ # -> Dog(name="Harry", color="brown", fav_food="chicken")
525
+ """ # noqa: E501
526
+ if isinstance(output_schema, dict):
527
+ function: Any = {
528
+ "name": "output_formatter",
529
+ "description": (
530
+ "Output formatter. Should always be used to format your response to the"
531
+ " user."
532
+ ),
533
+ "parameters": output_schema,
534
+ }
535
+ else:
536
+
537
+ class _OutputFormatter(BaseModel):
538
+ """Output formatter. Should always be used to format your response to the user.""" # noqa: E501
539
+
540
+ output: output_schema # type: ignore[valid-type]
541
+
542
+ function = _OutputFormatter
543
+ output_parser = output_parser or PydanticAttrOutputFunctionsParser(
544
+ pydantic_schema=_OutputFormatter, attr_name="output"
545
+ )
546
+ return create_ernie_fn_chain(
547
+ [function],
548
+ llm,
549
+ prompt,
550
+ output_key=output_key,
551
+ output_parser=output_parser,
552
+ **kwargs,
553
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Question answering over a knowledge graph."""
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/arangodb.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from langchain_classic.chains.base import Chain
9
+ from langchain_classic.chains.llm import LLMChain
10
+ from langchain_core.callbacks import CallbackManagerForChainRun
11
+ from langchain_core.language_models import BaseLanguageModel
12
+ from langchain_core.prompts import BasePromptTemplate
13
+ from pydantic import Field
14
+
15
+ from langchain_community.chains.graph_qa.prompts import (
16
+ AQL_FIX_PROMPT,
17
+ AQL_GENERATION_PROMPT,
18
+ AQL_QA_PROMPT,
19
+ )
20
+ from langchain_community.graphs.arangodb_graph import ArangoGraph
21
+
22
+
23
+ class ArangoGraphQAChain(Chain):
24
+ """Chain for question-answering against a graph by generating AQL statements.
25
+
26
+ *Security note*: Make sure that the database connection uses credentials
27
+ that are narrowly-scoped to only include necessary permissions.
28
+ Failure to do so may result in data corruption or loss, since the calling
29
+ code may attempt commands that would result in deletion, mutation
30
+ of data if appropriately prompted or reading sensitive data if such
31
+ data is present in the database.
32
+ The best way to guard against such negative outcomes is to (as appropriate)
33
+ limit the permissions granted to the credentials used with this tool.
34
+
35
+ See https://python.langchain.com/docs/security for more information.
36
+ """
37
+
38
+ graph: ArangoGraph = Field(exclude=True)
39
+ aql_generation_chain: LLMChain
40
+ aql_fix_chain: LLMChain
41
+ qa_chain: LLMChain
42
+ input_key: str = "query" #: :meta private:
43
+ output_key: str = "result" #: :meta private:
44
+
45
+ # Specifies the maximum number of AQL Query Results to return
46
+ top_k: int = 10
47
+
48
+ # Specifies the set of AQL Query Examples that promote few-shot-learning
49
+ aql_examples: str = ""
50
+
51
+ # Specify whether to return the AQL Query in the output dictionary
52
+ return_aql_query: bool = False
53
+
54
+ # Specify whether to return the AQL JSON Result in the output dictionary
55
+ return_aql_result: bool = False
56
+
57
+ # Specify the maximum amount of AQL Generation attempts that should be made
58
+ max_aql_generation_attempts: int = 3
59
+
60
+ allow_dangerous_requests: bool = False
61
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
62
+
63
+ *Security note*: Make sure that the database connection uses credentials
64
+ that are narrowly-scoped to only include necessary permissions.
65
+ Failure to do so may result in data corruption or loss, since the calling
66
+ code may attempt commands that would result in deletion, mutation
67
+ of data if appropriately prompted or reading sensitive data if such
68
+ data is present in the database.
69
+ The best way to guard against such negative outcomes is to (as appropriate)
70
+ limit the permissions granted to the credentials used with this tool.
71
+
72
+ See https://python.langchain.com/docs/security for more information.
73
+ """
74
+
75
+ def __init__(self, **kwargs: Any) -> None:
76
+ """Initialize the chain."""
77
+ super().__init__(**kwargs)
78
+ if self.allow_dangerous_requests is not True:
79
+ raise ValueError(
80
+ "In order to use this chain, you must acknowledge that it can make "
81
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
82
+ "You must narrowly scope the permissions of the database connection "
83
+ "to only include necessary permissions. Failure to do so may result "
84
+ "in data corruption or loss or reading sensitive data if such data is "
85
+ "present in the database."
86
+ "Only use this chain if you understand the risks and have taken the "
87
+ "necessary precautions. "
88
+ "See https://python.langchain.com/docs/security for more information."
89
+ )
90
+
91
+ @property
92
+ def input_keys(self) -> List[str]:
93
+ return [self.input_key]
94
+
95
+ @property
96
+ def output_keys(self) -> List[str]:
97
+ return [self.output_key]
98
+
99
+ @property
100
+ def _chain_type(self) -> str:
101
+ return "graph_aql_chain"
102
+
103
+ @classmethod
104
+ def from_llm(
105
+ cls,
106
+ llm: BaseLanguageModel,
107
+ *,
108
+ qa_prompt: BasePromptTemplate = AQL_QA_PROMPT,
109
+ aql_generation_prompt: BasePromptTemplate = AQL_GENERATION_PROMPT,
110
+ aql_fix_prompt: BasePromptTemplate = AQL_FIX_PROMPT,
111
+ **kwargs: Any,
112
+ ) -> ArangoGraphQAChain:
113
+ """Initialize from LLM."""
114
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
115
+ aql_generation_chain = LLMChain(llm=llm, prompt=aql_generation_prompt)
116
+ aql_fix_chain = LLMChain(llm=llm, prompt=aql_fix_prompt)
117
+
118
+ return cls(
119
+ qa_chain=qa_chain,
120
+ aql_generation_chain=aql_generation_chain,
121
+ aql_fix_chain=aql_fix_chain,
122
+ **kwargs,
123
+ )
124
+
125
+ def _call(
126
+ self,
127
+ inputs: Dict[str, Any],
128
+ run_manager: Optional[CallbackManagerForChainRun] = None,
129
+ ) -> Dict[str, Any]:
130
+ """
131
+ Generate an AQL statement from user input, use it retrieve a response
132
+ from an ArangoDB Database instance, and respond to the user input
133
+ in natural language.
134
+
135
+ Users can modify the following ArangoGraphQAChain Class Variables:
136
+
137
+ :var top_k: The maximum number of AQL Query Results to return
138
+ :type top_k: int
139
+
140
+ :var aql_examples: A set of AQL Query Examples that are passed to
141
+ the AQL Generation Prompt Template to promote few-shot-learning.
142
+ Defaults to an empty string.
143
+ :type aql_examples: str
144
+
145
+ :var return_aql_query: Whether to return the AQL Query in the
146
+ output dictionary. Defaults to False.
147
+ :type return_aql_query: bool
148
+
149
+ :var return_aql_result: Whether to return the AQL Query in the
150
+ output dictionary. Defaults to False
151
+ :type return_aql_result: bool
152
+
153
+ :var max_aql_generation_attempts: The maximum amount of AQL
154
+ Generation attempts to be made prior to raising the last
155
+ AQL Query Execution Error. Defaults to 3.
156
+ :type max_aql_generation_attempts: int
157
+ """
158
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
159
+ callbacks = _run_manager.get_child()
160
+ user_input = inputs[self.input_key]
161
+
162
+ #########################
163
+ # Generate AQL Query #
164
+ aql_generation_output = self.aql_generation_chain.run(
165
+ {
166
+ "adb_schema": self.graph.schema,
167
+ "aql_examples": self.aql_examples,
168
+ "user_input": user_input,
169
+ },
170
+ callbacks=callbacks,
171
+ )
172
+ #########################
173
+
174
+ aql_query = ""
175
+ aql_error = ""
176
+ aql_result = None
177
+ aql_generation_attempt = 1
178
+
179
+ while (
180
+ aql_result is None
181
+ and aql_generation_attempt < self.max_aql_generation_attempts + 1
182
+ ):
183
+ #####################
184
+ # Extract AQL Query #
185
+ pattern = r"```(?i:aql)?(.*?)```"
186
+ matches = re.findall(pattern, aql_generation_output, re.DOTALL)
187
+ if not matches:
188
+ _run_manager.on_text(
189
+ "Invalid Response: ", end="\n", verbose=self.verbose
190
+ )
191
+ _run_manager.on_text(
192
+ aql_generation_output, color="red", end="\n", verbose=self.verbose
193
+ )
194
+ raise ValueError(f"Response is Invalid: {aql_generation_output}")
195
+
196
+ aql_query = matches[0]
197
+ #####################
198
+
199
+ _run_manager.on_text(
200
+ f"AQL Query ({aql_generation_attempt}):", verbose=self.verbose
201
+ )
202
+ _run_manager.on_text(
203
+ aql_query, color="green", end="\n", verbose=self.verbose
204
+ )
205
+
206
+ #####################
207
+ # Execute AQL Query #
208
+ from arango import AQLQueryExecuteError
209
+
210
+ try:
211
+ aql_result = self.graph.query(aql_query, self.top_k)
212
+ except AQLQueryExecuteError as e:
213
+ aql_error = e.error_message
214
+
215
+ _run_manager.on_text(
216
+ "AQL Query Execution Error: ", end="\n", verbose=self.verbose
217
+ )
218
+ _run_manager.on_text(
219
+ aql_error, color="yellow", end="\n\n", verbose=self.verbose
220
+ )
221
+
222
+ ########################
223
+ # Retry AQL Generation #
224
+ aql_generation_output = self.aql_fix_chain.run(
225
+ {
226
+ "adb_schema": self.graph.schema,
227
+ "aql_query": aql_query,
228
+ "aql_error": aql_error,
229
+ },
230
+ callbacks=callbacks,
231
+ )
232
+ ########################
233
+
234
+ #####################
235
+
236
+ aql_generation_attempt += 1
237
+
238
+ if aql_result is None:
239
+ m = f"""
240
+ Maximum amount of AQL Query Generation attempts reached.
241
+ Unable to execute the AQL Query due to the following error:
242
+ {aql_error}
243
+ """
244
+ raise ValueError(m)
245
+
246
+ _run_manager.on_text("AQL Result:", end="\n", verbose=self.verbose)
247
+ _run_manager.on_text(
248
+ str(aql_result), color="green", end="\n", verbose=self.verbose
249
+ )
250
+
251
+ ########################
252
+ # Interpret AQL Result #
253
+ result = self.qa_chain(
254
+ {
255
+ "adb_schema": self.graph.schema,
256
+ "user_input": user_input,
257
+ "aql_query": aql_query,
258
+ "aql_result": aql_result,
259
+ },
260
+ callbacks=callbacks,
261
+ )
262
+ ########################
263
+
264
+ # Return results #
265
+ result = {self.output_key: result[self.qa_chain.output_key]}
266
+
267
+ if self.return_aql_query:
268
+ result["aql_query"] = aql_query
269
+
270
+ if self.return_aql_result:
271
+ result["aql_result"] = aql_result
272
+
273
+ return result
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/base.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from langchain_classic.chains.base import Chain
8
+ from langchain_classic.chains.llm import LLMChain
9
+ from langchain_core.callbacks.manager import CallbackManagerForChainRun
10
+ from langchain_core.language_models import BaseLanguageModel
11
+ from langchain_core.prompts import BasePromptTemplate
12
+ from pydantic import Field
13
+
14
+ from langchain_community.chains.graph_qa.prompts import (
15
+ ENTITY_EXTRACTION_PROMPT,
16
+ GRAPH_QA_PROMPT,
17
+ )
18
+ from langchain_community.graphs.networkx_graph import NetworkxEntityGraph, get_entities
19
+
20
+
21
+ class GraphQAChain(Chain):
22
+ """Chain for question-answering against a graph.
23
+
24
+ *Security note*: Make sure that the database connection uses credentials
25
+ that are narrowly-scoped to only include necessary permissions.
26
+ Failure to do so may result in data corruption or loss, since the calling
27
+ code may attempt commands that would result in deletion, mutation
28
+ of data if appropriately prompted or reading sensitive data if such
29
+ data is present in the database.
30
+ The best way to guard against such negative outcomes is to (as appropriate)
31
+ limit the permissions granted to the credentials used with this tool.
32
+
33
+ See https://python.langchain.com/docs/security for more information.
34
+ """
35
+
36
+ graph: NetworkxEntityGraph = Field(exclude=True)
37
+ entity_extraction_chain: LLMChain
38
+ qa_chain: LLMChain
39
+ input_key: str = "query" #: :meta private:
40
+ output_key: str = "result" #: :meta private:
41
+
42
+ @property
43
+ def input_keys(self) -> List[str]:
44
+ """Input keys.
45
+
46
+ :meta private:
47
+ """
48
+ return [self.input_key]
49
+
50
+ @property
51
+ def output_keys(self) -> List[str]:
52
+ """Output keys.
53
+
54
+ :meta private:
55
+ """
56
+ _output_keys = [self.output_key]
57
+ return _output_keys
58
+
59
+ @classmethod
60
+ def from_llm(
61
+ cls,
62
+ llm: BaseLanguageModel,
63
+ qa_prompt: BasePromptTemplate = GRAPH_QA_PROMPT,
64
+ entity_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT,
65
+ **kwargs: Any,
66
+ ) -> GraphQAChain:
67
+ """Initialize from LLM."""
68
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
69
+ entity_chain = LLMChain(llm=llm, prompt=entity_prompt)
70
+
71
+ return cls(
72
+ qa_chain=qa_chain,
73
+ entity_extraction_chain=entity_chain,
74
+ **kwargs,
75
+ )
76
+
77
+ def _call(
78
+ self,
79
+ inputs: Dict[str, Any],
80
+ run_manager: Optional[CallbackManagerForChainRun] = None,
81
+ ) -> Dict[str, str]:
82
+ """Extract entities, look up info and answer question."""
83
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
84
+ question = inputs[self.input_key]
85
+
86
+ entity_string = self.entity_extraction_chain.run(question)
87
+
88
+ _run_manager.on_text("Entities Extracted:", end="\n", verbose=self.verbose)
89
+ _run_manager.on_text(
90
+ entity_string, color="green", end="\n", verbose=self.verbose
91
+ )
92
+ entities = get_entities(entity_string)
93
+ context = ""
94
+ all_triplets = []
95
+ for entity in entities:
96
+ all_triplets.extend(self.graph.get_entity_knowledge(entity))
97
+ context = "\n".join(all_triplets)
98
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
99
+ _run_manager.on_text(context, color="green", end="\n", verbose=self.verbose)
100
+ result = self.qa_chain(
101
+ {"question": question, "context": context},
102
+ callbacks=_run_manager.get_child(),
103
+ )
104
+ return {self.output_key: result[self.qa_chain.output_key]}
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/cypher.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Dict, List, Optional, Union
7
+
8
+ from langchain_classic.chains.base import Chain
9
+ from langchain_classic.chains.llm import LLMChain
10
+ from langchain_core._api.deprecation import deprecated
11
+ from langchain_core.callbacks import CallbackManagerForChainRun
12
+ from langchain_core.language_models import BaseLanguageModel
13
+ from langchain_core.messages import (
14
+ AIMessage,
15
+ BaseMessage,
16
+ SystemMessage,
17
+ ToolMessage,
18
+ )
19
+ from langchain_core.output_parsers import StrOutputParser
20
+ from langchain_core.prompts import (
21
+ BasePromptTemplate,
22
+ ChatPromptTemplate,
23
+ HumanMessagePromptTemplate,
24
+ MessagesPlaceholder,
25
+ )
26
+ from langchain_core.runnables import Runnable
27
+ from pydantic import Field
28
+
29
+ from langchain_community.chains.graph_qa.cypher_utils import (
30
+ CypherQueryCorrector,
31
+ Schema,
32
+ )
33
+ from langchain_community.chains.graph_qa.prompts import (
34
+ CYPHER_GENERATION_PROMPT,
35
+ CYPHER_QA_PROMPT,
36
+ )
37
+ from langchain_community.graphs.graph_store import GraphStore
38
+
39
+ INTERMEDIATE_STEPS_KEY = "intermediate_steps"
40
+
41
+ FUNCTION_RESPONSE_SYSTEM = """You are an assistant that helps to form nice and human
42
+ understandable answers based on the provided information from tools.
43
+ Do not add any other information that wasn't present in the tools, and use
44
+ very concise style in interpreting results!
45
+ """
46
+
47
+
48
+ @deprecated(
49
+ since="0.3.8",
50
+ removal="1.0",
51
+ alternative_import="langchain_neo4j.chains.graph_qa.cypher.extract_cypher",
52
+ )
53
+ def extract_cypher(text: str) -> str:
54
+ """Extract Cypher code from a text.
55
+
56
+ Args:
57
+ text: Text to extract Cypher code from.
58
+
59
+ Returns:
60
+ Cypher code extracted from the text.
61
+ """
62
+ # The pattern to find Cypher code enclosed in triple backticks
63
+ pattern = r"```(.*?)```"
64
+
65
+ # Find all matches in the input text
66
+ matches = re.findall(pattern, text, re.DOTALL)
67
+
68
+ return matches[0] if matches else text
69
+
70
+
71
+ @deprecated(
72
+ since="0.3.8",
73
+ removal="1.0",
74
+ alternative_import="langchain_neo4j.chains.graph_qa.cypher.construct_schema",
75
+ )
76
+ def construct_schema(
77
+ structured_schema: Dict[str, Any],
78
+ include_types: List[str],
79
+ exclude_types: List[str],
80
+ ) -> str:
81
+ """Filter the schema based on included or excluded types"""
82
+
83
+ def filter_func(x: str) -> bool:
84
+ return x in include_types if include_types else x not in exclude_types
85
+
86
+ filtered_schema: Dict[str, Any] = {
87
+ "node_props": {
88
+ k: v
89
+ for k, v in structured_schema.get("node_props", {}).items()
90
+ if filter_func(k)
91
+ },
92
+ "rel_props": {
93
+ k: v
94
+ for k, v in structured_schema.get("rel_props", {}).items()
95
+ if filter_func(k)
96
+ },
97
+ "relationships": [
98
+ r
99
+ for r in structured_schema.get("relationships", [])
100
+ if all(filter_func(r[t]) for t in ["start", "end", "type"])
101
+ ],
102
+ }
103
+
104
+ # Format node properties
105
+ formatted_node_props = []
106
+ for label, properties in filtered_schema["node_props"].items():
107
+ props_str = ", ".join(
108
+ [f"{prop['property']}: {prop['type']}" for prop in properties]
109
+ )
110
+ formatted_node_props.append(f"{label} {{{props_str}}}")
111
+
112
+ # Format relationship properties
113
+ formatted_rel_props = []
114
+ for rel_type, properties in filtered_schema["rel_props"].items():
115
+ props_str = ", ".join(
116
+ [f"{prop['property']}: {prop['type']}" for prop in properties]
117
+ )
118
+ formatted_rel_props.append(f"{rel_type} {{{props_str}}}")
119
+
120
+ # Format relationships
121
+ formatted_rels = [
122
+ f"(:{el['start']})-[:{el['type']}]->(:{el['end']})"
123
+ for el in filtered_schema["relationships"]
124
+ ]
125
+
126
+ return "\n".join(
127
+ [
128
+ "Node properties are the following:",
129
+ ",".join(formatted_node_props),
130
+ "Relationship properties are the following:",
131
+ ",".join(formatted_rel_props),
132
+ "The relationships are the following:",
133
+ ",".join(formatted_rels),
134
+ ]
135
+ )
136
+
137
+
138
+ @deprecated(
139
+ since="0.3.8",
140
+ removal="1.0",
141
+ alternative_import="langchain_neo4j.chains.graph_qa.cypher.get_function_response",
142
+ )
143
+ def get_function_response(
144
+ question: str, context: List[Dict[str, Any]]
145
+ ) -> List[BaseMessage]:
146
+ TOOL_ID = "call_H7fABDuzEau48T10Qn0Lsh0D"
147
+ messages = [
148
+ AIMessage(
149
+ content="",
150
+ additional_kwargs={
151
+ "tool_calls": [
152
+ {
153
+ "id": TOOL_ID,
154
+ "function": {
155
+ "arguments": '{"question":"' + question + '"}',
156
+ "name": "GetInformation",
157
+ },
158
+ "type": "function",
159
+ }
160
+ ]
161
+ },
162
+ ),
163
+ ToolMessage(content=str(context), tool_call_id=TOOL_ID),
164
+ ]
165
+ return messages
166
+
167
+
168
+ @deprecated(
169
+ since="0.3.8",
170
+ removal="1.0",
171
+ alternative_import="langchain_neo4j.GraphCypherQAChain",
172
+ )
173
+ class GraphCypherQAChain(Chain):
174
+ """Chain for question-answering against a graph by generating Cypher statements.
175
+
176
+ *Security note*: Make sure that the database connection uses credentials
177
+ that are narrowly-scoped to only include necessary permissions.
178
+ Failure to do so may result in data corruption or loss, since the calling
179
+ code may attempt commands that would result in deletion, mutation
180
+ of data if appropriately prompted or reading sensitive data if such
181
+ data is present in the database.
182
+ The best way to guard against such negative outcomes is to (as appropriate)
183
+ limit the permissions granted to the credentials used with this tool.
184
+
185
+ See https://python.langchain.com/docs/security for more information.
186
+ """
187
+
188
+ graph: GraphStore = Field(exclude=True)
189
+ cypher_generation_chain: LLMChain
190
+ qa_chain: Union[LLMChain, Runnable]
191
+ graph_schema: str
192
+ input_key: str = "query" #: :meta private:
193
+ output_key: str = "result" #: :meta private:
194
+ top_k: int = 10
195
+ """Number of results to return from the query"""
196
+ return_intermediate_steps: bool = False
197
+ """Whether or not to return the intermediate steps along with the final answer."""
198
+ return_direct: bool = False
199
+ """Whether or not to return the result of querying the graph directly."""
200
+ cypher_query_corrector: Optional[CypherQueryCorrector] = None
201
+ """Optional cypher validation tool"""
202
+ use_function_response: bool = False
203
+ """Whether to wrap the database context as tool/function response"""
204
+ allow_dangerous_requests: bool = False
205
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
206
+
207
+ *Security note*: Make sure that the database connection uses credentials
208
+ that are narrowly-scoped to only include necessary permissions.
209
+ Failure to do so may result in data corruption or loss, since the calling
210
+ code may attempt commands that would result in deletion, mutation
211
+ of data if appropriately prompted or reading sensitive data if such
212
+ data is present in the database.
213
+ The best way to guard against such negative outcomes is to (as appropriate)
214
+ limit the permissions granted to the credentials used with this tool.
215
+
216
+ See https://python.langchain.com/docs/security for more information.
217
+ """
218
+
219
+ def __init__(self, **kwargs: Any) -> None:
220
+ """Initialize the chain."""
221
+ super().__init__(**kwargs)
222
+ if self.allow_dangerous_requests is not True:
223
+ raise ValueError(
224
+ "In order to use this chain, you must acknowledge that it can make "
225
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
226
+ "You must narrowly scope the permissions of the database connection "
227
+ "to only include necessary permissions. Failure to do so may result "
228
+ "in data corruption or loss or reading sensitive data if such data is "
229
+ "present in the database."
230
+ "Only use this chain if you understand the risks and have taken the "
231
+ "necessary precautions. "
232
+ "See https://python.langchain.com/docs/security for more information."
233
+ )
234
+
235
+ @property
236
+ def input_keys(self) -> List[str]:
237
+ """Return the input keys.
238
+
239
+ :meta private:
240
+ """
241
+ return [self.input_key]
242
+
243
+ @property
244
+ def output_keys(self) -> List[str]:
245
+ """Return the output keys.
246
+
247
+ :meta private:
248
+ """
249
+ _output_keys = [self.output_key]
250
+ return _output_keys
251
+
252
+ @property
253
+ def _chain_type(self) -> str:
254
+ return "graph_cypher_chain"
255
+
256
+ @classmethod
257
+ def from_llm(
258
+ cls,
259
+ llm: Optional[BaseLanguageModel] = None,
260
+ *,
261
+ qa_prompt: Optional[BasePromptTemplate] = None,
262
+ cypher_prompt: Optional[BasePromptTemplate] = None,
263
+ cypher_llm: Optional[BaseLanguageModel] = None,
264
+ qa_llm: Optional[Union[BaseLanguageModel, Any]] = None,
265
+ exclude_types: List[str] = [],
266
+ include_types: List[str] = [],
267
+ validate_cypher: bool = False,
268
+ qa_llm_kwargs: Optional[Dict[str, Any]] = None,
269
+ cypher_llm_kwargs: Optional[Dict[str, Any]] = None,
270
+ use_function_response: bool = False,
271
+ function_response_system: str = FUNCTION_RESPONSE_SYSTEM,
272
+ **kwargs: Any,
273
+ ) -> GraphCypherQAChain:
274
+ """Initialize from LLM."""
275
+
276
+ if not cypher_llm and not llm:
277
+ raise ValueError("Either `llm` or `cypher_llm` parameters must be provided")
278
+ if not qa_llm and not llm:
279
+ raise ValueError("Either `llm` or `qa_llm` parameters must be provided")
280
+ if cypher_llm and qa_llm and llm:
281
+ raise ValueError(
282
+ "You can specify up to two of 'cypher_llm', 'qa_llm'"
283
+ ", and 'llm', but not all three simultaneously."
284
+ )
285
+ if cypher_prompt and cypher_llm_kwargs:
286
+ raise ValueError(
287
+ "Specifying cypher_prompt and cypher_llm_kwargs together is"
288
+ " not allowed. Please pass prompt via cypher_llm_kwargs."
289
+ )
290
+ if qa_prompt and qa_llm_kwargs:
291
+ raise ValueError(
292
+ "Specifying qa_prompt and qa_llm_kwargs together is"
293
+ " not allowed. Please pass prompt via qa_llm_kwargs."
294
+ )
295
+ use_qa_llm_kwargs = qa_llm_kwargs if qa_llm_kwargs is not None else {}
296
+ use_cypher_llm_kwargs = (
297
+ cypher_llm_kwargs if cypher_llm_kwargs is not None else {}
298
+ )
299
+ if "prompt" not in use_qa_llm_kwargs:
300
+ use_qa_llm_kwargs["prompt"] = (
301
+ qa_prompt if qa_prompt is not None else CYPHER_QA_PROMPT
302
+ )
303
+ if "prompt" not in use_cypher_llm_kwargs:
304
+ use_cypher_llm_kwargs["prompt"] = (
305
+ cypher_prompt if cypher_prompt is not None else CYPHER_GENERATION_PROMPT
306
+ )
307
+
308
+ qa_llm = qa_llm or llm
309
+ if use_function_response:
310
+ try:
311
+ qa_llm.bind_tools({}) # type: ignore[union-attr]
312
+ response_prompt = ChatPromptTemplate.from_messages(
313
+ [
314
+ SystemMessage(content=function_response_system),
315
+ HumanMessagePromptTemplate.from_template("{question}"),
316
+ MessagesPlaceholder(variable_name="function_response"),
317
+ ]
318
+ )
319
+ qa_chain = response_prompt | qa_llm | StrOutputParser() # type: ignore[operator]
320
+ except (NotImplementedError, AttributeError):
321
+ raise ValueError("Provided LLM does not support native tools/functions")
322
+ else:
323
+ qa_chain = LLMChain(llm=qa_llm, **use_qa_llm_kwargs) # type: ignore[arg-type]
324
+
325
+ cypher_generation_chain = LLMChain(
326
+ llm=cypher_llm or llm, # type: ignore[arg-type]
327
+ **use_cypher_llm_kwargs,
328
+ )
329
+
330
+ if exclude_types and include_types:
331
+ raise ValueError(
332
+ "Either `exclude_types` or `include_types` "
333
+ "can be provided, but not both"
334
+ )
335
+ graph_schema = construct_schema(
336
+ kwargs["graph"].get_structured_schema, include_types, exclude_types
337
+ )
338
+
339
+ cypher_query_corrector = None
340
+ if validate_cypher:
341
+ corrector_schema = [
342
+ Schema(el["start"], el["type"], el["end"])
343
+ for el in kwargs["graph"].structured_schema.get("relationships")
344
+ ]
345
+ cypher_query_corrector = CypherQueryCorrector(corrector_schema)
346
+
347
+ return cls(
348
+ graph_schema=graph_schema,
349
+ qa_chain=qa_chain,
350
+ cypher_generation_chain=cypher_generation_chain,
351
+ cypher_query_corrector=cypher_query_corrector,
352
+ use_function_response=use_function_response,
353
+ **kwargs,
354
+ )
355
+
356
+ def _call(
357
+ self,
358
+ inputs: Dict[str, Any],
359
+ run_manager: Optional[CallbackManagerForChainRun] = None,
360
+ ) -> Dict[str, Any]:
361
+ """Generate Cypher statement, use it to look up in db and answer question."""
362
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
363
+ callbacks = _run_manager.get_child()
364
+ question = inputs[self.input_key]
365
+ args = {
366
+ "question": question,
367
+ "schema": self.graph_schema,
368
+ }
369
+ args.update(inputs)
370
+
371
+ intermediate_steps: List = []
372
+
373
+ generated_cypher = self.cypher_generation_chain.run(args, callbacks=callbacks)
374
+
375
+ # Extract Cypher code if it is wrapped in backticks
376
+ generated_cypher = extract_cypher(generated_cypher)
377
+
378
+ # Correct Cypher query if enabled
379
+ if self.cypher_query_corrector:
380
+ generated_cypher = self.cypher_query_corrector(generated_cypher)
381
+
382
+ _run_manager.on_text("Generated Cypher:", end="\n", verbose=self.verbose)
383
+ _run_manager.on_text(
384
+ generated_cypher, color="green", end="\n", verbose=self.verbose
385
+ )
386
+
387
+ intermediate_steps.append({"query": generated_cypher})
388
+
389
+ # Retrieve and limit the number of results
390
+ # Generated Cypher be null if query corrector identifies invalid schema
391
+ if generated_cypher:
392
+ context = self.graph.query(generated_cypher)[: self.top_k]
393
+ else:
394
+ context = []
395
+
396
+ if self.return_direct:
397
+ final_result = context
398
+ else:
399
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
400
+ _run_manager.on_text(
401
+ str(context), color="green", end="\n", verbose=self.verbose
402
+ )
403
+
404
+ intermediate_steps.append({"context": context})
405
+ if self.use_function_response:
406
+ function_response = get_function_response(question, context)
407
+ final_result = self.qa_chain.invoke( # type: ignore[assignment]
408
+ {"question": question, "function_response": function_response},
409
+ )
410
+ else:
411
+ result = self.qa_chain.invoke(
412
+ {"question": question, "context": context},
413
+ callbacks=callbacks,
414
+ )
415
+ final_result = result[self.qa_chain.output_key] # type: ignore[union-attr]
416
+
417
+ chain_result: Dict[str, Any] = {self.output_key: final_result}
418
+ if self.return_intermediate_steps:
419
+ chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps
420
+
421
+ return chain_result
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/cypher_utils.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from collections import namedtuple
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ from langchain_core._api.deprecation import deprecated
6
+
7
+ Schema = namedtuple("Schema", ["left_node", "relation", "right_node"])
8
+
9
+
10
+ @deprecated(
11
+ since="0.3.8",
12
+ removal="1.0",
13
+ alternative_import="langchain_neo4j.chains.graph_qa.cypher_utils.CypherQueryCorrector",
14
+ )
15
+ class CypherQueryCorrector:
16
+ """
17
+ Used to correct relationship direction in generated Cypher statements.
18
+ This code is copied from the winner's submission to the Cypher competition:
19
+ https://github.com/sakusaku-rich/cypher-direction-competition
20
+ """
21
+
22
+ property_pattern = re.compile(r"\{.+?\}")
23
+ node_pattern = re.compile(r"\(.+?\)")
24
+ path_pattern = re.compile(
25
+ r"(\([^\,\(\)]*?(\{.+\})?[^\,\(\)]*?\))(<?-)(\[.*?\])?(->?)(\([^\,\(\)]*?(\{.+\})?[^\,\(\)]*?\))"
26
+ )
27
+ node_relation_node_pattern = re.compile(
28
+ r"(\()+(?P<left_node>[^()]*?)\)(?P<relation>.*?)\((?P<right_node>[^()]*?)(\))+"
29
+ )
30
+ relation_type_pattern = re.compile(r":(?P<relation_type>.+?)?(\{.+\})?]")
31
+
32
+ def __init__(self, schemas: List[Schema]):
33
+ """
34
+ Args:
35
+ schemas: list of schemas
36
+ """
37
+ self.schemas = schemas
38
+
39
+ def clean_node(self, node: str) -> str:
40
+ """
41
+ Args:
42
+ node: node in string format
43
+
44
+ """
45
+ node = re.sub(self.property_pattern, "", node)
46
+ node = node.replace("(", "")
47
+ node = node.replace(")", "")
48
+ node = node.strip()
49
+ return node
50
+
51
+ def detect_node_variables(self, query: str) -> Dict[str, List[str]]:
52
+ """
53
+ Args:
54
+ query: cypher query
55
+ """
56
+ nodes = re.findall(self.node_pattern, query)
57
+ nodes = [self.clean_node(node) for node in nodes]
58
+ res: Dict[str, Any] = {}
59
+ for node in nodes:
60
+ parts = node.split(":")
61
+ if parts == "":
62
+ continue
63
+ variable = parts[0]
64
+ if variable not in res:
65
+ res[variable] = []
66
+ res[variable] += parts[1:]
67
+ return res
68
+
69
+ def extract_paths(self, query: str) -> "List[str]":
70
+ """
71
+ Args:
72
+ query: cypher query
73
+ """
74
+ paths = []
75
+ idx = 0
76
+ while matched := self.path_pattern.findall(query[idx:]):
77
+ matched = matched[0]
78
+ matched = [
79
+ m for i, m in enumerate(matched) if i not in [1, len(matched) - 1]
80
+ ]
81
+ path = "".join(matched)
82
+ idx = query.find(path) + len(path) - len(matched[-1])
83
+ paths.append(path)
84
+ return paths
85
+
86
+ def judge_direction(self, relation: str) -> str:
87
+ """
88
+ Args:
89
+ relation: relation in string format
90
+ """
91
+ direction = "BIDIRECTIONAL"
92
+ if relation[0] == "<":
93
+ direction = "INCOMING"
94
+ if relation[-1] == ">":
95
+ direction = "OUTGOING"
96
+ return direction
97
+
98
+ def extract_node_variable(self, part: str) -> Optional[str]:
99
+ """
100
+ Args:
101
+ part: node in string format
102
+ """
103
+ part = part.lstrip("(").rstrip(")")
104
+ idx = part.find(":")
105
+ if idx != -1:
106
+ part = part[:idx]
107
+ return None if part == "" else part
108
+
109
+ def detect_labels(
110
+ self, str_node: str, node_variable_dict: Dict[str, Any]
111
+ ) -> List[str]:
112
+ """
113
+ Args:
114
+ str_node: node in string format
115
+ node_variable_dict: dictionary of node variables
116
+ """
117
+ splitted_node = str_node.split(":")
118
+ variable = splitted_node[0]
119
+ labels = []
120
+ if variable in node_variable_dict:
121
+ labels = node_variable_dict[variable]
122
+ elif variable == "" and len(splitted_node) > 1:
123
+ labels = splitted_node[1:]
124
+ return labels
125
+
126
+ def verify_schema(
127
+ self,
128
+ from_node_labels: List[str],
129
+ relation_types: List[str],
130
+ to_node_labels: List[str],
131
+ ) -> bool:
132
+ """
133
+ Args:
134
+ from_node_labels: labels of the from node
135
+ relation_type: type of the relation
136
+ to_node_labels: labels of the to node
137
+ """
138
+ valid_schemas = self.schemas
139
+ if from_node_labels != []:
140
+ from_node_labels = [label.strip("`") for label in from_node_labels]
141
+ valid_schemas = [
142
+ schema for schema in valid_schemas if schema[0] in from_node_labels
143
+ ]
144
+ if to_node_labels != []:
145
+ to_node_labels = [label.strip("`") for label in to_node_labels]
146
+ valid_schemas = [
147
+ schema for schema in valid_schemas if schema[2] in to_node_labels
148
+ ]
149
+ if relation_types != []:
150
+ relation_types = [type.strip("`") for type in relation_types]
151
+ valid_schemas = [
152
+ schema for schema in valid_schemas if schema[1] in relation_types
153
+ ]
154
+ return valid_schemas != []
155
+
156
+ def detect_relation_types(self, str_relation: str) -> Tuple[str, List[str]]:
157
+ """
158
+ Args:
159
+ str_relation: relation in string format
160
+ """
161
+ relation_direction = self.judge_direction(str_relation)
162
+ relation_type = self.relation_type_pattern.search(str_relation)
163
+ if relation_type is None or relation_type.group("relation_type") is None:
164
+ return relation_direction, []
165
+ relation_types = [
166
+ t.strip().strip("!")
167
+ for t in relation_type.group("relation_type").split("|")
168
+ ]
169
+ return relation_direction, relation_types
170
+
171
+ def correct_query(self, query: str) -> str:
172
+ """
173
+ Args:
174
+ query: cypher query
175
+ """
176
+ node_variable_dict = self.detect_node_variables(query)
177
+ paths = self.extract_paths(query)
178
+ for path in paths:
179
+ original_path = path
180
+ start_idx = 0
181
+ while start_idx < len(path):
182
+ match_res = re.match(self.node_relation_node_pattern, path[start_idx:])
183
+ if match_res is None:
184
+ break
185
+ start_idx += match_res.start()
186
+ match_dict = match_res.groupdict()
187
+ left_node_labels = self.detect_labels(
188
+ match_dict["left_node"], node_variable_dict
189
+ )
190
+ right_node_labels = self.detect_labels(
191
+ match_dict["right_node"], node_variable_dict
192
+ )
193
+ end_idx = (
194
+ start_idx
195
+ + 4
196
+ + len(match_dict["left_node"])
197
+ + len(match_dict["relation"])
198
+ + len(match_dict["right_node"])
199
+ )
200
+ original_partial_path = original_path[start_idx : end_idx + 1]
201
+ relation_direction, relation_types = self.detect_relation_types(
202
+ match_dict["relation"]
203
+ )
204
+
205
+ if relation_types != [] and "".join(relation_types).find("*") != -1:
206
+ start_idx += (
207
+ len(match_dict["left_node"]) + len(match_dict["relation"]) + 2
208
+ )
209
+ continue
210
+
211
+ if relation_direction == "OUTGOING":
212
+ is_legal = self.verify_schema(
213
+ left_node_labels, relation_types, right_node_labels
214
+ )
215
+ if not is_legal:
216
+ is_legal = self.verify_schema(
217
+ right_node_labels, relation_types, left_node_labels
218
+ )
219
+ if is_legal:
220
+ corrected_relation = "<" + match_dict["relation"][:-1]
221
+ corrected_partial_path = original_partial_path.replace(
222
+ match_dict["relation"], corrected_relation
223
+ )
224
+ query = query.replace(
225
+ original_partial_path, corrected_partial_path
226
+ )
227
+ else:
228
+ return ""
229
+ elif relation_direction == "INCOMING":
230
+ is_legal = self.verify_schema(
231
+ right_node_labels, relation_types, left_node_labels
232
+ )
233
+ if not is_legal:
234
+ is_legal = self.verify_schema(
235
+ left_node_labels, relation_types, right_node_labels
236
+ )
237
+ if is_legal:
238
+ corrected_relation = match_dict["relation"][1:] + ">"
239
+ corrected_partial_path = original_partial_path.replace(
240
+ match_dict["relation"], corrected_relation
241
+ )
242
+ query = query.replace(
243
+ original_partial_path, corrected_partial_path
244
+ )
245
+ else:
246
+ return ""
247
+ else:
248
+ is_legal = self.verify_schema(
249
+ left_node_labels, relation_types, right_node_labels
250
+ )
251
+ is_legal |= self.verify_schema(
252
+ right_node_labels, relation_types, left_node_labels
253
+ )
254
+ if not is_legal:
255
+ return ""
256
+
257
+ start_idx += (
258
+ len(match_dict["left_node"]) + len(match_dict["relation"]) + 2
259
+ )
260
+ return query
261
+
262
+ def __call__(self, query: str) -> str:
263
+ """Correct the query to make it valid. If
264
+ Args:
265
+ query: cypher query
266
+ """
267
+ return self.correct_query(query)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/falkordb.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from langchain_classic.chains.base import Chain
9
+ from langchain_classic.chains.llm import LLMChain
10
+ from langchain_core.callbacks import CallbackManagerForChainRun
11
+ from langchain_core.language_models import BaseLanguageModel
12
+ from langchain_core.prompts import BasePromptTemplate
13
+ from pydantic import Field
14
+
15
+ from langchain_community.chains.graph_qa.prompts import (
16
+ CYPHER_GENERATION_PROMPT,
17
+ CYPHER_QA_PROMPT,
18
+ )
19
+ from langchain_community.graphs import FalkorDBGraph
20
+
21
+ INTERMEDIATE_STEPS_KEY = "intermediate_steps"
22
+
23
+
24
+ def extract_cypher(text: str) -> str:
25
+ """
26
+ Extract Cypher code from a text.
27
+ Args:
28
+ text: Text to extract Cypher code from.
29
+
30
+ Returns:
31
+ Cypher code extracted from the text.
32
+ """
33
+ # The pattern to find Cypher code enclosed in triple backticks
34
+ pattern = r"```(.*?)```"
35
+
36
+ # Find all matches in the input text
37
+ matches = re.findall(pattern, text, re.DOTALL)
38
+
39
+ return matches[0] if matches else text
40
+
41
+
42
+ class FalkorDBQAChain(Chain):
43
+ """Chain for question-answering against a graph by generating Cypher statements.
44
+
45
+ *Security note*: Make sure that the database connection uses credentials
46
+ that are narrowly-scoped to only include necessary permissions.
47
+ Failure to do so may result in data corruption or loss, since the calling
48
+ code may attempt commands that would result in deletion, mutation
49
+ of data if appropriately prompted or reading sensitive data if such
50
+ data is present in the database.
51
+ The best way to guard against such negative outcomes is to (as appropriate)
52
+ limit the permissions granted to the credentials used with this tool.
53
+
54
+ See https://python.langchain.com/docs/security for more information.
55
+ """
56
+
57
+ graph: FalkorDBGraph = Field(exclude=True)
58
+ cypher_generation_chain: LLMChain
59
+ qa_chain: LLMChain
60
+ input_key: str = "query" #: :meta private:
61
+ output_key: str = "result" #: :meta private:
62
+ top_k: int = 10
63
+ """Number of results to return from the query"""
64
+ return_intermediate_steps: bool = False
65
+ """Whether or not to return the intermediate steps along with the final answer."""
66
+ return_direct: bool = False
67
+ """Whether or not to return the result of querying the graph directly."""
68
+
69
+ allow_dangerous_requests: bool = False
70
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
71
+
72
+ *Security note*: Make sure that the database connection uses credentials
73
+ that are narrowly-scoped to only include necessary permissions.
74
+ Failure to do so may result in data corruption or loss, since the calling
75
+ code may attempt commands that would result in deletion, mutation
76
+ of data if appropriately prompted or reading sensitive data if such
77
+ data is present in the database.
78
+ The best way to guard against such negative outcomes is to (as appropriate)
79
+ limit the permissions granted to the credentials used with this tool.
80
+
81
+ See https://python.langchain.com/docs/security for more information.
82
+ """
83
+
84
+ def __init__(self, **kwargs: Any) -> None:
85
+ """Initialize the chain."""
86
+ super().__init__(**kwargs)
87
+ if self.allow_dangerous_requests is not True:
88
+ raise ValueError(
89
+ "In order to use this chain, you must acknowledge that it can make "
90
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
91
+ "You must narrowly scope the permissions of the database connection "
92
+ "to only include necessary permissions. Failure to do so may result "
93
+ "in data corruption or loss or reading sensitive data if such data is "
94
+ "present in the database."
95
+ "Only use this chain if you understand the risks and have taken the "
96
+ "necessary precautions. "
97
+ "See https://python.langchain.com/docs/security for more information."
98
+ )
99
+
100
+ @property
101
+ def input_keys(self) -> List[str]:
102
+ """Return the input keys.
103
+
104
+ :meta private:
105
+ """
106
+ return [self.input_key]
107
+
108
+ @property
109
+ def output_keys(self) -> List[str]:
110
+ """Return the output keys.
111
+
112
+ :meta private:
113
+ """
114
+ _output_keys = [self.output_key]
115
+ return _output_keys
116
+
117
+ @property
118
+ def _chain_type(self) -> str:
119
+ return "graph_cypher_chain"
120
+
121
+ @classmethod
122
+ def from_llm(
123
+ cls,
124
+ llm: BaseLanguageModel,
125
+ *,
126
+ qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,
127
+ cypher_prompt: BasePromptTemplate = CYPHER_GENERATION_PROMPT,
128
+ **kwargs: Any,
129
+ ) -> FalkorDBQAChain:
130
+ """Initialize from LLM."""
131
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
132
+ cypher_generation_chain = LLMChain(llm=llm, prompt=cypher_prompt)
133
+
134
+ return cls(
135
+ qa_chain=qa_chain,
136
+ cypher_generation_chain=cypher_generation_chain,
137
+ **kwargs,
138
+ )
139
+
140
+ def _call(
141
+ self,
142
+ inputs: Dict[str, Any],
143
+ run_manager: Optional[CallbackManagerForChainRun] = None,
144
+ ) -> Dict[str, Any]:
145
+ """Generate Cypher statement, use it to look up in db and answer question."""
146
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
147
+ callbacks = _run_manager.get_child()
148
+ question = inputs[self.input_key]
149
+
150
+ intermediate_steps: List = []
151
+
152
+ generated_cypher = self.cypher_generation_chain.run(
153
+ {"question": question, "schema": self.graph.schema}, callbacks=callbacks
154
+ )
155
+
156
+ # Extract Cypher code if it is wrapped in backticks
157
+ generated_cypher = extract_cypher(generated_cypher)
158
+
159
+ _run_manager.on_text("Generated Cypher:", end="\n", verbose=self.verbose)
160
+ _run_manager.on_text(
161
+ generated_cypher, color="green", end="\n", verbose=self.verbose
162
+ )
163
+
164
+ intermediate_steps.append({"query": generated_cypher})
165
+
166
+ # Retrieve and limit the number of results
167
+ context = self.graph.query(generated_cypher)[: self.top_k]
168
+
169
+ if self.return_direct:
170
+ final_result = context
171
+ else:
172
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
173
+ _run_manager.on_text(
174
+ str(context), color="green", end="\n", verbose=self.verbose
175
+ )
176
+
177
+ intermediate_steps.append({"context": context})
178
+
179
+ result = self.qa_chain(
180
+ {"question": question, "context": context},
181
+ callbacks=callbacks,
182
+ )
183
+ final_result = result[self.qa_chain.output_key]
184
+
185
+ chain_result: Dict[str, Any] = {self.output_key: final_result}
186
+ if self.return_intermediate_steps:
187
+ chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps
188
+
189
+ return chain_result
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/gremlin.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from langchain_classic.chains.base import Chain
8
+ from langchain_classic.chains.llm import LLMChain
9
+ from langchain_core.callbacks.manager import CallbackManager, CallbackManagerForChainRun
10
+ from langchain_core.language_models import BaseLanguageModel
11
+ from langchain_core.prompts import BasePromptTemplate
12
+ from langchain_core.prompts.prompt import PromptTemplate
13
+ from pydantic import Field
14
+
15
+ from langchain_community.chains.graph_qa.prompts import (
16
+ CYPHER_QA_PROMPT,
17
+ GRAPHDB_SPARQL_FIX_TEMPLATE,
18
+ GREMLIN_GENERATION_PROMPT,
19
+ )
20
+ from langchain_community.graphs import GremlinGraph
21
+
22
+ INTERMEDIATE_STEPS_KEY = "intermediate_steps"
23
+
24
+
25
+ def extract_gremlin(text: str) -> str:
26
+ """Extract Gremlin code from a text.
27
+
28
+ Args:
29
+ text: Text to extract Gremlin code from.
30
+
31
+ Returns:
32
+ Gremlin code extracted from the text.
33
+ """
34
+ text = text.replace("`", "")
35
+ if text.startswith("gremlin"):
36
+ text = text[len("gremlin") :]
37
+ return text.replace("\n", "")
38
+
39
+
40
+ class GremlinQAChain(Chain):
41
+ """Chain for question-answering against a graph by generating gremlin statements.
42
+
43
+ *Security note*: Make sure that the database connection uses credentials
44
+ that are narrowly-scoped to only include necessary permissions.
45
+ Failure to do so may result in data corruption or loss, since the calling
46
+ code may attempt commands that would result in deletion, mutation
47
+ of data if appropriately prompted or reading sensitive data if such
48
+ data is present in the database.
49
+ The best way to guard against such negative outcomes is to (as appropriate)
50
+ limit the permissions granted to the credentials used with this tool.
51
+
52
+ See https://python.langchain.com/docs/security for more information.
53
+ """
54
+
55
+ graph: GremlinGraph = Field(exclude=True)
56
+ gremlin_generation_chain: LLMChain
57
+ qa_chain: LLMChain
58
+ gremlin_fix_chain: LLMChain
59
+ max_fix_retries: int = 3
60
+ input_key: str = "query" #: :meta private:
61
+ output_key: str = "result" #: :meta private:
62
+ top_k: int = 100
63
+ return_direct: bool = False
64
+ return_intermediate_steps: bool = False
65
+
66
+ allow_dangerous_requests: bool = False
67
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
68
+
69
+ *Security note*: Make sure that the database connection uses credentials
70
+ that are narrowly-scoped to only include necessary permissions.
71
+ Failure to do so may result in data corruption or loss, since the calling
72
+ code may attempt commands that would result in deletion, mutation
73
+ of data if appropriately prompted or reading sensitive data if such
74
+ data is present in the database.
75
+ The best way to guard against such negative outcomes is to (as appropriate)
76
+ limit the permissions granted to the credentials used with this tool.
77
+
78
+ See https://python.langchain.com/docs/security for more information.
79
+ """
80
+
81
+ def __init__(self, **kwargs: Any) -> None:
82
+ """Initialize the chain."""
83
+ super().__init__(**kwargs)
84
+ if self.allow_dangerous_requests is not True:
85
+ raise ValueError(
86
+ "In order to use this chain, you must acknowledge that it can make "
87
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
88
+ "You must narrowly scope the permissions of the database connection "
89
+ "to only include necessary permissions. Failure to do so may result "
90
+ "in data corruption or loss or reading sensitive data if such data is "
91
+ "present in the database."
92
+ "Only use this chain if you understand the risks and have taken the "
93
+ "necessary precautions. "
94
+ "See https://python.langchain.com/docs/security for more information."
95
+ )
96
+
97
+ @property
98
+ def input_keys(self) -> List[str]:
99
+ """Input keys.
100
+
101
+ :meta private:
102
+ """
103
+ return [self.input_key]
104
+
105
+ @property
106
+ def output_keys(self) -> List[str]:
107
+ """Output keys.
108
+
109
+ :meta private:
110
+ """
111
+ _output_keys = [self.output_key]
112
+ return _output_keys
113
+
114
+ @classmethod
115
+ def from_llm(
116
+ cls,
117
+ llm: BaseLanguageModel,
118
+ *,
119
+ gremlin_fix_prompt: BasePromptTemplate = PromptTemplate(
120
+ input_variables=["error_message", "generated_sparql", "schema"],
121
+ template=GRAPHDB_SPARQL_FIX_TEMPLATE.replace("SPARQL", "Gremlin").replace(
122
+ "in Turtle format", ""
123
+ ),
124
+ ),
125
+ qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,
126
+ gremlin_prompt: BasePromptTemplate = GREMLIN_GENERATION_PROMPT,
127
+ **kwargs: Any,
128
+ ) -> GremlinQAChain:
129
+ """Initialize from LLM."""
130
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
131
+ gremlin_generation_chain = LLMChain(llm=llm, prompt=gremlin_prompt)
132
+ gremlinl_fix_chain = LLMChain(llm=llm, prompt=gremlin_fix_prompt)
133
+ return cls(
134
+ qa_chain=qa_chain,
135
+ gremlin_generation_chain=gremlin_generation_chain,
136
+ gremlin_fix_chain=gremlinl_fix_chain,
137
+ **kwargs,
138
+ )
139
+
140
+ def _call(
141
+ self,
142
+ inputs: Dict[str, Any],
143
+ run_manager: Optional[CallbackManagerForChainRun] = None,
144
+ ) -> Dict[str, str]:
145
+ """Generate gremlin statement, use it to look up in db and answer question."""
146
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
147
+ callbacks = _run_manager.get_child()
148
+ question = inputs[self.input_key]
149
+
150
+ intermediate_steps: List = []
151
+
152
+ chain_response = self.gremlin_generation_chain.invoke(
153
+ {"question": question, "schema": self.graph.get_schema}, callbacks=callbacks
154
+ )
155
+
156
+ generated_gremlin = extract_gremlin(
157
+ chain_response[self.gremlin_generation_chain.output_key]
158
+ )
159
+
160
+ _run_manager.on_text("Generated gremlin:", end="\n", verbose=self.verbose)
161
+ _run_manager.on_text(
162
+ generated_gremlin, color="green", end="\n", verbose=self.verbose
163
+ )
164
+
165
+ intermediate_steps.append({"query": generated_gremlin})
166
+
167
+ if generated_gremlin:
168
+ context = self.execute_with_retry(
169
+ _run_manager, callbacks, generated_gremlin
170
+ )[: self.top_k]
171
+ else:
172
+ context = []
173
+
174
+ if self.return_direct:
175
+ final_result = context
176
+ else:
177
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
178
+ _run_manager.on_text(
179
+ str(context), color="green", end="\n", verbose=self.verbose
180
+ )
181
+
182
+ intermediate_steps.append({"context": context})
183
+
184
+ result = self.qa_chain.invoke(
185
+ {"question": question, "context": context},
186
+ callbacks=callbacks,
187
+ )
188
+ final_result = result[self.qa_chain.output_key]
189
+
190
+ chain_result: Dict[str, Any] = {self.output_key: final_result}
191
+ if self.return_intermediate_steps:
192
+ chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps
193
+
194
+ return chain_result
195
+
196
+ def execute_query(self, query: str) -> List[Any]:
197
+ try:
198
+ return self.graph.query(query)
199
+ except Exception as e:
200
+ if hasattr(e, "status_message"):
201
+ raise ValueError(e.status_message)
202
+ else:
203
+ raise ValueError(str(e))
204
+
205
+ def execute_with_retry(
206
+ self,
207
+ _run_manager: CallbackManagerForChainRun,
208
+ callbacks: CallbackManager,
209
+ generated_gremlin: str,
210
+ ) -> List[Any]:
211
+ try:
212
+ return self.execute_query(generated_gremlin)
213
+ except Exception as e:
214
+ retries = 0
215
+ error_message = str(e)
216
+ self.log_invalid_query(_run_manager, generated_gremlin, error_message)
217
+
218
+ while retries < self.max_fix_retries:
219
+ try:
220
+ fix_chain_result = self.gremlin_fix_chain.invoke(
221
+ {
222
+ "error_message": error_message,
223
+ # we are borrowing template from sparql
224
+ "generated_sparql": generated_gremlin,
225
+ "schema": self.schema,
226
+ },
227
+ callbacks=callbacks,
228
+ )
229
+ fixed_gremlin = fix_chain_result[self.gremlin_fix_chain.output_key]
230
+ return self.execute_query(fixed_gremlin)
231
+ except Exception as e:
232
+ retries += 1
233
+ parse_exception = str(e)
234
+ self.log_invalid_query(_run_manager, fixed_gremlin, parse_exception)
235
+
236
+ raise ValueError("The generated Gremlin query is invalid.")
237
+
238
+ def log_invalid_query(
239
+ self,
240
+ _run_manager: CallbackManagerForChainRun,
241
+ generated_query: str,
242
+ error_message: str,
243
+ ) -> None:
244
+ _run_manager.on_text("Invalid Gremlin query: ", end="\n", verbose=self.verbose)
245
+ _run_manager.on_text(
246
+ generated_query, color="red", end="\n", verbose=self.verbose
247
+ )
248
+ _run_manager.on_text(
249
+ "Gremlin Query Parse Error: ", end="\n", verbose=self.verbose
250
+ )
251
+ _run_manager.on_text(
252
+ error_message, color="red", end="\n\n", verbose=self.verbose
253
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/hugegraph.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from langchain_classic.chains.base import Chain
8
+ from langchain_classic.chains.llm import LLMChain
9
+ from langchain_core.callbacks import CallbackManagerForChainRun
10
+ from langchain_core.language_models import BaseLanguageModel
11
+ from langchain_core.prompts import BasePromptTemplate
12
+ from pydantic import Field
13
+
14
+ from langchain_community.chains.graph_qa.prompts import (
15
+ CYPHER_QA_PROMPT,
16
+ GREMLIN_GENERATION_PROMPT,
17
+ )
18
+ from langchain_community.graphs.hugegraph import HugeGraph
19
+
20
+
21
+ class HugeGraphQAChain(Chain):
22
+ """Chain for question-answering against a graph by generating gremlin statements.
23
+
24
+ *Security note*: Make sure that the database connection uses credentials
25
+ that are narrowly-scoped to only include necessary permissions.
26
+ Failure to do so may result in data corruption or loss, since the calling
27
+ code may attempt commands that would result in deletion, mutation
28
+ of data if appropriately prompted or reading sensitive data if such
29
+ data is present in the database.
30
+ The best way to guard against such negative outcomes is to (as appropriate)
31
+ limit the permissions granted to the credentials used with this tool.
32
+
33
+ See https://python.langchain.com/docs/security for more information.
34
+ """
35
+
36
+ graph: HugeGraph = Field(exclude=True)
37
+ gremlin_generation_chain: LLMChain
38
+ qa_chain: LLMChain
39
+ input_key: str = "query" #: :meta private:
40
+ output_key: str = "result" #: :meta private:
41
+
42
+ allow_dangerous_requests: bool = False
43
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
44
+
45
+ *Security note*: Make sure that the database connection uses credentials
46
+ that are narrowly-scoped to only include necessary permissions.
47
+ Failure to do so may result in data corruption or loss, since the calling
48
+ code may attempt commands that would result in deletion, mutation
49
+ of data if appropriately prompted or reading sensitive data if such
50
+ data is present in the database.
51
+ The best way to guard against such negative outcomes is to (as appropriate)
52
+ limit the permissions granted to the credentials used with this tool.
53
+
54
+ See https://python.langchain.com/docs/security for more information.
55
+ """
56
+
57
+ def __init__(self, **kwargs: Any) -> None:
58
+ """Initialize the chain."""
59
+ super().__init__(**kwargs)
60
+ if self.allow_dangerous_requests is not True:
61
+ raise ValueError(
62
+ "In order to use this chain, you must acknowledge that it can make "
63
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
64
+ "You must narrowly scope the permissions of the database connection "
65
+ "to only include necessary permissions. Failure to do so may result "
66
+ "in data corruption or loss or reading sensitive data if such data is "
67
+ "present in the database."
68
+ "Only use this chain if you understand the risks and have taken the "
69
+ "necessary precautions. "
70
+ "See https://python.langchain.com/docs/security for more information."
71
+ )
72
+
73
+ @property
74
+ def input_keys(self) -> List[str]:
75
+ """Input keys.
76
+
77
+ :meta private:
78
+ """
79
+ return [self.input_key]
80
+
81
+ @property
82
+ def output_keys(self) -> List[str]:
83
+ """Output keys.
84
+
85
+ :meta private:
86
+ """
87
+ _output_keys = [self.output_key]
88
+ return _output_keys
89
+
90
+ @classmethod
91
+ def from_llm(
92
+ cls,
93
+ llm: BaseLanguageModel,
94
+ *,
95
+ qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,
96
+ gremlin_prompt: BasePromptTemplate = GREMLIN_GENERATION_PROMPT,
97
+ **kwargs: Any,
98
+ ) -> HugeGraphQAChain:
99
+ """Initialize from LLM."""
100
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
101
+ gremlin_generation_chain = LLMChain(llm=llm, prompt=gremlin_prompt)
102
+
103
+ return cls(
104
+ qa_chain=qa_chain,
105
+ gremlin_generation_chain=gremlin_generation_chain,
106
+ **kwargs,
107
+ )
108
+
109
+ def _call(
110
+ self,
111
+ inputs: Dict[str, Any],
112
+ run_manager: Optional[CallbackManagerForChainRun] = None,
113
+ ) -> Dict[str, str]:
114
+ """Generate gremlin statement, use it to look up in db and answer question."""
115
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
116
+ callbacks = _run_manager.get_child()
117
+ question = inputs[self.input_key]
118
+
119
+ generated_gremlin = self.gremlin_generation_chain.run(
120
+ {"question": question, "schema": self.graph.get_schema}, callbacks=callbacks
121
+ )
122
+
123
+ _run_manager.on_text("Generated gremlin:", end="\n", verbose=self.verbose)
124
+ _run_manager.on_text(
125
+ generated_gremlin, color="green", end="\n", verbose=self.verbose
126
+ )
127
+ context = self.graph.query(generated_gremlin)
128
+
129
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
130
+ _run_manager.on_text(
131
+ str(context), color="green", end="\n", verbose=self.verbose
132
+ )
133
+
134
+ result = self.qa_chain(
135
+ {"question": question, "context": context},
136
+ callbacks=callbacks,
137
+ )
138
+ return {self.output_key: result[self.qa_chain.output_key]}
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/kuzu.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from langchain_classic.chains.base import Chain
9
+ from langchain_classic.chains.llm import LLMChain
10
+ from langchain_core.callbacks import CallbackManagerForChainRun
11
+ from langchain_core.language_models import BaseLanguageModel
12
+ from langchain_core.prompts import BasePromptTemplate
13
+ from pydantic import Field
14
+
15
+ from langchain_community.chains.graph_qa.prompts import (
16
+ CYPHER_QA_PROMPT,
17
+ KUZU_GENERATION_PROMPT,
18
+ )
19
+ from langchain_community.graphs.kuzu_graph import KuzuGraph
20
+
21
+
22
+ def remove_prefix(text: str, prefix: str) -> str:
23
+ """Remove a prefix from a text.
24
+
25
+ Args:
26
+ text: Text to remove the prefix from.
27
+ prefix: Prefix to remove from the text.
28
+
29
+ Returns:
30
+ Text with the prefix removed.
31
+ """
32
+ if text.startswith(prefix):
33
+ return text[len(prefix) :]
34
+ return text
35
+
36
+
37
+ def extract_cypher(text: str) -> str:
38
+ """Extract Cypher code from a text.
39
+
40
+ Args:
41
+ text: Text to extract Cypher code from.
42
+
43
+ Returns:
44
+ Cypher code extracted from the text.
45
+ """
46
+ # The pattern to find Cypher code enclosed in triple backticks
47
+ pattern = r"```(.*?)```"
48
+
49
+ # Find all matches in the input text
50
+ matches = re.findall(pattern, text, re.DOTALL)
51
+
52
+ return matches[0] if matches else text
53
+
54
+
55
+ class KuzuQAChain(Chain):
56
+ """Question-answering against a graph by generating Cypher statements for Kùzu.
57
+
58
+ *Security note*: Make sure that the database connection uses credentials
59
+ that are narrowly-scoped to only include necessary permissions.
60
+ Failure to do so may result in data corruption or loss, since the calling
61
+ code may attempt commands that would result in deletion, mutation
62
+ of data if appropriately prompted or reading sensitive data if such
63
+ data is present in the database.
64
+ The best way to guard against such negative outcomes is to (as appropriate)
65
+ limit the permissions granted to the credentials used with this tool.
66
+
67
+ See https://python.langchain.com/docs/security for more information.
68
+ """
69
+
70
+ graph: KuzuGraph = Field(exclude=True)
71
+ cypher_generation_chain: LLMChain
72
+ qa_chain: LLMChain
73
+ input_key: str = "query" #: :meta private:
74
+ output_key: str = "result" #: :meta private:
75
+
76
+ allow_dangerous_requests: bool = False
77
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
78
+
79
+ *Security note*: Make sure that the database connection uses credentials
80
+ that are narrowly-scoped to only include necessary permissions.
81
+ Failure to do so may result in data corruption or loss, since the calling
82
+ code may attempt commands that would result in deletion, mutation
83
+ of data if appropriately prompted or reading sensitive data if such
84
+ data is present in the database.
85
+ The best way to guard against such negative outcomes is to (as appropriate)
86
+ limit the permissions granted to the credentials used with this tool.
87
+
88
+ See https://python.langchain.com/docs/security for more information.
89
+ """
90
+
91
+ def __init__(self, **kwargs: Any) -> None:
92
+ """Initialize the chain."""
93
+ super().__init__(**kwargs)
94
+ if self.allow_dangerous_requests is not True:
95
+ raise ValueError(
96
+ "In order to use this chain, you must acknowledge that it can make "
97
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
98
+ "You must narrowly scope the permissions of the database connection "
99
+ "to only include necessary permissions. Failure to do so may result "
100
+ "in data corruption or loss or reading sensitive data if such data is "
101
+ "present in the database."
102
+ "Only use this chain if you understand the risks and have taken the "
103
+ "necessary precautions. "
104
+ "See https://python.langchain.com/docs/security for more information."
105
+ )
106
+
107
+ @property
108
+ def input_keys(self) -> List[str]:
109
+ """Return the input keys.
110
+
111
+ :meta private:
112
+ """
113
+ return [self.input_key]
114
+
115
+ @property
116
+ def output_keys(self) -> List[str]:
117
+ """Return the output keys.
118
+
119
+ :meta private:
120
+ """
121
+ _output_keys = [self.output_key]
122
+ return _output_keys
123
+
124
+ @classmethod
125
+ def from_llm(
126
+ cls,
127
+ llm: Optional[BaseLanguageModel] = None,
128
+ *,
129
+ qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,
130
+ cypher_prompt: BasePromptTemplate = KUZU_GENERATION_PROMPT,
131
+ cypher_llm: Optional[BaseLanguageModel] = None,
132
+ qa_llm: Optional[BaseLanguageModel] = None,
133
+ **kwargs: Any,
134
+ ) -> KuzuQAChain:
135
+ """Initialize from LLM."""
136
+ if not cypher_llm and not llm:
137
+ raise ValueError("Either `llm` or `cypher_llm` parameters must be provided")
138
+ if not qa_llm and not llm:
139
+ raise ValueError(
140
+ "Either `llm` or `qa_llm` parameters must be provided along with"
141
+ " `cypher_llm`"
142
+ )
143
+ if cypher_llm and qa_llm and llm:
144
+ raise ValueError(
145
+ "You can specify up to two of 'cypher_llm', 'qa_llm'"
146
+ ", and 'llm', but not all three simultaneously."
147
+ )
148
+
149
+ qa_chain = LLMChain(
150
+ llm=qa_llm or llm, # type: ignore[arg-type]
151
+ prompt=qa_prompt,
152
+ )
153
+ cypher_generation_chain = LLMChain(
154
+ llm=cypher_llm or llm, # type: ignore[arg-type]
155
+ prompt=cypher_prompt,
156
+ )
157
+
158
+ return cls(
159
+ qa_chain=qa_chain,
160
+ cypher_generation_chain=cypher_generation_chain,
161
+ **kwargs,
162
+ )
163
+
164
+ def _call(
165
+ self,
166
+ inputs: Dict[str, Any],
167
+ run_manager: Optional[CallbackManagerForChainRun] = None,
168
+ ) -> Dict[str, str]:
169
+ """Generate Cypher statement, use it to look up in db and answer question."""
170
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
171
+ callbacks = _run_manager.get_child()
172
+ question = inputs[self.input_key]
173
+
174
+ generated_cypher = self.cypher_generation_chain.run(
175
+ {"question": question, "schema": self.graph.get_schema}, callbacks=callbacks
176
+ )
177
+ # Extract Cypher code if it is wrapped in triple backticks
178
+ # with the language marker "cypher"
179
+ generated_cypher = remove_prefix(extract_cypher(generated_cypher), "cypher")
180
+
181
+ _run_manager.on_text("Generated Cypher:", end="\n", verbose=self.verbose)
182
+ _run_manager.on_text(
183
+ generated_cypher, color="green", end="\n", verbose=self.verbose
184
+ )
185
+ context = self.graph.query(generated_cypher)
186
+
187
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
188
+ _run_manager.on_text(
189
+ str(context), color="green", end="\n", verbose=self.verbose
190
+ )
191
+
192
+ result = self.qa_chain(
193
+ {"question": question, "context": context},
194
+ callbacks=callbacks,
195
+ )
196
+ return {self.output_key: result[self.qa_chain.output_key]}
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/memgraph.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Dict, List, Optional, Union
7
+
8
+ from langchain_classic.chains.base import Chain
9
+ from langchain_core.callbacks import CallbackManagerForChainRun
10
+ from langchain_core.language_models import BaseLanguageModel
11
+ from langchain_core.messages import (
12
+ AIMessage,
13
+ BaseMessage,
14
+ SystemMessage,
15
+ ToolMessage,
16
+ )
17
+ from langchain_core.output_parsers import StrOutputParser
18
+ from langchain_core.prompts import (
19
+ BasePromptTemplate,
20
+ ChatPromptTemplate,
21
+ HumanMessagePromptTemplate,
22
+ MessagesPlaceholder,
23
+ )
24
+ from langchain_core.runnables import Runnable
25
+ from pydantic import Field
26
+
27
+ from langchain_community.chains.graph_qa.prompts import (
28
+ MEMGRAPH_GENERATION_PROMPT,
29
+ MEMGRAPH_QA_PROMPT,
30
+ )
31
+ from langchain_community.graphs.memgraph_graph import MemgraphGraph
32
+
33
+ INTERMEDIATE_STEPS_KEY = "intermediate_steps"
34
+
35
+ FUNCTION_RESPONSE_SYSTEM = """You are an assistant that helps to form nice and human
36
+ understandable answers based on the provided information from tools.
37
+ Do not add any other information that wasn't present in the tools, and use
38
+ very concise style in interpreting results!
39
+ """
40
+
41
+
42
+ def extract_cypher(text: str) -> str:
43
+ """Extract Cypher code from a text.
44
+
45
+ Args:
46
+ text: Text to extract Cypher code from.
47
+
48
+ Returns:
49
+ Cypher code extracted from the text.
50
+ """
51
+ # The pattern to find Cypher code enclosed in triple backticks
52
+ pattern = r"```(.*?)```"
53
+
54
+ # Find all matches in the input text
55
+ matches = re.findall(pattern, text, re.DOTALL)
56
+
57
+ return matches[0] if matches else text
58
+
59
+
60
+ def get_function_response(
61
+ question: str, context: List[Dict[str, Any]]
62
+ ) -> List[BaseMessage]:
63
+ TOOL_ID = "call_H7fABDuzEau48T10Qn0Lsh0D"
64
+ messages = [
65
+ AIMessage(
66
+ content="",
67
+ additional_kwargs={
68
+ "tool_calls": [
69
+ {
70
+ "id": TOOL_ID,
71
+ "function": {
72
+ "arguments": '{"question":"' + question + '"}',
73
+ "name": "GetInformation",
74
+ },
75
+ "type": "function",
76
+ }
77
+ ]
78
+ },
79
+ ),
80
+ ToolMessage(content=str(context), tool_call_id=TOOL_ID),
81
+ ]
82
+ return messages
83
+
84
+
85
+ class MemgraphQAChain(Chain):
86
+ """Chain for question-answering against a graph by generating Cypher statements.
87
+
88
+ *Security note*: Make sure that the database connection uses credentials
89
+ that are narrowly-scoped to only include necessary permissions.
90
+ Failure to do so may result in data corruption or loss, since the calling
91
+ code may attempt commands that would result in deletion, mutation
92
+ of data if appropriately prompted or reading sensitive data if such
93
+ data is present in the database.
94
+ The best way to guard against such negative outcomes is to (as appropriate)
95
+ limit the permissions granted to the credentials used with this tool.
96
+
97
+ See https://python.langchain.com/docs/security for more information.
98
+ """
99
+
100
+ graph: MemgraphGraph = Field(exclude=True)
101
+ cypher_generation_chain: Runnable
102
+ qa_chain: Runnable
103
+ graph_schema: str
104
+ input_key: str = "query" #: :meta private:
105
+ output_key: str = "result" #: :meta private:
106
+ top_k: int = 10
107
+ """Number of results to return from the query"""
108
+ return_intermediate_steps: bool = False
109
+ """Whether or not to return the intermediate steps along with the final answer."""
110
+ return_direct: bool = False
111
+ """Optional cypher validation tool"""
112
+ use_function_response: bool = False
113
+ """Whether to wrap the database context as tool/function response"""
114
+ allow_dangerous_requests: bool = False
115
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
116
+
117
+ *Security note*: Make sure that the database connection uses credentials
118
+ that are narrowly-scoped to only include necessary permissions.
119
+ Failure to do so may result in data corruption or loss, since the calling
120
+ code may attempt commands that would result in deletion, mutation
121
+ of data if appropriately prompted or reading sensitive data if such
122
+ data is present in the database.
123
+ The best way to guard against such negative outcomes is to (as appropriate)
124
+ limit the permissions granted to the credentials used with this tool.
125
+
126
+ See https://python.langchain.com/docs/security for more information.
127
+ """
128
+
129
+ def __init__(self, **kwargs: Any) -> None:
130
+ """Initialize the chain."""
131
+ super().__init__(**kwargs)
132
+ if self.allow_dangerous_requests is not True:
133
+ raise ValueError(
134
+ "In order to use this chain, you must acknowledge that it can make "
135
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
136
+ "You must narrowly scope the permissions of the database connection "
137
+ "to only include necessary permissions. Failure to do so may result "
138
+ "in data corruption or loss or reading sensitive data if such data is "
139
+ "present in the database."
140
+ "Only use this chain if you understand the risks and have taken the "
141
+ "necessary precautions. "
142
+ "See https://python.langchain.com/docs/security for more information."
143
+ )
144
+
145
+ @property
146
+ def input_keys(self) -> List[str]:
147
+ """Return the input keys.
148
+
149
+ :meta private:
150
+ """
151
+ return [self.input_key]
152
+
153
+ @property
154
+ def output_keys(self) -> List[str]:
155
+ """Return the output keys.
156
+
157
+ :meta private:
158
+ """
159
+ _output_keys = [self.output_key]
160
+ return _output_keys
161
+
162
+ @property
163
+ def _chain_type(self) -> str:
164
+ return "graph_cypher_chain"
165
+
166
+ @classmethod
167
+ def from_llm(
168
+ cls,
169
+ llm: Optional[BaseLanguageModel] = None,
170
+ *,
171
+ qa_prompt: Optional[BasePromptTemplate] = None,
172
+ cypher_prompt: Optional[BasePromptTemplate] = None,
173
+ cypher_llm: Optional[BaseLanguageModel] = None,
174
+ qa_llm: Optional[Union[BaseLanguageModel, Any]] = None,
175
+ qa_llm_kwargs: Optional[Dict[str, Any]] = None,
176
+ cypher_llm_kwargs: Optional[Dict[str, Any]] = None,
177
+ use_function_response: bool = False,
178
+ function_response_system: str = FUNCTION_RESPONSE_SYSTEM,
179
+ **kwargs: Any,
180
+ ) -> MemgraphQAChain:
181
+ """Initialize from LLM."""
182
+
183
+ if not cypher_llm and not llm:
184
+ raise ValueError("Either `llm` or `cypher_llm` parameters must be provided")
185
+ if not qa_llm and not llm:
186
+ raise ValueError("Either `llm` or `qa_llm` parameters must be provided")
187
+ if cypher_llm and qa_llm and llm:
188
+ raise ValueError(
189
+ "You can specify up to two of 'cypher_llm', 'qa_llm'"
190
+ ", and 'llm', but not all three simultaneously."
191
+ )
192
+ if cypher_prompt and cypher_llm_kwargs:
193
+ raise ValueError(
194
+ "Specifying cypher_prompt and cypher_llm_kwargs together is"
195
+ " not allowed. Please pass prompt via cypher_llm_kwargs."
196
+ )
197
+ if qa_prompt and qa_llm_kwargs:
198
+ raise ValueError(
199
+ "Specifying qa_prompt and qa_llm_kwargs together is"
200
+ " not allowed. Please pass prompt via qa_llm_kwargs."
201
+ )
202
+ use_qa_llm_kwargs = qa_llm_kwargs if qa_llm_kwargs is not None else {}
203
+ use_cypher_llm_kwargs = (
204
+ cypher_llm_kwargs if cypher_llm_kwargs is not None else {}
205
+ )
206
+ if "prompt" not in use_qa_llm_kwargs:
207
+ use_qa_llm_kwargs["prompt"] = (
208
+ qa_prompt if qa_prompt is not None else MEMGRAPH_QA_PROMPT
209
+ )
210
+ if "prompt" not in use_cypher_llm_kwargs:
211
+ use_cypher_llm_kwargs["prompt"] = (
212
+ cypher_prompt
213
+ if cypher_prompt is not None
214
+ else MEMGRAPH_GENERATION_PROMPT
215
+ )
216
+
217
+ qa_llm = qa_llm or llm
218
+ if use_function_response:
219
+ try:
220
+ qa_llm.bind_tools({}) # type: ignore[union-attr]
221
+ response_prompt = ChatPromptTemplate.from_messages(
222
+ [
223
+ SystemMessage(content=function_response_system),
224
+ HumanMessagePromptTemplate.from_template("{question}"),
225
+ MessagesPlaceholder(variable_name="function_response"),
226
+ ]
227
+ )
228
+ qa_chain = response_prompt | qa_llm | StrOutputParser() # type: ignore[operator]
229
+ except (NotImplementedError, AttributeError):
230
+ raise ValueError("Provided LLM does not support native tools/functions")
231
+ else:
232
+ qa_chain = use_qa_llm_kwargs["prompt"] | qa_llm | StrOutputParser()
233
+
234
+ prompt = use_cypher_llm_kwargs["prompt"]
235
+ llm_to_use = cypher_llm if cypher_llm is not None else llm
236
+
237
+ if prompt is not None and llm_to_use is not None:
238
+ cypher_generation_chain = prompt | llm_to_use | StrOutputParser()
239
+ else:
240
+ raise ValueError(
241
+ "Missing required components for the cypher generation chain: "
242
+ "'prompt' or 'llm'"
243
+ )
244
+
245
+ graph_schema = kwargs["graph"].get_schema
246
+
247
+ return cls(
248
+ graph_schema=graph_schema,
249
+ qa_chain=qa_chain,
250
+ cypher_generation_chain=cypher_generation_chain,
251
+ use_function_response=use_function_response,
252
+ **kwargs,
253
+ )
254
+
255
+ def _call(
256
+ self,
257
+ inputs: Dict[str, Any],
258
+ run_manager: Optional[CallbackManagerForChainRun] = None,
259
+ ) -> Dict[str, Any]:
260
+ """Generate Cypher statement, use it to look up in db and answer question."""
261
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
262
+ callbacks = _run_manager.get_child()
263
+ question = inputs[self.input_key]
264
+ args = {
265
+ "question": question,
266
+ "schema": self.graph_schema,
267
+ }
268
+ args.update(inputs)
269
+
270
+ intermediate_steps: List = []
271
+
272
+ generated_cypher = self.cypher_generation_chain.invoke(
273
+ args, callbacks=callbacks
274
+ )
275
+ # Extract Cypher code if it is wrapped in backticks
276
+ generated_cypher = extract_cypher(generated_cypher)
277
+
278
+ _run_manager.on_text("Generated Cypher:", end="\n", verbose=self.verbose)
279
+ _run_manager.on_text(
280
+ generated_cypher, color="green", end="\n", verbose=self.verbose
281
+ )
282
+
283
+ intermediate_steps.append({"query": generated_cypher})
284
+
285
+ # Retrieve and limit the number of results
286
+ # Generated Cypher be null if query corrector identifies invalid schema
287
+ if generated_cypher:
288
+ context = self.graph.query(generated_cypher)[: self.top_k]
289
+ else:
290
+ context = []
291
+
292
+ if self.return_direct:
293
+ result = context
294
+ else:
295
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
296
+ _run_manager.on_text(
297
+ str(context), color="green", end="\n", verbose=self.verbose
298
+ )
299
+
300
+ intermediate_steps.append({"context": context})
301
+ if self.use_function_response:
302
+ function_response = get_function_response(question, context)
303
+ result = self.qa_chain.invoke(
304
+ {"question": question, "function_response": function_response},
305
+ )
306
+ else:
307
+ result = self.qa_chain.invoke(
308
+ {"question": question, "context": context},
309
+ callbacks=callbacks,
310
+ )
311
+
312
+ chain_result: Dict[str, Any] = {"result": result}
313
+ if self.return_intermediate_steps:
314
+ chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps
315
+
316
+ return chain_result
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/nebulagraph.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from langchain_classic.chains.base import Chain
8
+ from langchain_classic.chains.llm import LLMChain
9
+ from langchain_core.callbacks import CallbackManagerForChainRun
10
+ from langchain_core.language_models import BaseLanguageModel
11
+ from langchain_core.prompts import BasePromptTemplate
12
+ from pydantic import Field
13
+
14
+ from langchain_community.chains.graph_qa.prompts import (
15
+ CYPHER_QA_PROMPT,
16
+ NGQL_GENERATION_PROMPT,
17
+ )
18
+ from langchain_community.graphs.nebula_graph import NebulaGraph
19
+
20
+
21
+ class NebulaGraphQAChain(Chain):
22
+ """Chain for question-answering against a graph by generating nGQL statements.
23
+
24
+ *Security note*: Make sure that the database connection uses credentials
25
+ that are narrowly-scoped to only include necessary permissions.
26
+ Failure to do so may result in data corruption or loss, since the calling
27
+ code may attempt commands that would result in deletion, mutation
28
+ of data if appropriately prompted or reading sensitive data if such
29
+ data is present in the database.
30
+ The best way to guard against such negative outcomes is to (as appropriate)
31
+ limit the permissions granted to the credentials used with this tool.
32
+
33
+ See https://python.langchain.com/docs/security for more information.
34
+ """
35
+
36
+ graph: NebulaGraph = Field(exclude=True)
37
+ ngql_generation_chain: LLMChain
38
+ qa_chain: LLMChain
39
+ input_key: str = "query" #: :meta private:
40
+ output_key: str = "result" #: :meta private:
41
+
42
+ allow_dangerous_requests: bool = False
43
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
44
+
45
+ *Security note*: Make sure that the database connection uses credentials
46
+ that are narrowly-scoped to only include necessary permissions.
47
+ Failure to do so may result in data corruption or loss, since the calling
48
+ code may attempt commands that would result in deletion, mutation
49
+ of data if appropriately prompted or reading sensitive data if such
50
+ data is present in the database.
51
+ The best way to guard against such negative outcomes is to (as appropriate)
52
+ limit the permissions granted to the credentials used with this tool.
53
+
54
+ See https://python.langchain.com/docs/security for more information.
55
+ """
56
+
57
+ def __init__(self, **kwargs: Any) -> None:
58
+ """Initialize the chain."""
59
+ super().__init__(**kwargs)
60
+ if self.allow_dangerous_requests is not True:
61
+ raise ValueError(
62
+ "In order to use this chain, you must acknowledge that it can make "
63
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
64
+ "You must narrowly scope the permissions of the database connection "
65
+ "to only include necessary permissions. Failure to do so may result "
66
+ "in data corruption or loss or reading sensitive data if such data is "
67
+ "present in the database."
68
+ "Only use this chain if you understand the risks and have taken the "
69
+ "necessary precautions. "
70
+ "See https://python.langchain.com/docs/security for more information."
71
+ )
72
+
73
+ @property
74
+ def input_keys(self) -> List[str]:
75
+ """Return the input keys.
76
+
77
+ :meta private:
78
+ """
79
+ return [self.input_key]
80
+
81
+ @property
82
+ def output_keys(self) -> List[str]:
83
+ """Return the output keys.
84
+
85
+ :meta private:
86
+ """
87
+ _output_keys = [self.output_key]
88
+ return _output_keys
89
+
90
+ @classmethod
91
+ def from_llm(
92
+ cls,
93
+ llm: BaseLanguageModel,
94
+ *,
95
+ qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,
96
+ ngql_prompt: BasePromptTemplate = NGQL_GENERATION_PROMPT,
97
+ **kwargs: Any,
98
+ ) -> NebulaGraphQAChain:
99
+ """Initialize from LLM."""
100
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
101
+ ngql_generation_chain = LLMChain(llm=llm, prompt=ngql_prompt)
102
+
103
+ return cls(
104
+ qa_chain=qa_chain,
105
+ ngql_generation_chain=ngql_generation_chain,
106
+ **kwargs,
107
+ )
108
+
109
+ def _call(
110
+ self,
111
+ inputs: Dict[str, Any],
112
+ run_manager: Optional[CallbackManagerForChainRun] = None,
113
+ ) -> Dict[str, str]:
114
+ """Generate nGQL statement, use it to look up in db and answer question."""
115
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
116
+ callbacks = _run_manager.get_child()
117
+ question = inputs[self.input_key]
118
+
119
+ generated_ngql = self.ngql_generation_chain.run(
120
+ {"question": question, "schema": self.graph.get_schema}, callbacks=callbacks
121
+ )
122
+
123
+ _run_manager.on_text("Generated nGQL:", end="\n", verbose=self.verbose)
124
+ _run_manager.on_text(
125
+ generated_ngql, color="green", end="\n", verbose=self.verbose
126
+ )
127
+ context = self.graph.query(generated_ngql)
128
+
129
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
130
+ _run_manager.on_text(
131
+ str(context), color="green", end="\n", verbose=self.verbose
132
+ )
133
+
134
+ result = self.qa_chain(
135
+ {"question": question, "context": context},
136
+ callbacks=callbacks,
137
+ )
138
+ return {self.output_key: result[self.qa_chain.output_key]}
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/neptune_cypher.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from langchain_classic.chains.base import Chain
7
+ from langchain_classic.chains.llm import LLMChain
8
+ from langchain_classic.chains.prompt_selector import ConditionalPromptSelector
9
+ from langchain_core._api.deprecation import deprecated
10
+ from langchain_core.callbacks import CallbackManagerForChainRun
11
+ from langchain_core.language_models import BaseLanguageModel
12
+ from langchain_core.prompts.base import BasePromptTemplate
13
+ from pydantic import Field
14
+
15
+ from langchain_community.chains.graph_qa.prompts import (
16
+ CYPHER_QA_PROMPT,
17
+ NEPTUNE_OPENCYPHER_GENERATION_PROMPT,
18
+ NEPTUNE_OPENCYPHER_GENERATION_SIMPLE_PROMPT,
19
+ )
20
+ from langchain_community.graphs import BaseNeptuneGraph
21
+
22
+ INTERMEDIATE_STEPS_KEY = "intermediate_steps"
23
+
24
+
25
+ def trim_query(query: str) -> str:
26
+ """Trim the query to only include Cypher keywords."""
27
+ keywords = (
28
+ "CALL",
29
+ "CREATE",
30
+ "DELETE",
31
+ "DETACH",
32
+ "LIMIT",
33
+ "MATCH",
34
+ "MERGE",
35
+ "OPTIONAL",
36
+ "ORDER",
37
+ "REMOVE",
38
+ "RETURN",
39
+ "SET",
40
+ "SKIP",
41
+ "UNWIND",
42
+ "WITH",
43
+ "WHERE",
44
+ "//",
45
+ )
46
+
47
+ lines = query.split("\n")
48
+ new_query = ""
49
+
50
+ for line in lines:
51
+ if line.strip().upper().startswith(keywords):
52
+ new_query += line + "\n"
53
+
54
+ return new_query
55
+
56
+
57
+ def extract_cypher(text: str) -> str:
58
+ """Extract Cypher code from text using Regex."""
59
+ # The pattern to find Cypher code enclosed in triple backticks
60
+ pattern = r"```(.*?)```"
61
+
62
+ # Find all matches in the input text
63
+ matches = re.findall(pattern, text, re.DOTALL)
64
+
65
+ return matches[0] if matches else text
66
+
67
+
68
+ def use_simple_prompt(llm: BaseLanguageModel) -> bool:
69
+ """Decides whether to use the simple prompt"""
70
+ if llm._llm_type and "anthropic" in llm._llm_type: # type: ignore[attr-defined]
71
+ return True
72
+
73
+ # Bedrock anthropic
74
+ if hasattr(llm, "model_id") and "anthropic" in llm.model_id:
75
+ return True
76
+
77
+ return False
78
+
79
+
80
+ PROMPT_SELECTOR = ConditionalPromptSelector(
81
+ default_prompt=NEPTUNE_OPENCYPHER_GENERATION_PROMPT,
82
+ conditionals=[(use_simple_prompt, NEPTUNE_OPENCYPHER_GENERATION_SIMPLE_PROMPT)],
83
+ )
84
+
85
+
86
+ @deprecated(
87
+ since="0.3.15",
88
+ removal="1.0",
89
+ alternative_import="langchain_aws.create_neptune_opencypher_qa_chain",
90
+ )
91
+ class NeptuneOpenCypherQAChain(Chain):
92
+ """Chain for question-answering against a Neptune graph
93
+ by generating openCypher statements.
94
+
95
+ *Security note*: Make sure that the database connection uses credentials
96
+ that are narrowly-scoped to only include necessary permissions.
97
+ Failure to do so may result in data corruption or loss, since the calling
98
+ code may attempt commands that would result in deletion, mutation
99
+ of data if appropriately prompted or reading sensitive data if such
100
+ data is present in the database.
101
+ The best way to guard against such negative outcomes is to (as appropriate)
102
+ limit the permissions granted to the credentials used with this tool.
103
+
104
+ See https://python.langchain.com/docs/security for more information.
105
+
106
+ Example:
107
+ .. code-block:: python
108
+
109
+ chain = NeptuneOpenCypherQAChain.from_llm(
110
+ llm=llm,
111
+ graph=graph
112
+ )
113
+ response = chain.run(query)
114
+ """
115
+
116
+ graph: BaseNeptuneGraph = Field(exclude=True)
117
+ cypher_generation_chain: LLMChain
118
+ qa_chain: LLMChain
119
+ input_key: str = "query" #: :meta private:
120
+ output_key: str = "result" #: :meta private:
121
+ top_k: int = 10
122
+ return_intermediate_steps: bool = False
123
+ """Whether or not to return the intermediate steps along with the final answer."""
124
+ return_direct: bool = False
125
+ """Whether or not to return the result of querying the graph directly."""
126
+ extra_instructions: Optional[str] = None
127
+ """Extra instructions by the appended to the query generation prompt."""
128
+
129
+ allow_dangerous_requests: bool = False
130
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
131
+
132
+ *Security note*: Make sure that the database connection uses credentials
133
+ that are narrowly-scoped to only include necessary permissions.
134
+ Failure to do so may result in data corruption or loss, since the calling
135
+ code may attempt commands that would result in deletion, mutation
136
+ of data if appropriately prompted or reading sensitive data if such
137
+ data is present in the database.
138
+ The best way to guard against such negative outcomes is to (as appropriate)
139
+ limit the permissions granted to the credentials used with this tool.
140
+
141
+ See https://python.langchain.com/docs/security for more information.
142
+ """
143
+
144
+ def __init__(self, **kwargs: Any) -> None:
145
+ """Initialize the chain."""
146
+ super().__init__(**kwargs)
147
+ if self.allow_dangerous_requests is not True:
148
+ raise ValueError(
149
+ "In order to use this chain, you must acknowledge that it can make "
150
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
151
+ "You must narrowly scope the permissions of the database connection "
152
+ "to only include necessary permissions. Failure to do so may result "
153
+ "in data corruption or loss or reading sensitive data if such data is "
154
+ "present in the database."
155
+ "Only use this chain if you understand the risks and have taken the "
156
+ "necessary precautions. "
157
+ "See https://python.langchain.com/docs/security for more information."
158
+ )
159
+
160
+ @property
161
+ def input_keys(self) -> List[str]:
162
+ """Return the input keys.
163
+
164
+ :meta private:
165
+ """
166
+ return [self.input_key]
167
+
168
+ @property
169
+ def output_keys(self) -> List[str]:
170
+ """Return the output keys.
171
+
172
+ :meta private:
173
+ """
174
+ _output_keys = [self.output_key]
175
+ return _output_keys
176
+
177
+ @classmethod
178
+ def from_llm(
179
+ cls,
180
+ llm: BaseLanguageModel,
181
+ *,
182
+ qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,
183
+ cypher_prompt: Optional[BasePromptTemplate] = None,
184
+ extra_instructions: Optional[str] = None,
185
+ **kwargs: Any,
186
+ ) -> NeptuneOpenCypherQAChain:
187
+ """Initialize from LLM."""
188
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
189
+
190
+ _cypher_prompt = cypher_prompt or PROMPT_SELECTOR.get_prompt(llm)
191
+ cypher_generation_chain = LLMChain(llm=llm, prompt=_cypher_prompt)
192
+
193
+ return cls(
194
+ qa_chain=qa_chain,
195
+ cypher_generation_chain=cypher_generation_chain,
196
+ extra_instructions=extra_instructions,
197
+ **kwargs,
198
+ )
199
+
200
+ def _call(
201
+ self,
202
+ inputs: Dict[str, Any],
203
+ run_manager: Optional[CallbackManagerForChainRun] = None,
204
+ ) -> Dict[str, Any]:
205
+ """Generate Cypher statement, use it to look up in db and answer question."""
206
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
207
+ callbacks = _run_manager.get_child()
208
+ question = inputs[self.input_key]
209
+
210
+ intermediate_steps: List = []
211
+
212
+ generated_cypher = self.cypher_generation_chain.run(
213
+ {
214
+ "question": question,
215
+ "schema": self.graph.get_schema,
216
+ "extra_instructions": self.extra_instructions or "",
217
+ },
218
+ callbacks=callbacks,
219
+ )
220
+
221
+ # Extract Cypher code if it is wrapped in backticks
222
+ generated_cypher = extract_cypher(generated_cypher)
223
+ generated_cypher = trim_query(generated_cypher)
224
+
225
+ _run_manager.on_text("Generated Cypher:", end="\n", verbose=self.verbose)
226
+ _run_manager.on_text(
227
+ generated_cypher, color="green", end="\n", verbose=self.verbose
228
+ )
229
+
230
+ intermediate_steps.append({"query": generated_cypher})
231
+
232
+ context = self.graph.query(generated_cypher)
233
+
234
+ if self.return_direct:
235
+ final_result = context
236
+ else:
237
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
238
+ _run_manager.on_text(
239
+ str(context), color="green", end="\n", verbose=self.verbose
240
+ )
241
+
242
+ intermediate_steps.append({"context": context})
243
+
244
+ result = self.qa_chain(
245
+ {"question": question, "context": context},
246
+ callbacks=callbacks,
247
+ )
248
+ final_result = result[self.qa_chain.output_key]
249
+
250
+ chain_result: Dict[str, Any] = {self.output_key: final_result}
251
+ if self.return_intermediate_steps:
252
+ chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps
253
+
254
+ return chain_result
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/neptune_sparql.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Question answering over an RDF or OWL graph using SPARQL.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ from langchain_classic.chains.base import Chain
10
+ from langchain_classic.chains.llm import LLMChain
11
+ from langchain_core._api.deprecation import deprecated
12
+ from langchain_core.callbacks.manager import CallbackManagerForChainRun
13
+ from langchain_core.language_models import BaseLanguageModel
14
+ from langchain_core.prompts.base import BasePromptTemplate
15
+ from langchain_core.prompts.prompt import PromptTemplate
16
+ from pydantic import Field
17
+
18
+ from langchain_community.chains.graph_qa.prompts import SPARQL_QA_PROMPT
19
+ from langchain_community.graphs import NeptuneRdfGraph
20
+
21
+ INTERMEDIATE_STEPS_KEY = "intermediate_steps"
22
+
23
+ SPARQL_GENERATION_TEMPLATE = """
24
+ Task: Generate a SPARQL SELECT statement for querying a graph database.
25
+ For instance, to find all email addresses of John Doe, the following
26
+ query in backticks would be suitable:
27
+ ```
28
+ PREFIX foaf: <http://xmlns.com/foaf/0.1/>
29
+ SELECT ?email
30
+ WHERE {{
31
+ ?person foaf:name "John Doe" .
32
+ ?person foaf:mbox ?email .
33
+ }}
34
+ ```
35
+ Instructions:
36
+ Use only the node types and properties provided in the schema.
37
+ Do not use any node types and properties that are not explicitly provided.
38
+ Include all necessary prefixes.
39
+
40
+ Examples:
41
+
42
+ Schema:
43
+ {schema}
44
+ Note: Be as concise as possible.
45
+ Do not include any explanations or apologies in your responses.
46
+ Do not respond to any questions that ask for anything else than
47
+ for you to construct a SPARQL query.
48
+ Do not include any text except the SPARQL query generated.
49
+
50
+ The question is:
51
+ {prompt}"""
52
+
53
+ SPARQL_GENERATION_PROMPT = PromptTemplate(
54
+ input_variables=["schema", "prompt"], template=SPARQL_GENERATION_TEMPLATE
55
+ )
56
+
57
+
58
+ def extract_sparql(query: str) -> str:
59
+ """Extract SPARQL code from a text.
60
+
61
+ Args:
62
+ query: Text to extract SPARQL code from.
63
+
64
+ Returns:
65
+ SPARQL code extracted from the text.
66
+ """
67
+ query = query.strip()
68
+ querytoks = query.split("```")
69
+ if len(querytoks) == 3:
70
+ query = querytoks[1]
71
+
72
+ if query.startswith("sparql"):
73
+ query = query[6:]
74
+ elif query.startswith("<sparql>") and query.endswith("</sparql>"):
75
+ query = query[8:-9]
76
+ return query
77
+
78
+
79
+ @deprecated(
80
+ since="0.3.15",
81
+ removal="1.0",
82
+ alternative_import="langchain_aws.create_neptune_sparql_qa_chain",
83
+ )
84
+ class NeptuneSparqlQAChain(Chain):
85
+ """Chain for question-answering against a Neptune graph
86
+ by generating SPARQL statements.
87
+
88
+ *Security note*: Make sure that the database connection uses credentials
89
+ that are narrowly-scoped to only include necessary permissions.
90
+ Failure to do so may result in data corruption or loss, since the calling
91
+ code may attempt commands that would result in deletion, mutation
92
+ of data if appropriately prompted or reading sensitive data if such
93
+ data is present in the database.
94
+ The best way to guard against such negative outcomes is to (as appropriate)
95
+ limit the permissions granted to the credentials used with this tool.
96
+
97
+ See https://python.langchain.com/docs/security for more information.
98
+
99
+ Example:
100
+ .. code-block:: python
101
+
102
+ chain = NeptuneSparqlQAChain.from_llm(
103
+ llm=llm,
104
+ graph=graph
105
+ )
106
+ response = chain.invoke(query)
107
+ """
108
+
109
+ graph: NeptuneRdfGraph = Field(exclude=True)
110
+ sparql_generation_chain: LLMChain
111
+ qa_chain: LLMChain
112
+ input_key: str = "query" #: :meta private:
113
+ output_key: str = "result" #: :meta private:
114
+ top_k: int = 10
115
+ return_intermediate_steps: bool = False
116
+ """Whether or not to return the intermediate steps along with the final answer."""
117
+ return_direct: bool = False
118
+ """Whether or not to return the result of querying the graph directly."""
119
+ extra_instructions: Optional[str] = None
120
+ """Extra instructions by the appended to the query generation prompt."""
121
+
122
+ allow_dangerous_requests: bool = False
123
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
124
+
125
+ *Security note*: Make sure that the database connection uses credentials
126
+ that are narrowly-scoped to only include necessary permissions.
127
+ Failure to do so may result in data corruption or loss, since the calling
128
+ code may attempt commands that would result in deletion, mutation
129
+ of data if appropriately prompted or reading sensitive data if such
130
+ data is present in the database.
131
+ The best way to guard against such negative outcomes is to (as appropriate)
132
+ limit the permissions granted to the credentials used with this tool.
133
+
134
+ See https://python.langchain.com/docs/security for more information.
135
+ """
136
+
137
+ def __init__(self, **kwargs: Any) -> None:
138
+ """Initialize the chain."""
139
+ super().__init__(**kwargs)
140
+ if self.allow_dangerous_requests is not True:
141
+ raise ValueError(
142
+ "In order to use this chain, you must acknowledge that it can make "
143
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
144
+ "You must narrowly scope the permissions of the database connection "
145
+ "to only include necessary permissions. Failure to do so may result "
146
+ "in data corruption or loss or reading sensitive data if such data is "
147
+ "present in the database."
148
+ "Only use this chain if you understand the risks and have taken the "
149
+ "necessary precautions. "
150
+ "See https://python.langchain.com/docs/security for more information."
151
+ )
152
+
153
+ @property
154
+ def input_keys(self) -> List[str]:
155
+ return [self.input_key]
156
+
157
+ @property
158
+ def output_keys(self) -> List[str]:
159
+ _output_keys = [self.output_key]
160
+ return _output_keys
161
+
162
+ @classmethod
163
+ def from_llm(
164
+ cls,
165
+ llm: BaseLanguageModel,
166
+ *,
167
+ qa_prompt: BasePromptTemplate = SPARQL_QA_PROMPT,
168
+ sparql_prompt: BasePromptTemplate = SPARQL_GENERATION_PROMPT,
169
+ examples: Optional[str] = None,
170
+ **kwargs: Any,
171
+ ) -> NeptuneSparqlQAChain:
172
+ """Initialize from LLM."""
173
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
174
+ template_to_use = SPARQL_GENERATION_TEMPLATE
175
+ if examples:
176
+ template_to_use = template_to_use.replace(
177
+ "Examples:", "Examples: " + examples
178
+ )
179
+ sparql_prompt = PromptTemplate(
180
+ input_variables=["schema", "prompt"], template=template_to_use
181
+ )
182
+ sparql_generation_chain = LLMChain(llm=llm, prompt=sparql_prompt)
183
+
184
+ return cls(
185
+ qa_chain=qa_chain,
186
+ sparql_generation_chain=sparql_generation_chain,
187
+ examples=examples,
188
+ **kwargs,
189
+ )
190
+
191
+ def _call(
192
+ self,
193
+ inputs: Dict[str, Any],
194
+ run_manager: Optional[CallbackManagerForChainRun] = None,
195
+ ) -> Dict[str, str]:
196
+ """
197
+ Generate SPARQL query, use it to retrieve a response from the gdb and answer
198
+ the question.
199
+ """
200
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
201
+ callbacks = _run_manager.get_child()
202
+ prompt = inputs[self.input_key]
203
+
204
+ intermediate_steps: List = []
205
+
206
+ generated_sparql = self.sparql_generation_chain.run(
207
+ {"prompt": prompt, "schema": self.graph.get_schema}, callbacks=callbacks
208
+ )
209
+
210
+ # Extract SPARQL
211
+ generated_sparql = extract_sparql(generated_sparql)
212
+
213
+ _run_manager.on_text("Generated SPARQL:", end="\n", verbose=self.verbose)
214
+ _run_manager.on_text(
215
+ generated_sparql, color="green", end="\n", verbose=self.verbose
216
+ )
217
+
218
+ intermediate_steps.append({"query": generated_sparql})
219
+
220
+ context = self.graph.query(generated_sparql)
221
+
222
+ if self.return_direct:
223
+ final_result = context
224
+ else:
225
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
226
+ _run_manager.on_text(
227
+ str(context), color="green", end="\n", verbose=self.verbose
228
+ )
229
+
230
+ intermediate_steps.append({"context": context})
231
+
232
+ result = self.qa_chain(
233
+ {"prompt": prompt, "context": context},
234
+ callbacks=callbacks,
235
+ )
236
+ final_result = result[self.qa_chain.output_key]
237
+
238
+ chain_result: Dict[str, Any] = {self.output_key: final_result}
239
+ if self.return_intermediate_steps:
240
+ chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps
241
+
242
+ return chain_result
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/ontotext_graphdb.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question answering over a graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional
6
+
7
+ if TYPE_CHECKING:
8
+ import rdflib
9
+
10
+ from langchain_classic.chains.base import Chain
11
+ from langchain_classic.chains.llm import LLMChain
12
+ from langchain_core.callbacks.manager import CallbackManager, CallbackManagerForChainRun
13
+ from langchain_core.language_models import BaseLanguageModel
14
+ from langchain_core.prompts.base import BasePromptTemplate
15
+ from pydantic import Field
16
+
17
+ from langchain_community.chains.graph_qa.prompts import (
18
+ GRAPHDB_QA_PROMPT,
19
+ GRAPHDB_SPARQL_FIX_PROMPT,
20
+ GRAPHDB_SPARQL_GENERATION_PROMPT,
21
+ )
22
+ from langchain_community.graphs import OntotextGraphDBGraph
23
+
24
+
25
+ class OntotextGraphDBQAChain(Chain):
26
+ """Question-answering against Ontotext GraphDB
27
+ https://graphdb.ontotext.com/ by generating SPARQL queries.
28
+
29
+ *Security note*: Make sure that the database connection uses credentials
30
+ that are narrowly-scoped to only include necessary permissions.
31
+ Failure to do so may result in data corruption or loss, since the calling
32
+ code may attempt commands that would result in deletion, mutation
33
+ of data if appropriately prompted or reading sensitive data if such
34
+ data is present in the database.
35
+ The best way to guard against such negative outcomes is to (as appropriate)
36
+ limit the permissions granted to the credentials used with this tool.
37
+
38
+ See https://python.langchain.com/docs/security for more information.
39
+ """
40
+
41
+ graph: OntotextGraphDBGraph = Field(exclude=True)
42
+ sparql_generation_chain: LLMChain
43
+ sparql_fix_chain: LLMChain
44
+ max_fix_retries: int
45
+ qa_chain: LLMChain
46
+ input_key: str = "query" #: :meta private:
47
+ output_key: str = "result" #: :meta private:
48
+
49
+ allow_dangerous_requests: bool = False
50
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
51
+
52
+ *Security note*: Make sure that the database connection uses credentials
53
+ that are narrowly-scoped to only include necessary permissions.
54
+ Failure to do so may result in data corruption or loss, since the calling
55
+ code may attempt commands that would result in deletion, mutation
56
+ of data if appropriately prompted or reading sensitive data if such
57
+ data is present in the database.
58
+ The best way to guard against such negative outcomes is to (as appropriate)
59
+ limit the permissions granted to the credentials used with this tool.
60
+
61
+ See https://python.langchain.com/docs/security for more information.
62
+ """
63
+
64
+ def __init__(self, **kwargs: Any) -> None:
65
+ """Initialize the chain."""
66
+ super().__init__(**kwargs)
67
+ if self.allow_dangerous_requests is not True:
68
+ raise ValueError(
69
+ "In order to use this chain, you must acknowledge that it can make "
70
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
71
+ "You must narrowly scope the permissions of the database connection "
72
+ "to only include necessary permissions. Failure to do so may result "
73
+ "in data corruption or loss or reading sensitive data if such data is "
74
+ "present in the database."
75
+ "Only use this chain if you understand the risks and have taken the "
76
+ "necessary precautions. "
77
+ "See https://python.langchain.com/docs/security for more information."
78
+ )
79
+
80
+ @property
81
+ def input_keys(self) -> List[str]:
82
+ return [self.input_key]
83
+
84
+ @property
85
+ def output_keys(self) -> List[str]:
86
+ _output_keys = [self.output_key]
87
+ return _output_keys
88
+
89
+ @classmethod
90
+ def from_llm(
91
+ cls,
92
+ llm: BaseLanguageModel,
93
+ *,
94
+ sparql_generation_prompt: BasePromptTemplate = GRAPHDB_SPARQL_GENERATION_PROMPT,
95
+ sparql_fix_prompt: BasePromptTemplate = GRAPHDB_SPARQL_FIX_PROMPT,
96
+ max_fix_retries: int = 5,
97
+ qa_prompt: BasePromptTemplate = GRAPHDB_QA_PROMPT,
98
+ **kwargs: Any,
99
+ ) -> OntotextGraphDBQAChain:
100
+ """Initialize from LLM."""
101
+ sparql_generation_chain = LLMChain(llm=llm, prompt=sparql_generation_prompt)
102
+ sparql_fix_chain = LLMChain(llm=llm, prompt=sparql_fix_prompt)
103
+ max_fix_retries = max_fix_retries
104
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
105
+ return cls(
106
+ qa_chain=qa_chain,
107
+ sparql_generation_chain=sparql_generation_chain,
108
+ sparql_fix_chain=sparql_fix_chain,
109
+ max_fix_retries=max_fix_retries,
110
+ **kwargs,
111
+ )
112
+
113
+ def _call(
114
+ self,
115
+ inputs: Dict[str, Any],
116
+ run_manager: Optional[CallbackManagerForChainRun] = None,
117
+ ) -> Dict[str, str]:
118
+ """
119
+ Generate a SPARQL query, use it to retrieve a response from GraphDB and answer
120
+ the question.
121
+ """
122
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
123
+ callbacks = _run_manager.get_child()
124
+ prompt = inputs[self.input_key]
125
+ ontology_schema = self.graph.get_schema
126
+
127
+ sparql_generation_chain_result = self.sparql_generation_chain.invoke(
128
+ {"prompt": prompt, "schema": ontology_schema}, callbacks=callbacks
129
+ )
130
+ generated_sparql = sparql_generation_chain_result[
131
+ self.sparql_generation_chain.output_key
132
+ ]
133
+
134
+ generated_sparql = self._get_prepared_sparql_query(
135
+ _run_manager, callbacks, generated_sparql, ontology_schema
136
+ )
137
+ query_results = self._execute_query(generated_sparql)
138
+
139
+ qa_chain_result = self.qa_chain.invoke(
140
+ {"prompt": prompt, "context": query_results}, callbacks=callbacks
141
+ )
142
+ result = qa_chain_result[self.qa_chain.output_key]
143
+ return {self.output_key: result}
144
+
145
+ def _get_prepared_sparql_query(
146
+ self,
147
+ _run_manager: CallbackManagerForChainRun,
148
+ callbacks: CallbackManager,
149
+ generated_sparql: str,
150
+ ontology_schema: str,
151
+ ) -> str:
152
+ try:
153
+ return self._prepare_sparql_query(_run_manager, generated_sparql)
154
+ except Exception as e:
155
+ retries = 0
156
+ error_message = str(e)
157
+ self._log_invalid_sparql_query(
158
+ _run_manager, generated_sparql, error_message
159
+ )
160
+
161
+ while retries < self.max_fix_retries:
162
+ try:
163
+ sparql_fix_chain_result = self.sparql_fix_chain.invoke(
164
+ {
165
+ "error_message": error_message,
166
+ "generated_sparql": generated_sparql,
167
+ "schema": ontology_schema,
168
+ },
169
+ callbacks=callbacks,
170
+ )
171
+ generated_sparql = sparql_fix_chain_result[
172
+ self.sparql_fix_chain.output_key
173
+ ]
174
+ return self._prepare_sparql_query(_run_manager, generated_sparql)
175
+ except Exception as e:
176
+ retries += 1
177
+ parse_exception = str(e)
178
+ self._log_invalid_sparql_query(
179
+ _run_manager, generated_sparql, parse_exception
180
+ )
181
+
182
+ raise ValueError("The generated SPARQL query is invalid.")
183
+
184
+ def _prepare_sparql_query(
185
+ self, _run_manager: CallbackManagerForChainRun, generated_sparql: str
186
+ ) -> str:
187
+ from rdflib.plugins.sparql import prepareQuery
188
+
189
+ prepareQuery(generated_sparql)
190
+ self._log_prepared_sparql_query(_run_manager, generated_sparql)
191
+ return generated_sparql
192
+
193
+ def _log_prepared_sparql_query(
194
+ self, _run_manager: CallbackManagerForChainRun, generated_query: str
195
+ ) -> None:
196
+ _run_manager.on_text("Generated SPARQL:", end="\n", verbose=self.verbose)
197
+ _run_manager.on_text(
198
+ generated_query, color="green", end="\n", verbose=self.verbose
199
+ )
200
+
201
+ def _log_invalid_sparql_query(
202
+ self,
203
+ _run_manager: CallbackManagerForChainRun,
204
+ generated_query: str,
205
+ error_message: str,
206
+ ) -> None:
207
+ _run_manager.on_text("Invalid SPARQL query: ", end="\n", verbose=self.verbose)
208
+ _run_manager.on_text(
209
+ generated_query, color="red", end="\n", verbose=self.verbose
210
+ )
211
+ _run_manager.on_text(
212
+ "SPARQL Query Parse Error: ", end="\n", verbose=self.verbose
213
+ )
214
+ _run_manager.on_text(
215
+ error_message, color="red", end="\n\n", verbose=self.verbose
216
+ )
217
+
218
+ def _execute_query(self, query: str) -> List[rdflib.query.ResultRow]:
219
+ try:
220
+ return self.graph.query(query)
221
+ except Exception:
222
+ raise ValueError("Failed to execute the generated SPARQL query.")
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/prompts.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+ from langchain_core.prompts.prompt import PromptTemplate
3
+
4
+ _DEFAULT_ENTITY_EXTRACTION_TEMPLATE = """Extract all entities from the following text. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.
5
+
6
+ Return the output as a single comma-separated list, or NONE if there is nothing of note to return.
7
+
8
+ EXAMPLE
9
+ i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.
10
+ Output: Langchain
11
+ END OF EXAMPLE
12
+
13
+ EXAMPLE
14
+ i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Sam.
15
+ Output: Langchain, Sam
16
+ END OF EXAMPLE
17
+
18
+ Begin!
19
+
20
+ {input}
21
+ Output:"""
22
+ ENTITY_EXTRACTION_PROMPT = PromptTemplate(
23
+ input_variables=["input"], template=_DEFAULT_ENTITY_EXTRACTION_TEMPLATE
24
+ )
25
+
26
+ _DEFAULT_GRAPH_QA_TEMPLATE = """Use the following knowledge triplets to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.
27
+
28
+ {context}
29
+
30
+ Question: {question}
31
+ Helpful Answer:"""
32
+ GRAPH_QA_PROMPT = PromptTemplate(
33
+ template=_DEFAULT_GRAPH_QA_TEMPLATE, input_variables=["context", "question"]
34
+ )
35
+
36
+ CYPHER_GENERATION_TEMPLATE = """Task:Generate Cypher statement to query a graph database.
37
+ Instructions:
38
+ Use only the provided relationship types and properties in the schema.
39
+ Do not use any other relationship types or properties that are not provided.
40
+ Schema:
41
+ {schema}
42
+ Note: Do not include any explanations or apologies in your responses.
43
+ Do not respond to any questions that might ask anything else than for you to construct a Cypher statement.
44
+ Do not include any text except the generated Cypher statement.
45
+
46
+ The question is:
47
+ {question}"""
48
+ CYPHER_GENERATION_PROMPT = PromptTemplate(
49
+ input_variables=["schema", "question"], template=CYPHER_GENERATION_TEMPLATE
50
+ )
51
+
52
+ NEBULAGRAPH_EXTRA_INSTRUCTIONS = """
53
+ Instructions:
54
+
55
+ First, generate cypher then convert it to NebulaGraph Cypher dialect(rather than standard):
56
+ 1. it requires explicit label specification only when referring to node properties: v.`Foo`.name
57
+ 2. note explicit label specification is not needed for edge properties, so it's e.name instead of e.`Bar`.name
58
+ 3. it uses double equals sign for comparison: `==` rather than `=`
59
+ For instance:
60
+ ```diff
61
+ < MATCH (p:person)-[e:directed]->(m:movie) WHERE m.name = 'The Godfather II'
62
+ < RETURN p.name, e.year, m.name;
63
+ ---
64
+ > MATCH (p:`person`)-[e:directed]->(m:`movie`) WHERE m.`movie`.`name` == 'The Godfather II'
65
+ > RETURN p.`person`.`name`, e.year, m.`movie`.`name`;
66
+ ```\n"""
67
+
68
+ NGQL_GENERATION_TEMPLATE = CYPHER_GENERATION_TEMPLATE.replace(
69
+ "Generate Cypher", "Generate NebulaGraph Cypher"
70
+ ).replace("Instructions:", NEBULAGRAPH_EXTRA_INSTRUCTIONS)
71
+
72
+ NGQL_GENERATION_PROMPT = PromptTemplate(
73
+ input_variables=["schema", "question"], template=NGQL_GENERATION_TEMPLATE
74
+ )
75
+
76
+ KUZU_EXTRA_INSTRUCTIONS = """
77
+ Instructions:
78
+ Generate the Kùzu dialect of Cypher with the following rules in mind:
79
+ 1. Do not omit the relationship pattern. Always use `()-[]->()` instead of `()->()`.
80
+ 2. Do not include triple backticks ``` in your response. Return only Cypher.
81
+ 3. Do not return any notes or comments in your response.
82
+ \n"""
83
+
84
+ KUZU_GENERATION_TEMPLATE = CYPHER_GENERATION_TEMPLATE.replace(
85
+ "Generate Cypher", "Generate Kùzu Cypher"
86
+ ).replace("Instructions:", KUZU_EXTRA_INSTRUCTIONS)
87
+
88
+ KUZU_GENERATION_PROMPT = PromptTemplate(
89
+ input_variables=["schema", "question"], template=KUZU_GENERATION_TEMPLATE
90
+ )
91
+
92
+ GREMLIN_GENERATION_TEMPLATE = CYPHER_GENERATION_TEMPLATE.replace("Cypher", "Gremlin")
93
+
94
+ GREMLIN_GENERATION_PROMPT = PromptTemplate(
95
+ input_variables=["schema", "question"], template=GREMLIN_GENERATION_TEMPLATE
96
+ )
97
+
98
+ CYPHER_QA_TEMPLATE = """You are an assistant that helps to form nice and human understandable answers.
99
+ The information part contains the provided information that you must use to construct an answer.
100
+ The provided information is authoritative, you must never doubt it or try to use your internal knowledge to correct it.
101
+ Make the answer sound as a response to the question. Do not mention that you based the result on the given information.
102
+ Here is an example:
103
+
104
+ Question: Which managers own Neo4j stocks?
105
+ Context:[manager:CTL LLC, manager:JANE STREET GROUP LLC]
106
+ Helpful Answer: CTL LLC, JANE STREET GROUP LLC owns Neo4j stocks.
107
+
108
+ Follow this example when generating answers.
109
+ If the provided information is empty, say that you don't know the answer.
110
+ Information:
111
+ {context}
112
+
113
+ Question: {question}
114
+ Helpful Answer:"""
115
+ CYPHER_QA_PROMPT = PromptTemplate(
116
+ input_variables=["context", "question"], template=CYPHER_QA_TEMPLATE
117
+ )
118
+
119
+ SPARQL_INTENT_TEMPLATE = """Task: Identify the intent of a prompt and return the appropriate SPARQL query type.
120
+ You are an assistant that distinguishes different types of prompts and returns the corresponding SPARQL query types.
121
+ Consider only the following query types:
122
+ * SELECT: this query type corresponds to questions
123
+ * UPDATE: this query type corresponds to all requests for deleting, inserting, or changing triples
124
+ Note: Be as concise as possible.
125
+ Do not include any explanations or apologies in your responses.
126
+ Do not respond to any questions that ask for anything else than for you to identify a SPARQL query type.
127
+ Do not include any unnecessary whitespaces or any text except the query type, i.e., either return 'SELECT' or 'UPDATE'.
128
+
129
+ The prompt is:
130
+ {prompt}
131
+ Helpful Answer:"""
132
+ SPARQL_INTENT_PROMPT = PromptTemplate(
133
+ input_variables=["prompt"], template=SPARQL_INTENT_TEMPLATE
134
+ )
135
+
136
+ SPARQL_GENERATION_SELECT_TEMPLATE = """Task: Generate a SPARQL SELECT statement for querying a graph database.
137
+ For instance, to find all email addresses of John Doe, the following query in backticks would be suitable:
138
+ ```
139
+ PREFIX foaf: <http://xmlns.com/foaf/0.1/>
140
+ SELECT ?email
141
+ WHERE {{
142
+ ?person foaf:name "John Doe" .
143
+ ?person foaf:mbox ?email .
144
+ }}
145
+ ```
146
+ Instructions:
147
+ Use only the node types and properties provided in the schema.
148
+ Do not use any node types and properties that are not explicitly provided.
149
+ Include all necessary prefixes.
150
+ Schema:
151
+ {schema}
152
+ Note: Be as concise as possible.
153
+ Do not include any explanations or apologies in your responses.
154
+ Do not respond to any questions that ask for anything else than for you to construct a SPARQL query.
155
+ Do not include any text except the SPARQL query generated.
156
+
157
+ The question is:
158
+ {prompt}"""
159
+ SPARQL_GENERATION_SELECT_PROMPT = PromptTemplate(
160
+ input_variables=["schema", "prompt"], template=SPARQL_GENERATION_SELECT_TEMPLATE
161
+ )
162
+
163
+ SPARQL_GENERATION_UPDATE_TEMPLATE = """Task: Generate a SPARQL UPDATE statement for updating a graph database.
164
+ For instance, to add 'jane.doe@foo.bar' as a new email address for Jane Doe, the following query in backticks would be suitable:
165
+ ```
166
+ PREFIX foaf: <http://xmlns.com/foaf/0.1/>
167
+ INSERT {{
168
+ ?person foaf:mbox <mailto:jane.doe@foo.bar> .
169
+ }}
170
+ WHERE {{
171
+ ?person foaf:name "Jane Doe" .
172
+ }}
173
+ ```
174
+ Instructions:
175
+ Make the query as short as possible and avoid adding unnecessary triples.
176
+ Use only the node types and properties provided in the schema.
177
+ Do not use any node types and properties that are not explicitly provided.
178
+ Include all necessary prefixes.
179
+ Schema:
180
+ {schema}
181
+ Note: Be as concise as possible.
182
+ Do not include any explanations or apologies in your responses.
183
+ Do not respond to any questions that ask for anything else than for you to construct a SPARQL query.
184
+ Return only the generated SPARQL query, nothing else.
185
+
186
+ The information to be inserted is:
187
+ {prompt}"""
188
+ SPARQL_GENERATION_UPDATE_PROMPT = PromptTemplate(
189
+ input_variables=["schema", "prompt"], template=SPARQL_GENERATION_UPDATE_TEMPLATE
190
+ )
191
+
192
+ SPARQL_QA_TEMPLATE = """Task: Generate a natural language response from the results of a SPARQL query.
193
+ You are an assistant that creates well-written and human understandable answers.
194
+ The information part contains the information provided, which you can use to construct an answer.
195
+ The information provided is authoritative, you must never doubt it or try to use your internal knowledge to correct it.
196
+ Make your response sound like the information is coming from an AI assistant, but don't add any information.
197
+ Information:
198
+ {context}
199
+
200
+ Question: {prompt}
201
+ Helpful Answer:"""
202
+ SPARQL_QA_PROMPT = PromptTemplate(
203
+ input_variables=["context", "prompt"], template=SPARQL_QA_TEMPLATE
204
+ )
205
+
206
+ GRAPHDB_SPARQL_GENERATION_TEMPLATE = """
207
+ Write a SPARQL SELECT query for querying a graph database.
208
+ The ontology schema delimited by triple backticks in Turtle format is:
209
+ ```
210
+ {schema}
211
+ ```
212
+ Use only the classes and properties provided in the schema to construct the SPARQL query.
213
+ Do not use any classes or properties that are not explicitly provided in the SPARQL query.
214
+ Include all necessary prefixes.
215
+ Do not include any explanations or apologies in your responses.
216
+ Do not wrap the query in backticks.
217
+ Do not include any text except the SPARQL query generated.
218
+ The question delimited by triple backticks is:
219
+ ```
220
+ {prompt}
221
+ ```
222
+ """
223
+ GRAPHDB_SPARQL_GENERATION_PROMPT = PromptTemplate(
224
+ input_variables=["schema", "prompt"],
225
+ template=GRAPHDB_SPARQL_GENERATION_TEMPLATE,
226
+ )
227
+
228
+ GRAPHDB_SPARQL_FIX_TEMPLATE = """
229
+ This following SPARQL query delimited by triple backticks
230
+ ```
231
+ {generated_sparql}
232
+ ```
233
+ is not valid.
234
+ The error delimited by triple backticks is
235
+ ```
236
+ {error_message}
237
+ ```
238
+ Give me a correct version of the SPARQL query.
239
+ Do not change the logic of the query.
240
+ Do not include any explanations or apologies in your responses.
241
+ Do not wrap the query in backticks.
242
+ Do not include any text except the SPARQL query generated.
243
+ The ontology schema delimited by triple backticks in Turtle format is:
244
+ ```
245
+ {schema}
246
+ ```
247
+ """
248
+
249
+ GRAPHDB_SPARQL_FIX_PROMPT = PromptTemplate(
250
+ input_variables=["error_message", "generated_sparql", "schema"],
251
+ template=GRAPHDB_SPARQL_FIX_TEMPLATE,
252
+ )
253
+
254
+ GRAPHDB_QA_TEMPLATE = """Task: Generate a natural language response from the results of a SPARQL query.
255
+ You are an assistant that creates well-written and human understandable answers.
256
+ The information part contains the information provided, which you can use to construct an answer.
257
+ The information provided is authoritative, you must never doubt it or try to use your internal knowledge to correct it.
258
+ Make your response sound like the information is coming from an AI assistant, but don't add any information.
259
+ Don't use internal knowledge to answer the question, just say you don't know if no information is available.
260
+ Information:
261
+ {context}
262
+
263
+ Question: {prompt}
264
+ Helpful Answer:"""
265
+ GRAPHDB_QA_PROMPT = PromptTemplate(
266
+ input_variables=["context", "prompt"], template=GRAPHDB_QA_TEMPLATE
267
+ )
268
+
269
+ AQL_GENERATION_TEMPLATE = """Task: Generate an ArangoDB Query Language (AQL) query from a User Input.
270
+
271
+ You are an ArangoDB Query Language (AQL) expert responsible for translating a `User Input` into an ArangoDB Query Language (AQL) query.
272
+
273
+ You are given an `ArangoDB Schema`. It is a JSON Object containing:
274
+ 1. `Graph Schema`: Lists all Graphs within the ArangoDB Database Instance, along with their Edge Relationships.
275
+ 2. `Collection Schema`: Lists all Collections within the ArangoDB Database Instance, along with their document/edge properties and a document/edge example.
276
+
277
+ You may also be given a set of `AQL Query Examples` to help you create the `AQL Query`. If provided, the `AQL Query Examples` should be used as a reference, similar to how `ArangoDB Schema` should be used.
278
+
279
+ Things you should do:
280
+ - Think step by step.
281
+ - Rely on `ArangoDB Schema` and `AQL Query Examples` (if provided) to generate the query.
282
+ - Begin the `AQL Query` by the `WITH` AQL keyword to specify all of the ArangoDB Collections required.
283
+ - Return the `AQL Query` wrapped in 3 backticks (```).
284
+ - Use only the provided relationship types and properties in the `ArangoDB Schema` and any `AQL Query Examples` queries.
285
+ - Only answer to requests related to generating an AQL Query.
286
+ - If a request is unrelated to generating AQL Query, say that you cannot help the user.
287
+
288
+ Things you should not do:
289
+ - Do not use any properties/relationships that can't be inferred from the `ArangoDB Schema` or the `AQL Query Examples`.
290
+ - Do not include any text except the generated AQL Query.
291
+ - Do not provide explanations or apologies in your responses.
292
+ - Do not generate an AQL Query that removes or deletes any data.
293
+
294
+ Under no circumstance should you generate an AQL Query that deletes any data whatsoever.
295
+
296
+ ArangoDB Schema:
297
+ {adb_schema}
298
+
299
+ AQL Query Examples (Optional):
300
+ {aql_examples}
301
+
302
+ User Input:
303
+ {user_input}
304
+
305
+ AQL Query:
306
+ """
307
+
308
+ AQL_GENERATION_PROMPT = PromptTemplate(
309
+ input_variables=["adb_schema", "aql_examples", "user_input"],
310
+ template=AQL_GENERATION_TEMPLATE,
311
+ )
312
+
313
+ AQL_FIX_TEMPLATE = """Task: Address the ArangoDB Query Language (AQL) error message of an ArangoDB Query Language query.
314
+
315
+ You are an ArangoDB Query Language (AQL) expert responsible for correcting the provided `AQL Query` based on the provided `AQL Error`.
316
+
317
+ The `AQL Error` explains why the `AQL Query` could not be executed in the database.
318
+ The `AQL Error` may also contain the position of the error relative to the total number of lines of the `AQL Query`.
319
+ For example, 'error X at position 2:5' denotes that the error X occurs on line 2, column 5 of the `AQL Query`.
320
+
321
+ You are also given the `ArangoDB Schema`. It is a JSON Object containing:
322
+ 1. `Graph Schema`: Lists all Graphs within the ArangoDB Database Instance, along with their Edge Relationships.
323
+ 2. `Collection Schema`: Lists all Collections within the ArangoDB Database Instance, along with their document/edge properties and a document/edge example.
324
+
325
+ You will output the `Corrected AQL Query` wrapped in 3 backticks (```). Do not include any text except the Corrected AQL Query.
326
+
327
+ Remember to think step by step.
328
+
329
+ ArangoDB Schema:
330
+ {adb_schema}
331
+
332
+ AQL Query:
333
+ {aql_query}
334
+
335
+ AQL Error:
336
+ {aql_error}
337
+
338
+ Corrected AQL Query:
339
+ """
340
+
341
+ AQL_FIX_PROMPT = PromptTemplate(
342
+ input_variables=[
343
+ "adb_schema",
344
+ "aql_query",
345
+ "aql_error",
346
+ ],
347
+ template=AQL_FIX_TEMPLATE,
348
+ )
349
+
350
+ AQL_QA_TEMPLATE = """Task: Generate a natural language `Summary` from the results of an ArangoDB Query Language query.
351
+
352
+ You are an ArangoDB Query Language (AQL) expert responsible for creating a well-written `Summary` from the `User Input` and associated `AQL Result`.
353
+
354
+ A user has executed an ArangoDB Query Language query, which has returned the AQL Result in JSON format.
355
+ You are responsible for creating an `Summary` based on the AQL Result.
356
+
357
+ You are given the following information:
358
+ - `ArangoDB Schema`: contains a schema representation of the user's ArangoDB Database.
359
+ - `User Input`: the original question/request of the user, which has been translated into an AQL Query.
360
+ - `AQL Query`: the AQL equivalent of the `User Input`, translated by another AI Model. Should you deem it to be incorrect, suggest a different AQL Query.
361
+ - `AQL Result`: the JSON output returned by executing the `AQL Query` within the ArangoDB Database.
362
+
363
+ Remember to think step by step.
364
+
365
+ Your `Summary` should sound like it is a response to the `User Input`.
366
+ Your `Summary` should not include any mention of the `AQL Query` or the `AQL Result`.
367
+
368
+ ArangoDB Schema:
369
+ {adb_schema}
370
+
371
+ User Input:
372
+ {user_input}
373
+
374
+ AQL Query:
375
+ {aql_query}
376
+
377
+ AQL Result:
378
+ {aql_result}
379
+ """
380
+ AQL_QA_PROMPT = PromptTemplate(
381
+ input_variables=["adb_schema", "user_input", "aql_query", "aql_result"],
382
+ template=AQL_QA_TEMPLATE,
383
+ )
384
+
385
+
386
+ NEPTUNE_OPENCYPHER_EXTRA_INSTRUCTIONS = """
387
+ Instructions:
388
+ Generate the query in openCypher format and follow these rules:
389
+ Do not use `NONE`, `ALL` or `ANY` predicate functions, rather use list comprehensions.
390
+ Do not use `REDUCE` function. Rather use a combination of list comprehension and the `UNWIND` clause to achieve similar results.
391
+ Do not use `FOREACH` clause. Rather use a combination of `WITH` and `UNWIND` clauses to achieve similar results.{extra_instructions}
392
+ \n"""
393
+
394
+ NEPTUNE_OPENCYPHER_GENERATION_TEMPLATE = CYPHER_GENERATION_TEMPLATE.replace(
395
+ "Instructions:", NEPTUNE_OPENCYPHER_EXTRA_INSTRUCTIONS
396
+ )
397
+
398
+ NEPTUNE_OPENCYPHER_GENERATION_PROMPT = PromptTemplate(
399
+ input_variables=["schema", "question", "extra_instructions"],
400
+ template=NEPTUNE_OPENCYPHER_GENERATION_TEMPLATE,
401
+ )
402
+
403
+ NEPTUNE_OPENCYPHER_GENERATION_SIMPLE_TEMPLATE = """
404
+ Write an openCypher query to answer the following question. Do not explain the answer. Only return the query.{extra_instructions}
405
+ Question: "{question}".
406
+ Here is the property graph schema:
407
+ {schema}
408
+ \n"""
409
+
410
+ NEPTUNE_OPENCYPHER_GENERATION_SIMPLE_PROMPT = PromptTemplate(
411
+ input_variables=["schema", "question", "extra_instructions"],
412
+ template=NEPTUNE_OPENCYPHER_GENERATION_SIMPLE_TEMPLATE,
413
+ )
414
+
415
+ MEMGRAPH_GENERATION_TEMPLATE = """Your task is to directly translate natural language inquiry into precise and executable Cypher query for Memgraph database.
416
+ You will utilize a provided database schema to understand the structure, nodes and relationships within the Memgraph database.
417
+ Instructions:
418
+ - Use provided node and relationship labels and property names from the
419
+ schema which describes the database's structure. Upon receiving a user
420
+ question, synthesize the schema to craft a precise Cypher query that
421
+ directly corresponds to the user's intent.
422
+ - Generate valid executable Cypher queries on top of Memgraph database.
423
+ Any explanation, context, or additional information that is not a part
424
+ of the Cypher query syntax should be omitted entirely.
425
+ - Use Memgraph MAGE procedures instead of Neo4j APOC procedures.
426
+ - Do not include any explanations or apologies in your responses.
427
+ - Do not include any text except the generated Cypher statement.
428
+ - For queries that ask for information or functionalities outside the direct
429
+ generation of Cypher queries, use the Cypher query format to communicate
430
+ limitations or capabilities. For example: RETURN "I am designed to generate
431
+ Cypher queries based on the provided schema only."
432
+ Schema:
433
+ {schema}
434
+
435
+ With all the above information and instructions, generate Cypher query for the
436
+ user question.
437
+
438
+ The question is:
439
+ {question}"""
440
+
441
+ MEMGRAPH_GENERATION_PROMPT = PromptTemplate(
442
+ input_variables=["schema", "question"], template=MEMGRAPH_GENERATION_TEMPLATE
443
+ )
444
+
445
+
446
+ MEMGRAPH_QA_TEMPLATE = """Your task is to form nice and human
447
+ understandable answers. The information part contains the provided
448
+ information that you must use to construct an answer.
449
+ The provided information is authoritative, you must never doubt it or try to
450
+ use your internal knowledge to correct it. Make the answer sound as a
451
+ response to the question. Do not mention that you based the result on the
452
+ given information. Here is an example:
453
+
454
+ Question: Which managers own Neo4j stocks?
455
+ Context:[manager:CTL LLC, manager:JANE STREET GROUP LLC]
456
+ Helpful Answer: CTL LLC, JANE STREET GROUP LLC owns Neo4j stocks.
457
+
458
+ Follow this example when generating answers. If the provided information is
459
+ empty, say that you don't know the answer.
460
+
461
+ Information:
462
+ {context}
463
+
464
+ Question: {question}
465
+ Helpful Answer:"""
466
+ MEMGRAPH_QA_PROMPT = PromptTemplate(
467
+ input_variables=["context", "question"], template=MEMGRAPH_QA_TEMPLATE
468
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/graph_qa/sparql.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Question answering over an RDF or OWL graph using SPARQL.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ from langchain_classic.chains.base import Chain
10
+ from langchain_classic.chains.llm import LLMChain
11
+ from langchain_core.callbacks import CallbackManagerForChainRun
12
+ from langchain_core.language_models import BaseLanguageModel
13
+ from langchain_core.prompts.base import BasePromptTemplate
14
+ from pydantic import Field
15
+
16
+ from langchain_community.chains.graph_qa.prompts import (
17
+ SPARQL_GENERATION_SELECT_PROMPT,
18
+ SPARQL_GENERATION_UPDATE_PROMPT,
19
+ SPARQL_INTENT_PROMPT,
20
+ SPARQL_QA_PROMPT,
21
+ )
22
+ from langchain_community.graphs.rdf_graph import RdfGraph
23
+
24
+
25
+ class GraphSparqlQAChain(Chain):
26
+ """Question-answering against an RDF or OWL graph by generating SPARQL statements.
27
+
28
+ *Security note*: Make sure that the database connection uses credentials
29
+ that are narrowly-scoped to only include necessary permissions.
30
+ Failure to do so may result in data corruption or loss, since the calling
31
+ code may attempt commands that would result in deletion, mutation
32
+ of data if appropriately prompted or reading sensitive data if such
33
+ data is present in the database.
34
+ The best way to guard against such negative outcomes is to (as appropriate)
35
+ limit the permissions granted to the credentials used with this tool.
36
+
37
+ See https://python.langchain.com/docs/security for more information.
38
+ """
39
+
40
+ graph: RdfGraph = Field(exclude=True)
41
+ sparql_generation_select_chain: LLMChain
42
+ sparql_generation_update_chain: LLMChain
43
+ sparql_intent_chain: LLMChain
44
+ qa_chain: LLMChain
45
+ return_sparql_query: bool = False
46
+ input_key: str = "query" #: :meta private:
47
+ output_key: str = "result" #: :meta private:
48
+ sparql_query_key: str = "sparql_query" #: :meta private:
49
+
50
+ allow_dangerous_requests: bool = False
51
+ """Forced user opt-in to acknowledge that the chain can make dangerous requests.
52
+
53
+ *Security note*: Make sure that the database connection uses credentials
54
+ that are narrowly-scoped to only include necessary permissions.
55
+ Failure to do so may result in data corruption or loss, since the calling
56
+ code may attempt commands that would result in deletion, mutation
57
+ of data if appropriately prompted or reading sensitive data if such
58
+ data is present in the database.
59
+ The best way to guard against such negative outcomes is to (as appropriate)
60
+ limit the permissions granted to the credentials used with this tool.
61
+
62
+ See https://python.langchain.com/docs/security for more information.
63
+ """
64
+
65
+ def __init__(self, **kwargs: Any) -> None:
66
+ """Initialize the chain."""
67
+ super().__init__(**kwargs)
68
+ if self.allow_dangerous_requests is not True:
69
+ raise ValueError(
70
+ "In order to use this chain, you must acknowledge that it can make "
71
+ "dangerous requests by setting `allow_dangerous_requests` to `True`."
72
+ "You must narrowly scope the permissions of the database connection "
73
+ "to only include necessary permissions. Failure to do so may result "
74
+ "in data corruption or loss or reading sensitive data if such data is "
75
+ "present in the database."
76
+ "Only use this chain if you understand the risks and have taken the "
77
+ "necessary precautions. "
78
+ "See https://python.langchain.com/docs/security for more information."
79
+ )
80
+
81
+ @property
82
+ def input_keys(self) -> List[str]:
83
+ """Return the input keys.
84
+
85
+ :meta private:
86
+ """
87
+ return [self.input_key]
88
+
89
+ @property
90
+ def output_keys(self) -> List[str]:
91
+ """Return the output keys.
92
+
93
+ :meta private:
94
+ """
95
+ _output_keys = [self.output_key]
96
+ return _output_keys
97
+
98
+ @classmethod
99
+ def from_llm(
100
+ cls,
101
+ llm: BaseLanguageModel,
102
+ *,
103
+ qa_prompt: BasePromptTemplate = SPARQL_QA_PROMPT,
104
+ sparql_select_prompt: BasePromptTemplate = SPARQL_GENERATION_SELECT_PROMPT,
105
+ sparql_update_prompt: BasePromptTemplate = SPARQL_GENERATION_UPDATE_PROMPT,
106
+ sparql_intent_prompt: BasePromptTemplate = SPARQL_INTENT_PROMPT,
107
+ **kwargs: Any,
108
+ ) -> GraphSparqlQAChain:
109
+ """Initialize from LLM."""
110
+ qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
111
+ sparql_generation_select_chain = LLMChain(llm=llm, prompt=sparql_select_prompt)
112
+ sparql_generation_update_chain = LLMChain(llm=llm, prompt=sparql_update_prompt)
113
+ sparql_intent_chain = LLMChain(llm=llm, prompt=sparql_intent_prompt)
114
+
115
+ return cls(
116
+ qa_chain=qa_chain,
117
+ sparql_generation_select_chain=sparql_generation_select_chain,
118
+ sparql_generation_update_chain=sparql_generation_update_chain,
119
+ sparql_intent_chain=sparql_intent_chain,
120
+ **kwargs,
121
+ )
122
+
123
+ def _call(
124
+ self,
125
+ inputs: Dict[str, Any],
126
+ run_manager: Optional[CallbackManagerForChainRun] = None,
127
+ ) -> Dict[str, str]:
128
+ """
129
+ Generate SPARQL query, use it to retrieve a response from the gdb and answer
130
+ the question.
131
+ """
132
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
133
+ callbacks = _run_manager.get_child()
134
+ prompt = inputs[self.input_key]
135
+
136
+ _intent = self.sparql_intent_chain.run({"prompt": prompt}, callbacks=callbacks)
137
+ intent = _intent.strip()
138
+
139
+ if "SELECT" in intent and "UPDATE" not in intent:
140
+ sparql_generation_chain = self.sparql_generation_select_chain
141
+ intent = "SELECT"
142
+ elif "UPDATE" in intent and "SELECT" not in intent:
143
+ sparql_generation_chain = self.sparql_generation_update_chain
144
+ intent = "UPDATE"
145
+ else:
146
+ raise ValueError(
147
+ "I am sorry, but this prompt seems to fit none of the currently "
148
+ "supported SPARQL query types, i.e., SELECT and UPDATE."
149
+ )
150
+
151
+ _run_manager.on_text("Identified intent:", end="\n", verbose=self.verbose)
152
+ _run_manager.on_text(intent, color="green", end="\n", verbose=self.verbose)
153
+
154
+ generated_sparql = sparql_generation_chain.run(
155
+ {"prompt": prompt, "schema": self.graph.get_schema}, callbacks=callbacks
156
+ )
157
+
158
+ _run_manager.on_text("Generated SPARQL:", end="\n", verbose=self.verbose)
159
+ _run_manager.on_text(
160
+ generated_sparql, color="green", end="\n", verbose=self.verbose
161
+ )
162
+
163
+ if intent == "SELECT":
164
+ context = self.graph.query(generated_sparql)
165
+
166
+ _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)
167
+ _run_manager.on_text(
168
+ str(context), color="green", end="\n", verbose=self.verbose
169
+ )
170
+ result = self.qa_chain(
171
+ {"prompt": prompt, "context": context},
172
+ callbacks=callbacks,
173
+ )
174
+ res = result[self.qa_chain.output_key]
175
+ elif intent == "UPDATE":
176
+ self.graph.update(generated_sparql)
177
+ res = "Successfully inserted triples into the graph."
178
+ else:
179
+ raise ValueError("Unsupported SPARQL query type.")
180
+
181
+ chain_result: Dict[str, Any] = {self.output_key: res}
182
+ if self.return_sparql_query:
183
+ chain_result[self.sparql_query_key] = generated_sparql
184
+ return chain_result
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/natbot/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Implement a GPT-3 driven browser.
2
+
3
+ Heavily influenced from https://github.com/nat/natbot
4
+ """
5
+
6
+ from langchain_community.chains.natbot.base import NatBotChain
7
+
8
+ __all__ = ["NatBotChain"]
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/natbot/base.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from langchain_classic.chains import NatBotChain
2
+
3
+ __all__ = ["NatBotChain"]
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/natbot/crawler.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from langchain_classic.chains.natbot.crawler import (
2
+ Crawler,
3
+ ElementInViewPort,
4
+ black_listed_elements,
5
+ )
6
+
7
+ __all__ = ["ElementInViewPort", "Crawler", "black_listed_elements"]
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/natbot/prompt.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from langchain_classic.chains.natbot.prompt import PROMPT
2
+
3
+ __all__ = ["PROMPT"]
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/__init__.py ADDED
File without changes
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/chain.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chain that makes API calls and summarizes the responses to answer a question."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Dict, List, NamedTuple, Optional, cast
7
+
8
+ from langchain_classic.chains.api.openapi.requests_chain import APIRequesterChain
9
+ from langchain_classic.chains.api.openapi.response_chain import APIResponderChain
10
+ from langchain_classic.chains.base import Chain
11
+ from langchain_classic.chains.llm import LLMChain
12
+ from langchain_core.callbacks import CallbackManagerForChainRun, Callbacks
13
+ from langchain_core.language_models import BaseLanguageModel
14
+ from pydantic import BaseModel, Field
15
+ from requests import Response
16
+
17
+ from langchain_community.tools.openapi.utils.api_models import APIOperation
18
+ from langchain_community.utilities.requests import Requests
19
+
20
+
21
+ class _ParamMapping(NamedTuple):
22
+ """Mapping from parameter name to parameter value."""
23
+
24
+ query_params: List[str]
25
+ body_params: List[str]
26
+ path_params: List[str]
27
+
28
+
29
+ class OpenAPIEndpointChain(Chain, BaseModel):
30
+ """Chain interacts with an OpenAPI endpoint using natural language."""
31
+
32
+ api_request_chain: LLMChain
33
+ api_response_chain: Optional[LLMChain] = None
34
+ api_operation: APIOperation
35
+ requests: Requests = Field(exclude=True, default_factory=Requests)
36
+ param_mapping: _ParamMapping = Field(alias="param_mapping")
37
+ return_intermediate_steps: bool = False
38
+ instructions_key: str = "instructions" #: :meta private:
39
+ output_key: str = "output" #: :meta private:
40
+ max_text_length: Optional[int] = Field(ge=0) #: :meta private:
41
+
42
+ @property
43
+ def input_keys(self) -> List[str]:
44
+ """Expect input key.
45
+
46
+ :meta private:
47
+ """
48
+ return [self.instructions_key]
49
+
50
+ @property
51
+ def output_keys(self) -> List[str]:
52
+ """Expect output key.
53
+
54
+ :meta private:
55
+ """
56
+ if not self.return_intermediate_steps:
57
+ return [self.output_key]
58
+ else:
59
+ return [self.output_key, "intermediate_steps"]
60
+
61
+ def _construct_path(self, args: Dict[str, str]) -> str:
62
+ """Construct the path from the deserialized input."""
63
+ path = self.api_operation.base_url + self.api_operation.path
64
+ for param in self.param_mapping.path_params:
65
+ path = path.replace(f"{{{param}}}", str(args.pop(param, "")))
66
+ return path
67
+
68
+ def _extract_query_params(self, args: Dict[str, str]) -> Dict[str, str]:
69
+ """Extract the query params from the deserialized input."""
70
+ query_params = {}
71
+ for param in self.param_mapping.query_params:
72
+ if param in args:
73
+ query_params[param] = args.pop(param)
74
+ return query_params
75
+
76
+ def _extract_body_params(self, args: Dict[str, str]) -> Optional[Dict[str, str]]:
77
+ """Extract the request body params from the deserialized input."""
78
+ body_params = None
79
+ if self.param_mapping.body_params:
80
+ body_params = {}
81
+ for param in self.param_mapping.body_params:
82
+ if param in args:
83
+ body_params[param] = args.pop(param)
84
+ return body_params
85
+
86
+ def deserialize_json_input(self, serialized_args: str) -> dict:
87
+ """Use the serialized typescript dictionary.
88
+
89
+ Resolve the path, query params dict, and optional requestBody dict.
90
+ """
91
+ args: dict = json.loads(serialized_args)
92
+ path = self._construct_path(args)
93
+ body_params = self._extract_body_params(args)
94
+ query_params = self._extract_query_params(args)
95
+ return {
96
+ "url": path,
97
+ "data": body_params,
98
+ "params": query_params,
99
+ }
100
+
101
+ def _get_output(self, output: str, intermediate_steps: dict) -> dict:
102
+ """Return the output from the API call."""
103
+ if self.return_intermediate_steps:
104
+ return {
105
+ self.output_key: output,
106
+ "intermediate_steps": intermediate_steps,
107
+ }
108
+ else:
109
+ return {self.output_key: output}
110
+
111
+ def _call(
112
+ self,
113
+ inputs: Dict[str, Any],
114
+ run_manager: Optional[CallbackManagerForChainRun] = None,
115
+ ) -> Dict[str, str]:
116
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
117
+ intermediate_steps = {}
118
+ instructions = inputs[self.instructions_key]
119
+ instructions = instructions[: self.max_text_length]
120
+ _api_arguments = self.api_request_chain.predict_and_parse(
121
+ instructions=instructions, callbacks=_run_manager.get_child()
122
+ )
123
+ api_arguments = cast(str, _api_arguments)
124
+ intermediate_steps["request_args"] = api_arguments
125
+ _run_manager.on_text(
126
+ api_arguments, color="green", end="\n", verbose=self.verbose
127
+ )
128
+ if api_arguments.startswith("ERROR"):
129
+ return self._get_output(api_arguments, intermediate_steps)
130
+ elif api_arguments.startswith("MESSAGE:"):
131
+ return self._get_output(
132
+ api_arguments[len("MESSAGE:") :], intermediate_steps
133
+ )
134
+ try:
135
+ request_args = self.deserialize_json_input(api_arguments)
136
+ method = getattr(self.requests, self.api_operation.method.value)
137
+ api_response: Response = method(**request_args)
138
+ if api_response.status_code != 200:
139
+ method_str = str(self.api_operation.method.value)
140
+ response_text = (
141
+ f"{api_response.status_code}: {api_response.reason}"
142
+ + f"\nFor {method_str.upper()} {request_args['url']}\n"
143
+ + f"Called with args: {request_args['params']}"
144
+ )
145
+ else:
146
+ response_text = api_response.text
147
+ except Exception as e:
148
+ response_text = f"Error with message {str(e)}"
149
+ response_text = response_text[: self.max_text_length]
150
+ intermediate_steps["response_text"] = response_text
151
+ _run_manager.on_text(
152
+ response_text, color="blue", end="\n", verbose=self.verbose
153
+ )
154
+ if self.api_response_chain is not None:
155
+ _answer = self.api_response_chain.predict_and_parse(
156
+ response=response_text,
157
+ instructions=instructions,
158
+ callbacks=_run_manager.get_child(),
159
+ )
160
+ answer = cast(str, _answer)
161
+ _run_manager.on_text(answer, color="yellow", end="\n", verbose=self.verbose)
162
+ return self._get_output(answer, intermediate_steps)
163
+ else:
164
+ return self._get_output(response_text, intermediate_steps)
165
+
166
+ @classmethod
167
+ def from_url_and_method(
168
+ cls,
169
+ spec_url: str,
170
+ path: str,
171
+ method: str,
172
+ llm: BaseLanguageModel,
173
+ requests: Optional[Requests] = None,
174
+ return_intermediate_steps: bool = False,
175
+ **kwargs: Any,
176
+ # TODO: Handle async
177
+ ) -> "OpenAPIEndpointChain":
178
+ """Create an OpenAPIEndpoint from a spec at the specified url."""
179
+ operation = APIOperation.from_openapi_url(spec_url, path, method)
180
+ return cls.from_api_operation(
181
+ operation,
182
+ requests=requests,
183
+ llm=llm,
184
+ return_intermediate_steps=return_intermediate_steps,
185
+ **kwargs,
186
+ )
187
+
188
+ @classmethod
189
+ def from_api_operation(
190
+ cls,
191
+ operation: APIOperation,
192
+ llm: BaseLanguageModel,
193
+ requests: Optional[Requests] = None,
194
+ verbose: bool = False,
195
+ return_intermediate_steps: bool = False,
196
+ raw_response: bool = False,
197
+ callbacks: Callbacks = None,
198
+ **kwargs: Any,
199
+ # TODO: Handle async
200
+ ) -> "OpenAPIEndpointChain":
201
+ """Create an OpenAPIEndpointChain from an operation and a spec."""
202
+ param_mapping = _ParamMapping(
203
+ query_params=operation.query_params,
204
+ body_params=operation.body_params,
205
+ path_params=operation.path_params,
206
+ )
207
+ requests_chain = APIRequesterChain.from_llm_and_typescript(
208
+ llm,
209
+ typescript_definition=operation.to_typescript(),
210
+ verbose=verbose,
211
+ callbacks=callbacks,
212
+ )
213
+ if raw_response:
214
+ response_chain = None
215
+ else:
216
+ response_chain = APIResponderChain.from_llm(
217
+ llm, verbose=verbose, callbacks=callbacks
218
+ )
219
+ _requests = requests or Requests()
220
+ return cls(
221
+ api_request_chain=requests_chain,
222
+ api_response_chain=response_chain,
223
+ api_operation=operation,
224
+ requests=_requests,
225
+ param_mapping=param_mapping,
226
+ verbose=verbose,
227
+ return_intermediate_steps=return_intermediate_steps,
228
+ callbacks=callbacks,
229
+ **kwargs,
230
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/prompts.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+ REQUEST_TEMPLATE = """You are a helpful AI Assistant. Please provide JSON arguments to agentFunc() based on the user's instructions.
3
+
4
+ API_SCHEMA: ```typescript
5
+ {schema}
6
+ ```
7
+
8
+ USER_INSTRUCTIONS: "{instructions}"
9
+
10
+ Your arguments must be plain json provided in a markdown block:
11
+
12
+ ARGS: ```json
13
+ {{valid json conforming to API_SCHEMA}}
14
+ ```
15
+
16
+ Example
17
+ -----
18
+
19
+ ARGS: ```json
20
+ {{"foo": "bar", "baz": {{"qux": "quux"}}}}
21
+ ```
22
+
23
+ The block must be no more than 1 line long, and all arguments must be valid JSON. All string arguments must be wrapped in double quotes.
24
+ You MUST strictly comply to the types indicated by the provided schema, including all required args.
25
+
26
+ If you don't have sufficient information to call the function due to things like requiring specific uuid's, you can reply with the following message:
27
+
28
+ Message: ```text
29
+ Concise response requesting the additional information that would make calling the function successful.
30
+ ```
31
+
32
+ Begin
33
+ -----
34
+ ARGS:
35
+ """
36
+ RESPONSE_TEMPLATE = """You are a helpful AI assistant trained to answer user queries from API responses.
37
+ You attempted to call an API, which resulted in:
38
+ API_RESPONSE: {response}
39
+
40
+ USER_COMMENT: "{instructions}"
41
+
42
+
43
+ If the API_RESPONSE can answer the USER_COMMENT respond with the following markdown json block:
44
+ Response: ```json
45
+ {{"response": "Human-understandable synthesis of the API_RESPONSE"}}
46
+ ```
47
+
48
+ Otherwise respond with the following markdown json block:
49
+ Response Error: ```json
50
+ {{"response": "What you did and a concise statement of the resulting error. If it can be easily fixed, provide a suggestion."}}
51
+ ```
52
+
53
+ You MUST respond as a markdown json code block. The person you are responding to CANNOT see the API_RESPONSE, so if there is any relevant information there you must include it in your response.
54
+
55
+ Begin:
56
+ ---
57
+ """
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/requests_chain.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """request parser."""
2
+
3
+ import json
4
+ import re
5
+ from typing import Any
6
+
7
+ from langchain_classic.chains.api.openapi.prompts import REQUEST_TEMPLATE
8
+ from langchain_classic.chains.llm import LLMChain
9
+ from langchain_core.language_models import BaseLanguageModel
10
+ from langchain_core.output_parsers import BaseOutputParser
11
+ from langchain_core.prompts.prompt import PromptTemplate
12
+
13
+
14
+ class APIRequesterOutputParser(BaseOutputParser):
15
+ """Parse the request and error tags."""
16
+
17
+ def _load_json_block(self, serialized_block: str) -> str:
18
+ try:
19
+ return json.dumps(json.loads(serialized_block, strict=False))
20
+ except json.JSONDecodeError:
21
+ return "ERROR serializing request."
22
+
23
+ def parse(self, llm_output: str) -> str:
24
+ """Parse the request and error tags."""
25
+
26
+ json_match = re.search(r"```json(.*?)```", llm_output, re.DOTALL)
27
+ if json_match:
28
+ return self._load_json_block(json_match.group(1).strip())
29
+ message_match = re.search(r"```text(.*?)```", llm_output, re.DOTALL)
30
+ if message_match:
31
+ return f"MESSAGE: {message_match.group(1).strip()}"
32
+ return "ERROR making request"
33
+
34
+ @property
35
+ def _type(self) -> str:
36
+ return "api_requester"
37
+
38
+
39
+ class APIRequesterChain(LLMChain):
40
+ """Get the request parser."""
41
+
42
+ @classmethod
43
+ def is_lc_serializable(cls) -> bool:
44
+ return False
45
+
46
+ @classmethod
47
+ def from_llm_and_typescript(
48
+ cls,
49
+ llm: BaseLanguageModel,
50
+ typescript_definition: str,
51
+ verbose: bool = True,
52
+ **kwargs: Any,
53
+ ) -> LLMChain:
54
+ """Get the request parser."""
55
+ output_parser = APIRequesterOutputParser()
56
+ prompt = PromptTemplate(
57
+ template=REQUEST_TEMPLATE,
58
+ output_parser=output_parser,
59
+ partial_variables={"schema": typescript_definition},
60
+ input_variables=["instructions"],
61
+ )
62
+ return cls(prompt=prompt, llm=llm, verbose=verbose, **kwargs)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/openapi/response_chain.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Response parser."""
2
+
3
+ import json
4
+ import re
5
+ from typing import Any
6
+
7
+ from langchain_classic.chains.api.openapi.prompts import RESPONSE_TEMPLATE
8
+ from langchain_classic.chains.llm import LLMChain
9
+ from langchain_core.language_models import BaseLanguageModel
10
+ from langchain_core.output_parsers import BaseOutputParser
11
+ from langchain_core.prompts.prompt import PromptTemplate
12
+
13
+
14
+ class APIResponderOutputParser(BaseOutputParser):
15
+ """Parse the response and error tags."""
16
+
17
+ def _load_json_block(self, serialized_block: str) -> str:
18
+ try:
19
+ response_content = json.loads(serialized_block, strict=False)
20
+ return response_content.get("response", "ERROR parsing response.")
21
+ except json.JSONDecodeError:
22
+ return "ERROR parsing response."
23
+ except:
24
+ raise
25
+
26
+ def parse(self, llm_output: str) -> str:
27
+ """Parse the response and error tags."""
28
+ json_match = re.search(r"```json(.*?)```", llm_output, re.DOTALL)
29
+ if json_match:
30
+ return self._load_json_block(json_match.group(1).strip())
31
+ else:
32
+ raise ValueError(f"No response found in output: {llm_output}.")
33
+
34
+ @property
35
+ def _type(self) -> str:
36
+ return "api_responder"
37
+
38
+
39
+ class APIResponderChain(LLMChain):
40
+ """Get the response parser."""
41
+
42
+ @classmethod
43
+ def is_lc_serializable(cls) -> bool:
44
+ return False
45
+
46
+ @classmethod
47
+ def from_llm(
48
+ cls, llm: BaseLanguageModel, verbose: bool = True, **kwargs: Any
49
+ ) -> LLMChain:
50
+ """Get the response parser."""
51
+ output_parser = APIResponderOutputParser()
52
+ prompt = PromptTemplate(
53
+ template=RESPONSE_TEMPLATE,
54
+ output_parser=output_parser,
55
+ input_variables=["response", "instructions"],
56
+ )
57
+ return cls(prompt=prompt, llm=llm, verbose=verbose, **kwargs)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__init__.py ADDED
File without changes
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__pycache__/base.cpython-311.pyc ADDED
Binary file (14.4 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__pycache__/enforcement_filters.cpython-311.pyc ADDED
Binary file (17.5 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__pycache__/models.cpython-311.pyc ADDED
Binary file (8.12 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/__pycache__/utilities.cpython-311.pyc ADDED
Binary file (23.4 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/base.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pebblo Retrieval Chain with Identity & Semantic Enforcement for question-answering
3
+ against a vector database.
4
+ """
5
+
6
+ import datetime
7
+ import inspect
8
+ import logging
9
+ from importlib.metadata import version
10
+ from typing import Any, Dict, List, Optional
11
+
12
+ from langchain_classic.chains.base import Chain
13
+ from langchain_classic.chains.combine_documents.base import BaseCombineDocumentsChain
14
+ from langchain_core.callbacks import (
15
+ AsyncCallbackManagerForChainRun,
16
+ CallbackManagerForChainRun,
17
+ )
18
+ from langchain_core.documents import Document
19
+ from langchain_core.language_models import BaseLanguageModel
20
+ from langchain_core.vectorstores import VectorStoreRetriever
21
+ from pydantic import ConfigDict, Field, validator
22
+
23
+ from langchain_community.chains.pebblo_retrieval.enforcement_filters import (
24
+ SUPPORTED_VECTORSTORES,
25
+ set_enforcement_filters,
26
+ )
27
+ from langchain_community.chains.pebblo_retrieval.models import (
28
+ App,
29
+ AuthContext,
30
+ ChainInfo,
31
+ Framework,
32
+ Model,
33
+ SemanticContext,
34
+ VectorDB,
35
+ )
36
+ from langchain_community.chains.pebblo_retrieval.utilities import (
37
+ PLUGIN_VERSION,
38
+ PebbloRetrievalAPIWrapper,
39
+ get_runtime,
40
+ )
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+
45
+ class PebbloRetrievalQA(Chain):
46
+ """
47
+ Retrieval Chain with Identity & Semantic Enforcement for question-answering
48
+ against a vector database.
49
+ """
50
+
51
+ combine_documents_chain: BaseCombineDocumentsChain
52
+ """Chain to use to combine the documents."""
53
+ input_key: str = "query" #: :meta private:
54
+ output_key: str = "result" #: :meta private:
55
+ return_source_documents: bool = False
56
+ """Return the source documents or not."""
57
+
58
+ retriever: VectorStoreRetriever = Field(exclude=True)
59
+ """VectorStore to use for retrieval."""
60
+ auth_context_key: str = "auth_context" #: :meta private:
61
+ """Authentication context for identity enforcement."""
62
+ semantic_context_key: str = "semantic_context" #: :meta private:
63
+ """Semantic context for semantic enforcement."""
64
+ app_name: str #: :meta private:
65
+ """App name."""
66
+ owner: str #: :meta private:
67
+ """Owner of app."""
68
+ description: str #: :meta private:
69
+ """Description of app."""
70
+ api_key: Optional[str] = None #: :meta private:
71
+ """Pebblo cloud API key for app."""
72
+ classifier_url: Optional[str] = None #: :meta private:
73
+ """Classifier endpoint."""
74
+ classifier_location: str = "local" #: :meta private:
75
+ """Classifier location. It could be either of 'local' or 'pebblo-cloud'."""
76
+ _discover_sent: bool = False #: :meta private:
77
+ """Flag to check if discover payload has been sent."""
78
+ enable_prompt_gov: bool = True #: :meta private:
79
+ """Flag to check if prompt governance is enabled or not"""
80
+ pb_client: PebbloRetrievalAPIWrapper = Field(
81
+ default_factory=PebbloRetrievalAPIWrapper
82
+ )
83
+ """Pebblo Retrieval API client"""
84
+
85
+ def _call(
86
+ self,
87
+ inputs: Dict[str, Any],
88
+ run_manager: Optional[CallbackManagerForChainRun] = None,
89
+ ) -> Dict[str, Any]:
90
+ """Run get_relevant_text and llm on input query.
91
+
92
+ If chain has 'return_source_documents' as 'True', returns
93
+ the retrieved documents as well under the key 'source_documents'.
94
+
95
+ Example:
96
+ .. code-block:: python
97
+
98
+ res = indexqa({'query': 'This is my query'})
99
+ answer, docs = res['result'], res['source_documents']
100
+ """
101
+ prompt_time = datetime.datetime.now().isoformat()
102
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
103
+ question = inputs[self.input_key]
104
+ auth_context = inputs.get(self.auth_context_key)
105
+ semantic_context = inputs.get(self.semantic_context_key)
106
+ _, prompt_entities = self.pb_client.check_prompt_validity(question)
107
+
108
+ accepts_run_manager = (
109
+ "run_manager" in inspect.signature(self._get_docs).parameters
110
+ )
111
+ if accepts_run_manager:
112
+ docs = self._get_docs(
113
+ question, auth_context, semantic_context, run_manager=_run_manager
114
+ )
115
+ else:
116
+ docs = self._get_docs(question, auth_context, semantic_context) # type: ignore[call-arg]
117
+ answer = self.combine_documents_chain.run(
118
+ input_documents=docs, question=question, callbacks=_run_manager.get_child()
119
+ )
120
+
121
+ self.pb_client.send_prompt(
122
+ self.app_name,
123
+ self.retriever,
124
+ question,
125
+ answer,
126
+ auth_context,
127
+ docs,
128
+ prompt_entities,
129
+ prompt_time,
130
+ self.enable_prompt_gov,
131
+ )
132
+
133
+ if self.return_source_documents:
134
+ return {self.output_key: answer, "source_documents": docs}
135
+ else:
136
+ return {self.output_key: answer}
137
+
138
+ async def _acall(
139
+ self,
140
+ inputs: Dict[str, Any],
141
+ run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
142
+ ) -> Dict[str, Any]:
143
+ """Run get_relevant_text and llm on input query.
144
+
145
+ If chain has 'return_source_documents' as 'True', returns
146
+ the retrieved documents as well under the key 'source_documents'.
147
+
148
+ Example:
149
+ .. code-block:: python
150
+
151
+ res = indexqa({'query': 'This is my query'})
152
+ answer, docs = res['result'], res['source_documents']
153
+ """
154
+ prompt_time = datetime.datetime.now().isoformat()
155
+ _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
156
+ question = inputs[self.input_key]
157
+ auth_context = inputs.get(self.auth_context_key)
158
+ semantic_context = inputs.get(self.semantic_context_key)
159
+ accepts_run_manager = (
160
+ "run_manager" in inspect.signature(self._aget_docs).parameters
161
+ )
162
+
163
+ _, prompt_entities = await self.pb_client.acheck_prompt_validity(question)
164
+
165
+ if accepts_run_manager:
166
+ docs = await self._aget_docs(
167
+ question, auth_context, semantic_context, run_manager=_run_manager
168
+ )
169
+ else:
170
+ docs = await self._aget_docs(question, auth_context, semantic_context) # type: ignore[call-arg]
171
+ answer = await self.combine_documents_chain.arun(
172
+ input_documents=docs, question=question, callbacks=_run_manager.get_child()
173
+ )
174
+
175
+ await self.pb_client.asend_prompt(
176
+ self.app_name,
177
+ self.retriever,
178
+ question,
179
+ answer,
180
+ auth_context,
181
+ docs,
182
+ prompt_entities,
183
+ prompt_time,
184
+ self.enable_prompt_gov,
185
+ )
186
+
187
+ if self.return_source_documents:
188
+ return {self.output_key: answer, "source_documents": docs}
189
+ else:
190
+ return {self.output_key: answer}
191
+
192
+ model_config = ConfigDict(
193
+ populate_by_name=True,
194
+ arbitrary_types_allowed=True,
195
+ extra="forbid",
196
+ )
197
+
198
+ @property
199
+ def input_keys(self) -> List[str]:
200
+ """Input keys.
201
+
202
+ :meta private:
203
+ """
204
+ return [self.input_key, self.auth_context_key, self.semantic_context_key]
205
+
206
+ @property
207
+ def output_keys(self) -> List[str]:
208
+ """Output keys.
209
+
210
+ :meta private:
211
+ """
212
+ _output_keys = [self.output_key]
213
+ if self.return_source_documents:
214
+ _output_keys += ["source_documents"]
215
+ return _output_keys
216
+
217
+ @property
218
+ def _chain_type(self) -> str:
219
+ """Return the chain type."""
220
+ return "pebblo_retrieval_qa"
221
+
222
+ @classmethod
223
+ def from_chain_type(
224
+ cls,
225
+ llm: BaseLanguageModel,
226
+ app_name: str,
227
+ description: str,
228
+ owner: str,
229
+ chain_type: str = "stuff",
230
+ chain_type_kwargs: Optional[dict] = None,
231
+ api_key: Optional[str] = None,
232
+ classifier_url: Optional[str] = None,
233
+ classifier_location: str = "local",
234
+ **kwargs: Any,
235
+ ) -> "PebbloRetrievalQA":
236
+ """Load chain from chain type."""
237
+ from langchain_classic.chains.question_answering import load_qa_chain
238
+
239
+ _chain_type_kwargs = chain_type_kwargs or {}
240
+ combine_documents_chain = load_qa_chain(
241
+ llm, chain_type=chain_type, **_chain_type_kwargs
242
+ )
243
+
244
+ # generate app
245
+ app: App = PebbloRetrievalQA._get_app_details(
246
+ app_name=app_name,
247
+ description=description,
248
+ owner=owner,
249
+ llm=llm,
250
+ **kwargs,
251
+ )
252
+ # initialize Pebblo API client
253
+ pb_client = PebbloRetrievalAPIWrapper(
254
+ api_key=api_key,
255
+ classifier_location=classifier_location,
256
+ classifier_url=classifier_url,
257
+ )
258
+ # send app discovery request
259
+ pb_client.send_app_discover(app)
260
+ return cls(
261
+ combine_documents_chain=combine_documents_chain,
262
+ app_name=app_name,
263
+ owner=owner,
264
+ description=description,
265
+ api_key=api_key,
266
+ classifier_url=classifier_url,
267
+ classifier_location=classifier_location,
268
+ pb_client=pb_client,
269
+ **kwargs,
270
+ )
271
+
272
+ @validator("retriever", pre=True, always=True)
273
+ def validate_vectorstore(
274
+ cls, retriever: VectorStoreRetriever
275
+ ) -> VectorStoreRetriever:
276
+ """
277
+ Validate that the vectorstore of the retriever is supported vectorstores.
278
+ """
279
+ if retriever.vectorstore.__class__.__name__ not in SUPPORTED_VECTORSTORES:
280
+ raise ValueError(
281
+ f"Vectorstore must be an instance of one of the supported "
282
+ f"vectorstores: {SUPPORTED_VECTORSTORES}. "
283
+ f"Got '{retriever.vectorstore.__class__.__name__}' instead."
284
+ )
285
+ return retriever
286
+
287
+ def _get_docs(
288
+ self,
289
+ question: str,
290
+ auth_context: Optional[AuthContext],
291
+ semantic_context: Optional[SemanticContext],
292
+ *,
293
+ run_manager: CallbackManagerForChainRun,
294
+ ) -> List[Document]:
295
+ """Get docs."""
296
+ set_enforcement_filters(self.retriever, auth_context, semantic_context)
297
+ return self.retriever.invoke(
298
+ question, config={"callbacks": run_manager.get_child()}
299
+ )
300
+
301
+ async def _aget_docs(
302
+ self,
303
+ question: str,
304
+ auth_context: Optional[AuthContext],
305
+ semantic_context: Optional[SemanticContext],
306
+ *,
307
+ run_manager: AsyncCallbackManagerForChainRun,
308
+ ) -> List[Document]:
309
+ """Get docs."""
310
+ set_enforcement_filters(self.retriever, auth_context, semantic_context)
311
+ return await self.retriever.ainvoke(
312
+ question, config={"callbacks": run_manager.get_child()}
313
+ )
314
+
315
+ @staticmethod
316
+ def _get_app_details(
317
+ app_name: str,
318
+ owner: str,
319
+ description: str,
320
+ llm: BaseLanguageModel,
321
+ **kwargs: Any,
322
+ ) -> App:
323
+ """Fetch app details. Internal method.
324
+ Returns:
325
+ App: App details.
326
+ """
327
+ framework, runtime = get_runtime()
328
+ chains = PebbloRetrievalQA.get_chain_details(llm, **kwargs)
329
+ app = App(
330
+ name=app_name,
331
+ owner=owner,
332
+ description=description,
333
+ runtime=runtime,
334
+ framework=framework,
335
+ chains=chains,
336
+ plugin_version=PLUGIN_VERSION,
337
+ client_version=Framework(
338
+ name="langchain_community",
339
+ version=version("langchain_community"),
340
+ ),
341
+ )
342
+ return app
343
+
344
+ @classmethod
345
+ def set_discover_sent(cls) -> None:
346
+ cls._discover_sent = True
347
+
348
+ @classmethod
349
+ def get_chain_details(
350
+ cls, llm: BaseLanguageModel, **kwargs: Any
351
+ ) -> List[ChainInfo]:
352
+ """
353
+ Get chain details.
354
+
355
+ Args:
356
+ llm (BaseLanguageModel): Language model instance.
357
+ **kwargs: Additional keyword arguments.
358
+
359
+ Returns:
360
+ List[ChainInfo]: Chain details.
361
+ """
362
+ llm_dict = llm.__dict__
363
+ chains = [
364
+ ChainInfo(
365
+ name=cls.__name__,
366
+ model=Model(
367
+ name=llm_dict.get("model_name", llm_dict.get("model")),
368
+ vendor=llm.__class__.__name__,
369
+ ),
370
+ vector_dbs=[
371
+ VectorDB(
372
+ name=kwargs["retriever"].vectorstore.__class__.__name__,
373
+ embedding_model=str(
374
+ kwargs["retriever"].vectorstore._embeddings.model
375
+ )
376
+ if hasattr(kwargs["retriever"].vectorstore, "_embeddings")
377
+ else (
378
+ str(kwargs["retriever"].vectorstore._embedding.model)
379
+ if hasattr(kwargs["retriever"].vectorstore, "_embedding")
380
+ else None
381
+ ),
382
+ )
383
+ ],
384
+ ),
385
+ ]
386
+ return chains
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/enforcement_filters.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Identity & Semantic Enforcement filters for PebbloRetrievalQA chain:
3
+
4
+ This module contains methods for applying Identity and Semantic Enforcement filters
5
+ in the PebbloRetrievalQA chain.
6
+ These filters are used to control the retrieval of documents based on authorization and
7
+ semantic context.
8
+ The Identity Enforcement filter ensures that only authorized identities can access
9
+ certain documents, while the Semantic Enforcement filter controls document retrieval
10
+ based on semantic context.
11
+
12
+ The methods in this module are designed to work with different types of vector stores.
13
+ """
14
+
15
+ import logging
16
+ from typing import Any, List, Optional, Union
17
+
18
+ from langchain_core.vectorstores import VectorStoreRetriever
19
+
20
+ from langchain_community.chains.pebblo_retrieval.models import (
21
+ AuthContext,
22
+ SemanticContext,
23
+ )
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ PINECONE = "Pinecone"
28
+ QDRANT = "Qdrant"
29
+ PGVECTOR = "PGVector"
30
+ PINECONE_VECTOR_STORE = "PineconeVectorStore"
31
+
32
+ SUPPORTED_VECTORSTORES = {PINECONE, QDRANT, PGVECTOR, PINECONE_VECTOR_STORE}
33
+
34
+
35
+ def clear_enforcement_filters(retriever: VectorStoreRetriever) -> None:
36
+ """
37
+ Clear the identity and semantic enforcement filters in the retriever search_kwargs.
38
+ """
39
+ if retriever.vectorstore.__class__.__name__ == PGVECTOR:
40
+ search_kwargs = retriever.search_kwargs
41
+ if "filter" in search_kwargs:
42
+ filters = search_kwargs["filter"]
43
+ _pgvector_clear_pebblo_filters(
44
+ search_kwargs, filters, "authorized_identities"
45
+ )
46
+ _pgvector_clear_pebblo_filters(
47
+ search_kwargs, filters, "pebblo_semantic_topics"
48
+ )
49
+ _pgvector_clear_pebblo_filters(
50
+ search_kwargs, filters, "pebblo_semantic_entities"
51
+ )
52
+
53
+
54
+ def set_enforcement_filters(
55
+ retriever: VectorStoreRetriever,
56
+ auth_context: Optional[AuthContext],
57
+ semantic_context: Optional[SemanticContext],
58
+ ) -> None:
59
+ """
60
+ Set identity and semantic enforcement filters in the retriever.
61
+ """
62
+ # Clear existing enforcement filters
63
+ clear_enforcement_filters(retriever)
64
+ if auth_context is not None:
65
+ _set_identity_enforcement_filter(retriever, auth_context)
66
+ if semantic_context is not None:
67
+ _set_semantic_enforcement_filter(retriever, semantic_context)
68
+
69
+
70
+ def _apply_qdrant_semantic_filter(
71
+ search_kwargs: dict, semantic_context: Optional[SemanticContext]
72
+ ) -> None:
73
+ """
74
+ Set semantic enforcement filter in search_kwargs for Qdrant vectorstore.
75
+ """
76
+ try:
77
+ from qdrant_client.http import models as rest
78
+ except ImportError as e:
79
+ raise ValueError(
80
+ "Could not import `qdrant-client.http` python package. "
81
+ "Please install it with `pip install qdrant-client`."
82
+ ) from e
83
+
84
+ # Create a semantic enforcement filter condition
85
+ semantic_filters: List[
86
+ Union[
87
+ rest.FieldCondition,
88
+ rest.IsEmptyCondition,
89
+ rest.IsNullCondition,
90
+ rest.HasIdCondition,
91
+ rest.NestedCondition,
92
+ rest.Filter,
93
+ ]
94
+ ] = []
95
+
96
+ if (
97
+ semantic_context is not None
98
+ and semantic_context.pebblo_semantic_topics is not None
99
+ ):
100
+ semantic_topics_filter = rest.FieldCondition(
101
+ key="metadata.pebblo_semantic_topics",
102
+ match=rest.MatchAny(any=semantic_context.pebblo_semantic_topics.deny),
103
+ )
104
+ semantic_filters.append(semantic_topics_filter)
105
+ if (
106
+ semantic_context is not None
107
+ and semantic_context.pebblo_semantic_entities is not None
108
+ ):
109
+ semantic_entities_filter = rest.FieldCondition(
110
+ key="metadata.pebblo_semantic_entities",
111
+ match=rest.MatchAny(any=semantic_context.pebblo_semantic_entities.deny),
112
+ )
113
+ semantic_filters.append(semantic_entities_filter)
114
+
115
+ # If 'filter' already exists in search_kwargs
116
+ if "filter" in search_kwargs:
117
+ existing_filter: rest.Filter = search_kwargs["filter"]
118
+
119
+ # Check if existing_filter is a qdrant-client filter
120
+ if isinstance(existing_filter, rest.Filter):
121
+ # If 'must_not' condition exists in the existing filter
122
+ if isinstance(existing_filter.must_not, list):
123
+ # Warn if 'pebblo_semantic_topics' or 'pebblo_semantic_entities'
124
+ # filter is overridden
125
+ new_must_not_conditions: List[
126
+ Union[
127
+ rest.FieldCondition,
128
+ rest.IsEmptyCondition,
129
+ rest.IsNullCondition,
130
+ rest.HasIdCondition,
131
+ rest.NestedCondition,
132
+ rest.Filter,
133
+ ]
134
+ ] = []
135
+ # Drop semantic filter conditions if already present
136
+ for condition in existing_filter.must_not:
137
+ if hasattr(condition, "key"):
138
+ if condition.key == "metadata.pebblo_semantic_topics":
139
+ continue
140
+ if condition.key == "metadata.pebblo_semantic_entities":
141
+ continue
142
+ new_must_not_conditions.append(condition)
143
+ # Add semantic enforcement filters to 'must_not' conditions
144
+ existing_filter.must_not = new_must_not_conditions
145
+ existing_filter.must_not.extend(semantic_filters)
146
+ else:
147
+ # Set 'must_not' condition with semantic enforcement filters
148
+ existing_filter.must_not = semantic_filters
149
+ else:
150
+ raise TypeError(
151
+ "Using dict as a `filter` is deprecated. "
152
+ "Please use qdrant-client filters directly: "
153
+ "https://qdrant.tech/documentation/concepts/filtering/"
154
+ )
155
+ else:
156
+ # If 'filter' does not exist in search_kwargs, create it
157
+ search_kwargs["filter"] = rest.Filter(must_not=semantic_filters)
158
+
159
+
160
+ def _apply_qdrant_authorization_filter(
161
+ search_kwargs: dict, auth_context: Optional[AuthContext]
162
+ ) -> None:
163
+ """
164
+ Set identity enforcement filter in search_kwargs for Qdrant vectorstore.
165
+ """
166
+ try:
167
+ from qdrant_client.http import models as rest
168
+ except ImportError as e:
169
+ raise ValueError(
170
+ "Could not import `qdrant-client.http` python package. "
171
+ "Please install it with `pip install qdrant-client`."
172
+ ) from e
173
+
174
+ if auth_context is not None:
175
+ # Create a identity enforcement filter condition
176
+ identity_enforcement_filter = rest.FieldCondition(
177
+ key="metadata.authorized_identities",
178
+ match=rest.MatchAny(any=auth_context.user_auth),
179
+ )
180
+ else:
181
+ return
182
+
183
+ # If 'filter' already exists in search_kwargs
184
+ if "filter" in search_kwargs:
185
+ existing_filter: rest.Filter = search_kwargs["filter"]
186
+
187
+ # Check if existing_filter is a qdrant-client filter
188
+ if isinstance(existing_filter, rest.Filter):
189
+ # If 'must' exists in the existing filter
190
+ if existing_filter.must:
191
+ new_must_conditions: List[
192
+ Union[
193
+ rest.FieldCondition,
194
+ rest.IsEmptyCondition,
195
+ rest.IsNullCondition,
196
+ rest.HasIdCondition,
197
+ rest.NestedCondition,
198
+ rest.Filter,
199
+ ]
200
+ ] = []
201
+ # Drop 'authorized_identities' filter condition if already present
202
+ for condition in existing_filter.must:
203
+ if (
204
+ hasattr(condition, "key")
205
+ and condition.key == "metadata.authorized_identities"
206
+ ):
207
+ continue
208
+ new_must_conditions.append(condition)
209
+
210
+ # Add identity enforcement filter to 'must' conditions
211
+ existing_filter.must = new_must_conditions
212
+ existing_filter.must.append(identity_enforcement_filter)
213
+ else:
214
+ # Set 'must' condition with identity enforcement filter
215
+ existing_filter.must = [identity_enforcement_filter]
216
+ else:
217
+ raise TypeError(
218
+ "Using dict as a `filter` is deprecated. "
219
+ "Please use qdrant-client filters directly: "
220
+ "https://qdrant.tech/documentation/concepts/filtering/"
221
+ )
222
+ else:
223
+ # If 'filter' does not exist in search_kwargs, create it
224
+ search_kwargs["filter"] = rest.Filter(must=[identity_enforcement_filter])
225
+
226
+
227
+ def _apply_pinecone_semantic_filter(
228
+ search_kwargs: dict, semantic_context: Optional[SemanticContext]
229
+ ) -> None:
230
+ """
231
+ Set semantic enforcement filter in search_kwargs for Pinecone vectorstore.
232
+ """
233
+ # Check if semantic_context is provided
234
+ semantic_context = semantic_context
235
+ if semantic_context is not None:
236
+ if semantic_context.pebblo_semantic_topics is not None:
237
+ # Add pebblo_semantic_topics filter to search_kwargs
238
+ search_kwargs.setdefault("filter", {})["pebblo_semantic_topics"] = {
239
+ "$nin": semantic_context.pebblo_semantic_topics.deny
240
+ }
241
+
242
+ if semantic_context.pebblo_semantic_entities is not None:
243
+ # Add pebblo_semantic_entities filter to search_kwargs
244
+ search_kwargs.setdefault("filter", {})["pebblo_semantic_entities"] = {
245
+ "$nin": semantic_context.pebblo_semantic_entities.deny
246
+ }
247
+
248
+
249
+ def _apply_pinecone_authorization_filter(
250
+ search_kwargs: dict, auth_context: Optional[AuthContext]
251
+ ) -> None:
252
+ """
253
+ Set identity enforcement filter in search_kwargs for Pinecone vectorstore.
254
+ """
255
+ if auth_context is not None:
256
+ search_kwargs.setdefault("filter", {})["authorized_identities"] = {
257
+ "$in": auth_context.user_auth
258
+ }
259
+
260
+
261
+ def _apply_pgvector_filter(
262
+ search_kwargs: dict, filters: Optional[Any], pebblo_filter: dict
263
+ ) -> None:
264
+ """
265
+ Apply pebblo filters in the search_kwargs filters.
266
+ """
267
+ if isinstance(filters, dict):
268
+ if len(filters) == 1:
269
+ # The only operators allowed at the top level are $and, $or, and $not
270
+ # First check if an operator or a field
271
+ key, value = list(filters.items())[0]
272
+ if key.startswith("$"):
273
+ # Then it's an operator
274
+ if key.lower() not in ["$and", "$or", "$not"]:
275
+ raise ValueError(
276
+ f"Invalid filter condition. Expected $and, $or or $not "
277
+ f"but got: {key}"
278
+ )
279
+ if not isinstance(value, list):
280
+ raise ValueError(
281
+ f"Expected a list, but got {type(value)} for value: {value}"
282
+ )
283
+
284
+ # Here we handle the $and, $or, and $not operators(Semantic filters)
285
+ if key.lower() == "$and":
286
+ # Add pebblo_filter to the $and list as it is
287
+ value.append(pebblo_filter)
288
+ elif key.lower() == "$not":
289
+ # Check if pebblo_filter is an operator or a field
290
+ _key, _value = list(pebblo_filter.items())[0]
291
+ if _key.startswith("$"):
292
+ # Then it's a operator
293
+ if _key.lower() == "$not":
294
+ # It's Semantic filter, add it's value to filters
295
+ value.append(_value)
296
+ logger.warning(
297
+ "Adding $not operator to the existing $not operator"
298
+ )
299
+ return
300
+ else:
301
+ # Only $not operator is supported in pebblo_filter
302
+ raise ValueError(
303
+ f"Invalid filter key. Expected '$not' but got: {_key}"
304
+ )
305
+ else:
306
+ # Then it's a field(Auth filter), move filters into $and
307
+ search_kwargs["filter"] = {"$and": [filters, pebblo_filter]}
308
+ return
309
+ elif key.lower() == "$or":
310
+ search_kwargs["filter"] = {"$and": [filters, pebblo_filter]}
311
+ else:
312
+ # Then it's a field and we can check pebblo_filter now
313
+ # Check if pebblo_filter is an operator or a field
314
+ _key, _ = list(pebblo_filter.items())[0]
315
+ if _key.startswith("$"):
316
+ # Then it's a operator
317
+ if _key.lower() == "$not":
318
+ # It's a $not operator(Semantic filter), move filters into $and
319
+ search_kwargs["filter"] = {"$and": [filters, pebblo_filter]}
320
+ return
321
+ else:
322
+ # Only $not operator is allowed in pebblo_filter
323
+ raise ValueError(
324
+ f"Invalid filter key. Expected '$not' but got: {_key}"
325
+ )
326
+ else:
327
+ # Then it's a field(This handles Auth filter)
328
+ filters.update(pebblo_filter)
329
+ return
330
+ elif len(filters) > 1:
331
+ # Then all keys have to be fields (they cannot be operators)
332
+ for key in filters.keys():
333
+ if key.startswith("$"):
334
+ raise ValueError(
335
+ f"Invalid filter condition. Expected a field but got: {key}"
336
+ )
337
+ # filters should all be fields and we can check pebblo_filter now
338
+ # Check if pebblo_filter is an operator or a field
339
+ _key, _ = list(pebblo_filter.items())[0]
340
+ if _key.startswith("$"):
341
+ # Then it's a operator
342
+ if _key.lower() == "$not":
343
+ # It's a $not operator(Semantic filter), move filters into '$and'
344
+ search_kwargs["filter"] = {"$and": [filters, pebblo_filter]}
345
+ return
346
+ else:
347
+ # Only $not operator is supported in pebblo_filter
348
+ raise ValueError(
349
+ f"Invalid filter key. Expected '$not' but got: {_key}"
350
+ )
351
+ else:
352
+ # Then it's a field(This handles Auth filter)
353
+ filters.update(pebblo_filter)
354
+ return
355
+ else:
356
+ # Got an empty dictionary for filters, set pebblo_filter in filter
357
+ search_kwargs.setdefault("filter", {}).update(pebblo_filter)
358
+ elif filters is None:
359
+ # If filters is None, set pebblo_filter as a new filter
360
+ search_kwargs.setdefault("filter", {}).update(pebblo_filter)
361
+ else:
362
+ raise ValueError(
363
+ f"Invalid filter. Expected a dictionary/None but got type: {type(filters)}"
364
+ )
365
+
366
+
367
+ def _pgvector_clear_pebblo_filters(
368
+ search_kwargs: dict, filters: dict, pebblo_filter_key: str
369
+ ) -> None:
370
+ """
371
+ Remove pebblo filters from the search_kwargs filters.
372
+ """
373
+ if isinstance(filters, dict):
374
+ if len(filters) == 1:
375
+ # The only operators allowed at the top level are $and, $or, and $not
376
+ # First check if an operator or a field
377
+ key, value = list(filters.items())[0]
378
+ if key.startswith("$"):
379
+ # Then it's an operator
380
+ # Validate the operator's key and value type
381
+ if key.lower() not in ["$and", "$or", "$not"]:
382
+ raise ValueError(
383
+ f"Invalid filter condition. Expected $and, $or or $not "
384
+ f"but got: {key}"
385
+ )
386
+ elif not isinstance(value, list):
387
+ raise ValueError(
388
+ f"Expected a list, but got {type(value)} for value: {value}"
389
+ )
390
+
391
+ # Here we handle the $and, $or, and $not operators
392
+ if key.lower() == "$and":
393
+ # Remove the pebblo filter from the $and list
394
+ for i, _filter in enumerate(value):
395
+ if pebblo_filter_key in _filter:
396
+ # This handles Auth filter
397
+ value.pop(i)
398
+ break
399
+ # Check for $not operator with Semantic filter
400
+ if "$not" in _filter:
401
+ sem_filter_found = False
402
+ # This handles Semantic filter
403
+ for j, nested_filter in enumerate(_filter["$not"]):
404
+ if pebblo_filter_key in nested_filter:
405
+ if len(_filter["$not"]) == 1:
406
+ # If only one filter is left,
407
+ # then remove the $not operator
408
+ value.pop(i)
409
+ else:
410
+ value[i]["$not"].pop(j)
411
+ sem_filter_found = True
412
+ break
413
+ if sem_filter_found:
414
+ break
415
+ if len(value) == 1:
416
+ # If only one filter is left, then remove the $and operator
417
+ search_kwargs["filter"] = value[0]
418
+ elif key.lower() == "$not":
419
+ # Remove the pebblo filter from the $not list
420
+ for i, _filter in enumerate(value):
421
+ if pebblo_filter_key in _filter:
422
+ # This removes Semantic filter
423
+ value.pop(i)
424
+ break
425
+ if len(value) == 0:
426
+ # If no filter is left, then unset the filter
427
+ search_kwargs["filter"] = {}
428
+ elif key.lower() == "$or":
429
+ # If $or, pebblo filter will not be present
430
+ return
431
+ else:
432
+ # Then it's a field, check if it's a pebblo filter
433
+ if key == pebblo_filter_key:
434
+ filters.pop(key)
435
+ return
436
+ elif len(filters) > 1:
437
+ # Then all keys have to be fields (they cannot be operators)
438
+ if pebblo_filter_key in filters:
439
+ # This handles Auth filter
440
+ filters.pop(pebblo_filter_key)
441
+ return
442
+ else:
443
+ # Got an empty dictionary for filters, ignore the filter
444
+ return
445
+ elif filters is None:
446
+ # If filters is None, ignore the filter
447
+ return
448
+ else:
449
+ raise ValueError(
450
+ f"Invalid filter. Expected a dictionary/None but got type: {type(filters)}"
451
+ )
452
+
453
+
454
+ def _apply_pgvector_semantic_filter(
455
+ search_kwargs: dict, semantic_context: Optional[SemanticContext]
456
+ ) -> None:
457
+ """
458
+ Set semantic enforcement filter in search_kwargs for PGVector vectorstore.
459
+ """
460
+ # Check if semantic_context is provided
461
+ if semantic_context is not None:
462
+ _semantic_filters = []
463
+ filters = search_kwargs.get("filter")
464
+ if semantic_context.pebblo_semantic_topics is not None:
465
+ # Add pebblo_semantic_topics filter to search_kwargs
466
+ topic_filter: dict = {
467
+ "pebblo_semantic_topics": {
468
+ "$eq": semantic_context.pebblo_semantic_topics.deny
469
+ }
470
+ }
471
+ _semantic_filters.append(topic_filter)
472
+
473
+ if semantic_context.pebblo_semantic_entities is not None:
474
+ # Add pebblo_semantic_entities filter to search_kwargs
475
+ entity_filter: dict = {
476
+ "pebblo_semantic_entities": {
477
+ "$eq": semantic_context.pebblo_semantic_entities.deny
478
+ }
479
+ }
480
+ _semantic_filters.append(entity_filter)
481
+
482
+ if len(_semantic_filters) > 0:
483
+ semantic_filter: dict = {"$not": _semantic_filters}
484
+ _apply_pgvector_filter(search_kwargs, filters, semantic_filter)
485
+
486
+
487
+ def _apply_pgvector_authorization_filter(
488
+ search_kwargs: dict, auth_context: Optional[AuthContext]
489
+ ) -> None:
490
+ """
491
+ Set identity enforcement filter in search_kwargs for PGVector vectorstore.
492
+ """
493
+ if auth_context is not None:
494
+ auth_filter: dict = {"authorized_identities": {"$eq": auth_context.user_auth}}
495
+ filters = search_kwargs.get("filter")
496
+ _apply_pgvector_filter(search_kwargs, filters, auth_filter)
497
+
498
+
499
+ def _set_identity_enforcement_filter(
500
+ retriever: VectorStoreRetriever, auth_context: Optional[AuthContext]
501
+ ) -> None:
502
+ """
503
+ Set identity enforcement filter in search_kwargs.
504
+
505
+ This method sets the identity enforcement filter in the search_kwargs
506
+ of the retriever based on the type of the vectorstore.
507
+ """
508
+ search_kwargs = retriever.search_kwargs
509
+ if retriever.vectorstore.__class__.__name__ in [PINECONE, PINECONE_VECTOR_STORE]:
510
+ _apply_pinecone_authorization_filter(search_kwargs, auth_context)
511
+ elif retriever.vectorstore.__class__.__name__ == QDRANT:
512
+ _apply_qdrant_authorization_filter(search_kwargs, auth_context)
513
+ elif retriever.vectorstore.__class__.__name__ == PGVECTOR:
514
+ _apply_pgvector_authorization_filter(search_kwargs, auth_context)
515
+
516
+
517
+ def _set_semantic_enforcement_filter(
518
+ retriever: VectorStoreRetriever, semantic_context: Optional[SemanticContext]
519
+ ) -> None:
520
+ """
521
+ Set semantic enforcement filter in search_kwargs.
522
+
523
+ This method sets the semantic enforcement filter in the search_kwargs
524
+ of the retriever based on the type of the vectorstore.
525
+ """
526
+ search_kwargs = retriever.search_kwargs
527
+ if retriever.vectorstore.__class__.__name__ == PINECONE:
528
+ _apply_pinecone_semantic_filter(search_kwargs, semantic_context)
529
+ elif retriever.vectorstore.__class__.__name__ == QDRANT:
530
+ _apply_qdrant_semantic_filter(search_kwargs, semantic_context)
531
+ elif retriever.vectorstore.__class__.__name__ == PGVECTOR:
532
+ _apply_pgvector_semantic_filter(search_kwargs, semantic_context)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/models.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Models for the PebbloRetrievalQA chain."""
2
+
3
+ from typing import Any, List, Optional, Union
4
+
5
+ from pydantic import BaseModel
6
+
7
+
8
+ class AuthContext(BaseModel):
9
+ """Class for an authorization context."""
10
+
11
+ name: Optional[str] = None
12
+ user_id: str
13
+ user_auth: List[str]
14
+ """List of user authorizations, which may include their User ID and
15
+ the groups they are part of"""
16
+
17
+
18
+ class SemanticEntities(BaseModel):
19
+ """Class for a semantic entity filter."""
20
+
21
+ deny: List[str]
22
+
23
+
24
+ class SemanticTopics(BaseModel):
25
+ """Class for a semantic topic filter."""
26
+
27
+ deny: List[str]
28
+
29
+
30
+ class SemanticContext(BaseModel):
31
+ """Class for a semantic context."""
32
+
33
+ pebblo_semantic_entities: Optional[SemanticEntities] = None
34
+ pebblo_semantic_topics: Optional[SemanticTopics] = None
35
+
36
+ def __init__(self, **data: Any) -> None:
37
+ super().__init__(**data)
38
+
39
+ # Validate semantic_context
40
+ if (
41
+ self.pebblo_semantic_entities is None
42
+ and self.pebblo_semantic_topics is None
43
+ ):
44
+ raise ValueError(
45
+ "semantic_context must contain 'pebblo_semantic_entities' or "
46
+ "'pebblo_semantic_topics'"
47
+ )
48
+
49
+
50
+ class ChainInput(BaseModel):
51
+ """Input for PebbloRetrievalQA chain."""
52
+
53
+ query: str
54
+ auth_context: Optional[AuthContext] = None
55
+ semantic_context: Optional[SemanticContext] = None
56
+
57
+ def dict(self, **kwargs: Any) -> dict:
58
+ base_dict = super().dict(**kwargs)
59
+ # Keep auth_context and semantic_context as it is(Pydantic models)
60
+ base_dict["auth_context"] = self.auth_context
61
+ base_dict["semantic_context"] = self.semantic_context
62
+ return base_dict
63
+
64
+
65
+ class Runtime(BaseModel):
66
+ """
67
+ OS, language details
68
+ """
69
+
70
+ type: Optional[str] = ""
71
+ host: str
72
+ path: str
73
+ ip: Optional[str] = ""
74
+ platform: str
75
+ os: str
76
+ os_version: str
77
+ language: str
78
+ language_version: str
79
+ runtime: Optional[str] = ""
80
+
81
+
82
+ class Framework(BaseModel):
83
+ """
84
+ Langchain framework details
85
+ """
86
+
87
+ name: str
88
+ version: str
89
+
90
+
91
+ class Model(BaseModel):
92
+ vendor: Optional[str]
93
+ name: Optional[str]
94
+
95
+
96
+ class PkgInfo(BaseModel):
97
+ project_home_page: Optional[str]
98
+ documentation_url: Optional[str]
99
+ pypi_url: Optional[str]
100
+ liscence_type: Optional[str]
101
+ installed_via: Optional[str]
102
+ location: Optional[str]
103
+
104
+
105
+ class VectorDB(BaseModel):
106
+ name: Optional[str] = None
107
+ version: Optional[str] = None
108
+ location: Optional[str] = None
109
+ embedding_model: Optional[str] = None
110
+
111
+
112
+ class ChainInfo(BaseModel):
113
+ name: str
114
+ model: Optional[Model]
115
+ vector_dbs: Optional[List[VectorDB]]
116
+
117
+
118
+ class App(BaseModel):
119
+ name: str
120
+ owner: str
121
+ description: Optional[str]
122
+ runtime: Runtime
123
+ framework: Framework
124
+ chains: List[ChainInfo]
125
+ plugin_version: str
126
+ client_version: Framework
127
+
128
+
129
+ class Context(BaseModel):
130
+ retrieved_from: Optional[str]
131
+ doc: Optional[str]
132
+ vector_db: str
133
+ pb_checksum: Optional[str]
134
+
135
+
136
+ class Prompt(BaseModel):
137
+ data: Optional[Union[list, str]]
138
+ entityCount: Optional[int] = None
139
+ entities: Optional[dict] = None
140
+ prompt_gov_enabled: Optional[bool] = None
141
+
142
+
143
+ class Qa(BaseModel):
144
+ name: str
145
+ context: Union[List[Optional[Context]], Optional[Context]]
146
+ prompt: Optional[Prompt]
147
+ response: Optional[Prompt]
148
+ prompt_time: str
149
+ user: str
150
+ user_identities: Optional[List[str]]
151
+ classifier_location: str
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/pebblo_retrieval/utilities.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ import platform
5
+ from enum import Enum
6
+ from http import HTTPStatus
7
+ from typing import Any, Dict, List, Optional, Tuple
8
+
9
+ import aiohttp
10
+ from aiohttp import ClientTimeout
11
+ from langchain_core.documents import Document
12
+ from langchain_core.env import get_runtime_environment
13
+ from langchain_core.utils import get_from_dict_or_env
14
+ from langchain_core.vectorstores import VectorStoreRetriever
15
+ from pydantic import BaseModel
16
+ from requests import Response, request
17
+ from requests.exceptions import RequestException
18
+
19
+ from langchain_community.chains.pebblo_retrieval.models import (
20
+ App,
21
+ AuthContext,
22
+ Context,
23
+ Framework,
24
+ Prompt,
25
+ Qa,
26
+ Runtime,
27
+ )
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ PLUGIN_VERSION = "0.1.1"
32
+
33
+ _DEFAULT_CLASSIFIER_URL = "http://localhost:8000"
34
+ _DEFAULT_PEBBLO_CLOUD_URL = "https://api.daxa.ai"
35
+
36
+
37
+ class Routes(str, Enum):
38
+ """Routes available for the Pebblo API as enumerator."""
39
+
40
+ retrieval_app_discover = "/v1/app/discover"
41
+ prompt = "/v1/prompt"
42
+ prompt_governance = "/v1/prompt/governance"
43
+
44
+
45
+ def get_runtime() -> Tuple[Framework, Runtime]:
46
+ """Fetch the current Framework and Runtime details.
47
+
48
+ Returns:
49
+ Tuple[Framework, Runtime]: Framework and Runtime for the current app instance.
50
+ """
51
+ runtime_env = get_runtime_environment()
52
+ framework = Framework(
53
+ name="langchain", version=runtime_env.get("library_version", "unknown")
54
+ )
55
+ uname = platform.uname()
56
+ runtime = Runtime(
57
+ host=uname.node,
58
+ path=os.environ["PWD"],
59
+ platform=runtime_env.get("platform", "unknown"),
60
+ os=uname.system,
61
+ os_version=uname.version,
62
+ ip=get_ip(),
63
+ language=runtime_env.get("runtime", "unknown"),
64
+ language_version=runtime_env.get("runtime_version", "unknown"),
65
+ )
66
+
67
+ if "Darwin" in runtime.os:
68
+ runtime.type = "desktop"
69
+ runtime.runtime = "Mac OSX"
70
+
71
+ logger.debug(f"framework {framework}")
72
+ logger.debug(f"runtime {runtime}")
73
+ return framework, runtime
74
+
75
+
76
+ def get_ip() -> str:
77
+ """Fetch local runtime ip address.
78
+
79
+ Returns:
80
+ str: IP address
81
+ """
82
+ import socket # lazy imports
83
+
84
+ host = socket.gethostname()
85
+ try:
86
+ public_ip = socket.gethostbyname(host)
87
+ except Exception:
88
+ public_ip = socket.gethostbyname("localhost")
89
+ return public_ip
90
+
91
+
92
+ class PebbloRetrievalAPIWrapper(BaseModel):
93
+ """Wrapper for Pebblo Retrieval API."""
94
+
95
+ api_key: Optional[str] # Use SecretStr
96
+ """API key for Pebblo Cloud"""
97
+ classifier_location: str = "local"
98
+ """Location of the classifier, local or cloud. Defaults to 'local'"""
99
+ classifier_url: Optional[str]
100
+ """URL of the Pebblo Classifier"""
101
+ cloud_url: Optional[str]
102
+ """URL of the Pebblo Cloud"""
103
+
104
+ def __init__(self, **kwargs: Any):
105
+ """Validate that api key in environment."""
106
+ kwargs["api_key"] = get_from_dict_or_env(
107
+ kwargs, "api_key", "PEBBLO_API_KEY", ""
108
+ )
109
+ kwargs["classifier_url"] = get_from_dict_or_env(
110
+ kwargs, "classifier_url", "PEBBLO_CLASSIFIER_URL", _DEFAULT_CLASSIFIER_URL
111
+ )
112
+ kwargs["cloud_url"] = get_from_dict_or_env(
113
+ kwargs, "cloud_url", "PEBBLO_CLOUD_URL", _DEFAULT_PEBBLO_CLOUD_URL
114
+ )
115
+ super().__init__(**kwargs)
116
+
117
+ def send_app_discover(self, app: App) -> None:
118
+ """
119
+ Send app discovery request to Pebblo server & cloud.
120
+
121
+ Args:
122
+ app (App): App instance to be discovered.
123
+ """
124
+ pebblo_resp = None
125
+ payload = app.dict(exclude_unset=True)
126
+
127
+ if self.classifier_location == "local":
128
+ # Send app details to local classifier
129
+ headers = self._make_headers()
130
+ app_discover_url = (
131
+ f"{self.classifier_url}{Routes.retrieval_app_discover.value}"
132
+ )
133
+ pebblo_resp = self.make_request("POST", app_discover_url, headers, payload)
134
+
135
+ if self.api_key:
136
+ # Send app details to Pebblo cloud if api_key is present
137
+ headers = self._make_headers(cloud_request=True)
138
+ if pebblo_resp:
139
+ pebblo_server_version = json.loads(pebblo_resp.text).get(
140
+ "pebblo_server_version"
141
+ )
142
+ payload.update({"pebblo_server_version": pebblo_server_version})
143
+
144
+ payload.update({"pebblo_client_version": PLUGIN_VERSION})
145
+ pebblo_cloud_url = f"{self.cloud_url}{Routes.retrieval_app_discover.value}"
146
+ _ = self.make_request("POST", pebblo_cloud_url, headers, payload)
147
+
148
+ def send_prompt(
149
+ self,
150
+ app_name: str,
151
+ retriever: VectorStoreRetriever,
152
+ question: str,
153
+ answer: str,
154
+ auth_context: Optional[AuthContext],
155
+ docs: List[Document],
156
+ prompt_entities: Dict[str, Any],
157
+ prompt_time: str,
158
+ prompt_gov_enabled: bool = False,
159
+ ) -> None:
160
+ """
161
+ Send prompt to Pebblo server for classification.
162
+ Then send prompt to Daxa cloud(If api_key is present).
163
+
164
+ Args:
165
+ app_name (str): Name of the app.
166
+ retriever (VectorStoreRetriever): Retriever instance.
167
+ question (str): Question asked in the prompt.
168
+ answer (str): Answer generated by the model.
169
+ auth_context (Optional[AuthContext]): Authentication context.
170
+ docs (List[Document]): List of documents retrieved.
171
+ prompt_entities (Dict[str, Any]): Entities present in the prompt.
172
+ prompt_time (str): Time when the prompt was generated.
173
+ prompt_gov_enabled (bool): Whether prompt governance is enabled.
174
+ """
175
+ pebblo_resp = None
176
+ payload = self.build_prompt_qa_payload(
177
+ app_name,
178
+ retriever,
179
+ question,
180
+ answer,
181
+ auth_context,
182
+ docs,
183
+ prompt_entities,
184
+ prompt_time,
185
+ prompt_gov_enabled,
186
+ )
187
+
188
+ if self.classifier_location == "local":
189
+ # Send prompt to local classifier
190
+ headers = self._make_headers()
191
+ prompt_url = f"{self.classifier_url}{Routes.prompt.value}"
192
+ pebblo_resp = self.make_request("POST", prompt_url, headers, payload)
193
+
194
+ if self.api_key:
195
+ # Send prompt to Pebblo cloud if api_key is present
196
+ if self.classifier_location == "local":
197
+ # If classifier location is local, then response, context and prompt
198
+ # should be fetched from pebblo_resp and replaced in payload.
199
+ pebblo_resp = pebblo_resp.json() if pebblo_resp else None
200
+ self.update_cloud_payload(payload, pebblo_resp)
201
+
202
+ headers = self._make_headers(cloud_request=True)
203
+ pebblo_cloud_prompt_url = f"{self.cloud_url}{Routes.prompt.value}"
204
+ _ = self.make_request("POST", pebblo_cloud_prompt_url, headers, payload)
205
+ elif self.classifier_location == "pebblo-cloud":
206
+ logger.warning("API key is missing for sending prompt to Pebblo cloud.")
207
+ raise NameError("API key is missing for sending prompt to Pebblo cloud.")
208
+
209
+ async def asend_prompt(
210
+ self,
211
+ app_name: str,
212
+ retriever: VectorStoreRetriever,
213
+ question: str,
214
+ answer: str,
215
+ auth_context: Optional[AuthContext],
216
+ docs: List[Document],
217
+ prompt_entities: Dict[str, Any],
218
+ prompt_time: str,
219
+ prompt_gov_enabled: bool = False,
220
+ ) -> None:
221
+ """
222
+ Send prompt to Pebblo server for classification.
223
+ Then send prompt to Daxa cloud(If api_key is present).
224
+
225
+ Args:
226
+ app_name (str): Name of the app.
227
+ retriever (VectorStoreRetriever): Retriever instance.
228
+ question (str): Question asked in the prompt.
229
+ answer (str): Answer generated by the model.
230
+ auth_context (Optional[AuthContext]): Authentication context.
231
+ docs (List[Document]): List of documents retrieved.
232
+ prompt_entities (Dict[str, Any]): Entities present in the prompt.
233
+ prompt_time (str): Time when the prompt was generated.
234
+ prompt_gov_enabled (bool): Whether prompt governance is enabled.
235
+ """
236
+ pebblo_resp = None
237
+ payload = self.build_prompt_qa_payload(
238
+ app_name,
239
+ retriever,
240
+ question,
241
+ answer,
242
+ auth_context,
243
+ docs,
244
+ prompt_entities,
245
+ prompt_time,
246
+ prompt_gov_enabled,
247
+ )
248
+
249
+ if self.classifier_location == "local":
250
+ # Send prompt to local classifier
251
+ headers = self._make_headers()
252
+ prompt_url = f"{self.classifier_url}{Routes.prompt.value}"
253
+ pebblo_resp = await self.amake_request("POST", prompt_url, headers, payload)
254
+
255
+ if self.api_key:
256
+ # Send prompt to Pebblo cloud if api_key is present
257
+ if self.classifier_location == "local":
258
+ # If classifier location is local, then response, context and prompt
259
+ # should be fetched from pebblo_resp and replaced in payload.
260
+ self.update_cloud_payload(payload, pebblo_resp)
261
+
262
+ headers = self._make_headers(cloud_request=True)
263
+ pebblo_cloud_prompt_url = f"{self.cloud_url}{Routes.prompt.value}"
264
+ _ = await self.amake_request(
265
+ "POST", pebblo_cloud_prompt_url, headers, payload
266
+ )
267
+ elif self.classifier_location == "pebblo-cloud":
268
+ logger.warning("API key is missing for sending prompt to Pebblo cloud.")
269
+ raise NameError("API key is missing for sending prompt to Pebblo cloud.")
270
+
271
+ def check_prompt_validity(self, question: str) -> Tuple[bool, Dict[str, Any]]:
272
+ """
273
+ Check the validity of the given prompt using a remote classification service.
274
+
275
+ This method sends a prompt to a remote classifier service and return entities
276
+ present in prompt or not.
277
+
278
+ Args:
279
+ question (str): The prompt question to be validated.
280
+
281
+ Returns:
282
+ bool: True if the prompt is valid (does not contain deny list entities),
283
+ False otherwise.
284
+ dict: The entities present in the prompt
285
+ """
286
+ prompt_payload = {"prompt": question}
287
+ prompt_entities: dict = {"entities": {}, "entityCount": 0}
288
+ is_valid_prompt: bool = True
289
+ if self.classifier_location == "local":
290
+ headers = self._make_headers()
291
+ prompt_gov_api_url = (
292
+ f"{self.classifier_url}{Routes.prompt_governance.value}"
293
+ )
294
+ pebblo_resp = self.make_request(
295
+ "POST", prompt_gov_api_url, headers, prompt_payload
296
+ )
297
+ if pebblo_resp:
298
+ prompt_entities["entities"] = pebblo_resp.json().get("entities", {})
299
+ prompt_entities["entityCount"] = pebblo_resp.json().get(
300
+ "entityCount", 0
301
+ )
302
+ return is_valid_prompt, prompt_entities
303
+
304
+ async def acheck_prompt_validity(
305
+ self, question: str
306
+ ) -> Tuple[bool, Dict[str, Any]]:
307
+ """
308
+ Check the validity of the given prompt using a remote classification service.
309
+
310
+ This method sends a prompt to a remote classifier service and return entities
311
+ present in prompt or not.
312
+
313
+ Args:
314
+ question (str): The prompt question to be validated.
315
+
316
+ Returns:
317
+ bool: True if the prompt is valid (does not contain deny list entities),
318
+ False otherwise.
319
+ dict: The entities present in the prompt
320
+ """
321
+ prompt_payload = {"prompt": question}
322
+ prompt_entities: dict = {"entities": {}, "entityCount": 0}
323
+ is_valid_prompt: bool = True
324
+ if self.classifier_location == "local":
325
+ headers = self._make_headers()
326
+ prompt_gov_api_url = (
327
+ f"{self.classifier_url}{Routes.prompt_governance.value}"
328
+ )
329
+ pebblo_resp = await self.amake_request(
330
+ "POST", prompt_gov_api_url, headers, prompt_payload
331
+ )
332
+ if pebblo_resp:
333
+ prompt_entities["entities"] = pebblo_resp.get("entities", {})
334
+ prompt_entities["entityCount"] = pebblo_resp.get("entityCount", 0)
335
+ return is_valid_prompt, prompt_entities
336
+
337
+ def _make_headers(self, cloud_request: bool = False) -> dict:
338
+ """
339
+ Generate headers for the request.
340
+
341
+ args:
342
+ cloud_request (bool): flag indicating whether the request is for Pebblo
343
+ cloud.
344
+ returns:
345
+ dict: Headers for the request.
346
+
347
+ """
348
+ headers = {
349
+ "Accept": "application/json",
350
+ "Content-Type": "application/json",
351
+ }
352
+ if cloud_request:
353
+ # Add API key for Pebblo cloud request
354
+ if self.api_key:
355
+ headers.update({"x-api-key": self.api_key})
356
+ else:
357
+ logger.warning("API key is missing for Pebblo cloud request.")
358
+ return headers
359
+
360
+ @staticmethod
361
+ def make_request(
362
+ method: str,
363
+ url: str,
364
+ headers: dict,
365
+ payload: Optional[dict] = None,
366
+ timeout: int = 20,
367
+ ) -> Optional[Response]:
368
+ """
369
+ Make a request to the Pebblo server/cloud API.
370
+
371
+ Args:
372
+ method (str): HTTP method (GET, POST, PUT, DELETE, etc.).
373
+ url (str): URL for the request.
374
+ headers (dict): Headers for the request.
375
+ payload (Optional[dict]): Payload for the request (for POST, PUT, etc.).
376
+ timeout (int): Timeout for the request in seconds.
377
+
378
+ Returns:
379
+ Optional[Response]: Response object if the request is successful.
380
+ """
381
+ try:
382
+ response = request(
383
+ method=method, url=url, headers=headers, json=payload, timeout=timeout
384
+ )
385
+ logger.debug(
386
+ "Request: method %s, url %s, len %s response status %s",
387
+ method,
388
+ response.request.url,
389
+ str(len(response.request.body if response.request.body else [])),
390
+ str(response.status_code),
391
+ )
392
+
393
+ if response.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR:
394
+ logger.warning(f"Pebblo Server: Error {response.status_code}")
395
+ elif response.status_code >= HTTPStatus.BAD_REQUEST:
396
+ logger.warning(f"Pebblo received an invalid payload: {response.text}")
397
+ elif response.status_code != HTTPStatus.OK:
398
+ logger.warning(
399
+ f"Pebblo returned an unexpected response code: "
400
+ f"{response.status_code}"
401
+ )
402
+
403
+ return response
404
+ except RequestException:
405
+ logger.warning("Unable to reach server %s", url)
406
+ except Exception as e:
407
+ logger.warning("An Exception caught in make_request: %s", e)
408
+ return None
409
+
410
+ @staticmethod
411
+ def update_cloud_payload(payload: dict, pebblo_resp: Optional[dict]) -> None:
412
+ """
413
+ Update the payload with response, prompt and context from Pebblo response.
414
+
415
+ Args:
416
+ payload (dict): Payload to be updated.
417
+ pebblo_resp (Optional[dict]): Response from Pebblo server.
418
+ """
419
+ if pebblo_resp:
420
+ # Update response, prompt and context from pebblo response
421
+ response = payload.get("response", {})
422
+ response.update(pebblo_resp.get("retrieval_data", {}).get("response", {}))
423
+ response.pop("data", None)
424
+ prompt = payload.get("prompt", {})
425
+ prompt.update(pebblo_resp.get("retrieval_data", {}).get("prompt", {}))
426
+ prompt.pop("data", None)
427
+ context = payload.get("context", [])
428
+ for context_data in context:
429
+ context_data.pop("doc", None)
430
+ else:
431
+ payload["response"] = {}
432
+ payload["prompt"] = {}
433
+ payload["context"] = []
434
+
435
+ @staticmethod
436
+ async def amake_request(
437
+ method: str,
438
+ url: str,
439
+ headers: dict,
440
+ payload: Optional[dict] = None,
441
+ timeout: int = 20,
442
+ ) -> Any:
443
+ """
444
+ Make a async request to the Pebblo server/cloud API.
445
+
446
+ Args:
447
+ method (str): HTTP method (GET, POST, PUT, DELETE, etc.).
448
+ url (str): URL for the request.
449
+ headers (dict): Headers for the request.
450
+ payload (Optional[dict]): Payload for the request (for POST, PUT, etc.).
451
+ timeout (int): Timeout for the request in seconds.
452
+
453
+ Returns:
454
+ Any: Response json if the request is successful.
455
+ """
456
+ try:
457
+ client_timeout = ClientTimeout(total=timeout)
458
+ async with aiohttp.ClientSession() as asession:
459
+ async with asession.request(
460
+ method=method,
461
+ url=url,
462
+ json=payload,
463
+ headers=headers,
464
+ timeout=client_timeout,
465
+ ) as response:
466
+ if response.status >= HTTPStatus.INTERNAL_SERVER_ERROR:
467
+ logger.warning(f"Pebblo Server: Error {response.status}")
468
+ elif response.status >= HTTPStatus.BAD_REQUEST:
469
+ logger.warning(
470
+ f"Pebblo received an invalid payload: {response.text}"
471
+ )
472
+ elif response.status != HTTPStatus.OK:
473
+ logger.warning(
474
+ f"Pebblo returned an unexpected response code: "
475
+ f"{response.status}"
476
+ )
477
+ response_json = await response.json()
478
+ return response_json
479
+ except RequestException:
480
+ logger.warning("Unable to reach server %s", url)
481
+ except Exception as e:
482
+ logger.warning("An Exception caught in amake_request: %s", e)
483
+ return None
484
+
485
+ def build_prompt_qa_payload(
486
+ self,
487
+ app_name: str,
488
+ retriever: VectorStoreRetriever,
489
+ question: str,
490
+ answer: str,
491
+ auth_context: Optional[AuthContext],
492
+ docs: List[Document],
493
+ prompt_entities: Dict[str, Any],
494
+ prompt_time: str,
495
+ prompt_gov_enabled: bool = False,
496
+ ) -> dict:
497
+ """
498
+ Build the QA payload for the prompt.
499
+
500
+ Args:
501
+ app_name (str): Name of the app.
502
+ retriever (VectorStoreRetriever): Retriever instance.
503
+ question (str): Question asked in the prompt.
504
+ answer (str): Answer generated by the model.
505
+ auth_context (Optional[AuthContext]): Authentication context.
506
+ docs (List[Document]): List of documents retrieved.
507
+ prompt_entities (Dict[str, Any]): Entities present in the prompt.
508
+ prompt_time (str): Time when the prompt was generated.
509
+ prompt_gov_enabled (bool): Whether prompt governance is enabled.
510
+
511
+ Returns:
512
+ dict: The QA payload for the prompt.
513
+ """
514
+ qa = Qa(
515
+ name=app_name,
516
+ context=[
517
+ Context(
518
+ retrieved_from=doc.metadata.get(
519
+ "full_path", doc.metadata.get("source")
520
+ ),
521
+ doc=doc.page_content,
522
+ vector_db=retriever.vectorstore.__class__.__name__,
523
+ pb_checksum=doc.metadata.get("pb_checksum"),
524
+ )
525
+ for doc in docs
526
+ if isinstance(doc, Document)
527
+ ],
528
+ prompt=Prompt(
529
+ data=question,
530
+ entities=prompt_entities.get("entities", {}),
531
+ entityCount=prompt_entities.get("entityCount", 0),
532
+ prompt_gov_enabled=prompt_gov_enabled,
533
+ ),
534
+ response=Prompt(data=answer),
535
+ prompt_time=prompt_time,
536
+ user=auth_context.user_id if auth_context else "unknown",
537
+ user_identities=auth_context.user_auth
538
+ if auth_context and hasattr(auth_context, "user_auth")
539
+ else [],
540
+ classifier_location=self.classifier_location,
541
+ )
542
+ return qa.dict(exclude_unset=True)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (2.83 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/base.cpython-311.pyc ADDED
Binary file (328 Bytes). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/facebook_messenger.cpython-311.pyc ADDED
Binary file (5.19 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/gmail.cpython-311.pyc ADDED
Binary file (6.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/imessage.cpython-311.pyc ADDED
Binary file (9.9 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/langsmith.cpython-311.pyc ADDED
Binary file (8.65 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/slack.cpython-311.pyc ADDED
Binary file (5.26 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/telegram.cpython-311.pyc ADDED
Binary file (8.42 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/utils.cpython-311.pyc ADDED
Binary file (4.78 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__pycache__/whatsapp.cpython-311.pyc ADDED
Binary file (6.62 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (6.05 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/__pycache__/astradb.cpython-311.pyc ADDED
Binary file (9.53 kB). View file