codekingpro commited on
Commit
357b371
·
verified ·
1 Parent(s): 1ad1ea4

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/adapters/__init__.py +8 -0
  2. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/adapters/openai.py +421 -0
  3. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/__init__.py +170 -0
  4. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_ai_services.py +31 -0
  5. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_cognitive_services.py +34 -0
  6. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/base.py +5 -0
  7. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/load_tools.py +771 -0
  8. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agents/__init__.py +0 -0
  9. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/__init__.py +157 -0
  10. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/aim_callback.py +434 -0
  11. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/argilla_callback.py +349 -0
  12. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arize_callback.py +213 -0
  13. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arthur_callback.py +297 -0
  14. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/bedrock_anthropic_callback.py +135 -0
  15. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/clearml_callback.py +518 -0
  16. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/comet_ml_callback.py +639 -0
  17. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/confident_callback.py +183 -0
  18. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/context_callback.py +192 -0
  19. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/fiddler_callback.py +335 -0
  20. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/flyte_callback.py +364 -0
  21. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/human.py +88 -0
  22. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/infino_callback.py +251 -0
  23. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/labelstudio_callback.py +390 -0
  24. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/llmonitor_callback.py +681 -0
  25. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/manager.py +104 -0
  26. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/mlflow_callback.py +769 -0
  27. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/openai_info.py +555 -0
  28. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/promptlayer_callback.py +163 -0
  29. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/sagemaker_callback.py +277 -0
  30. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/trubrics_callback.py +125 -0
  31. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/upstash_ratelimit_callback.py +206 -0
  32. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/uptrain_callback.py +384 -0
  33. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/utils.py +239 -0
  34. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/wandb_callback.py +597 -0
  35. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/whylabs_callback.py +187 -0
  36. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/__init__.py +24 -0
  37. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/llm_requests.py +98 -0
  38. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__init__.py +83 -0
  39. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/base.py +3 -0
  40. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/facebook_messenger.py +78 -0
  41. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/gmail.py +117 -0
  42. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/imessage.py +221 -0
  43. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/langsmith.py +159 -0
  44. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/slack.py +87 -0
  45. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/telegram.py +155 -0
  46. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/utils.py +104 -0
  47. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/whatsapp.py +119 -0
  48. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/__init__.py +149 -0
  49. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/astradb.py +162 -0
  50. micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/cassandra.py +130 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/adapters/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """**Adapters** are used to adapt LangChain models to other APIs.
2
+
3
+ LangChain integrates with many model providers.
4
+ While LangChain has its own message and model APIs,
5
+ LangChain has also made it as easy as
6
+ possible to explore other models by exposing an **adapter** to adapt LangChain
7
+ models to the other APIs, as to the OpenAI API.
8
+ """
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/adapters/openai.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ from typing import (
5
+ Any,
6
+ AsyncIterator,
7
+ Dict,
8
+ Iterable,
9
+ List,
10
+ Mapping,
11
+ Sequence,
12
+ Union,
13
+ overload,
14
+ )
15
+
16
+ from langchain_core.chat_sessions import ChatSession
17
+ from langchain_core.messages import (
18
+ AIMessage,
19
+ AIMessageChunk,
20
+ BaseMessage,
21
+ BaseMessageChunk,
22
+ ChatMessage,
23
+ FunctionMessage,
24
+ HumanMessage,
25
+ SystemMessage,
26
+ ToolMessage,
27
+ )
28
+ from pydantic import BaseModel
29
+ from typing_extensions import Literal
30
+
31
+
32
+ async def aenumerate(
33
+ iterable: AsyncIterator[Any], start: int = 0
34
+ ) -> AsyncIterator[tuple[int, Any]]:
35
+ """Async version of enumerate function."""
36
+ i = start
37
+ async for x in iterable:
38
+ yield i, x
39
+ i += 1
40
+
41
+
42
+ class IndexableBaseModel(BaseModel):
43
+ """Allows a BaseModel to return its fields by string variable indexing."""
44
+
45
+ def __getitem__(self, item: str) -> Any:
46
+ return getattr(self, item)
47
+
48
+
49
+ class Choice(IndexableBaseModel):
50
+ """Choice."""
51
+
52
+ message: dict
53
+
54
+
55
+ class ChatCompletions(IndexableBaseModel):
56
+ """Chat completions."""
57
+
58
+ choices: List[Choice]
59
+
60
+
61
+ class ChoiceChunk(IndexableBaseModel):
62
+ """Choice chunk."""
63
+
64
+ delta: dict
65
+
66
+
67
+ class ChatCompletionChunk(IndexableBaseModel):
68
+ """Chat completion chunk."""
69
+
70
+ choices: List[ChoiceChunk]
71
+
72
+
73
+ def convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
74
+ """Convert a dictionary to a LangChain message.
75
+
76
+ Args:
77
+ _dict: The dictionary.
78
+
79
+ Returns:
80
+ The LangChain message.
81
+ """
82
+ role = _dict.get("role")
83
+ if role == "user":
84
+ return HumanMessage(content=_dict.get("content", ""))
85
+ elif role == "assistant":
86
+ # Fix for azure
87
+ # Also OpenAI returns None for tool invocations
88
+ content = _dict.get("content", "") or ""
89
+ additional_kwargs: Dict = {}
90
+ if function_call := _dict.get("function_call"):
91
+ additional_kwargs["function_call"] = dict(function_call)
92
+ if tool_calls := _dict.get("tool_calls"):
93
+ additional_kwargs["tool_calls"] = tool_calls
94
+ if context := _dict.get("context"):
95
+ additional_kwargs["context"] = context
96
+ return AIMessage(content=content, additional_kwargs=additional_kwargs)
97
+ elif role == "system":
98
+ return SystemMessage(content=_dict.get("content", ""))
99
+ elif role == "function":
100
+ return FunctionMessage(content=_dict.get("content", ""), name=_dict.get("name")) # type: ignore[arg-type]
101
+ elif role == "tool":
102
+ additional_kwargs = {}
103
+ if "name" in _dict:
104
+ additional_kwargs["name"] = _dict["name"]
105
+ return ToolMessage(
106
+ content=_dict.get("content", ""),
107
+ tool_call_id=_dict.get("tool_call_id"),
108
+ additional_kwargs=additional_kwargs,
109
+ )
110
+ else:
111
+ return ChatMessage(content=_dict.get("content", ""), role=role) # type: ignore[arg-type]
112
+
113
+
114
+ def convert_message_to_dict(message: BaseMessage) -> dict:
115
+ """Convert a LangChain message to a dictionary.
116
+
117
+ Args:
118
+ message: The LangChain message.
119
+
120
+ Returns:
121
+ The dictionary.
122
+ """
123
+ message_dict: Dict[str, Any]
124
+ if isinstance(message, ChatMessage):
125
+ message_dict = {"role": message.role, "content": message.content}
126
+ elif isinstance(message, HumanMessage):
127
+ message_dict = {"role": "user", "content": message.content}
128
+ elif isinstance(message, AIMessage):
129
+ message_dict = {"role": "assistant", "content": message.content}
130
+ if "function_call" in message.additional_kwargs:
131
+ message_dict["function_call"] = message.additional_kwargs["function_call"]
132
+ # If function call only, content is None not empty string
133
+ if message_dict["content"] == "":
134
+ message_dict["content"] = None
135
+ if "tool_calls" in message.additional_kwargs:
136
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
137
+ # If tool calls only, content is None not empty string
138
+ if message_dict["content"] == "":
139
+ message_dict["content"] = None
140
+ if "context" in message.additional_kwargs:
141
+ message_dict["context"] = message.additional_kwargs["context"]
142
+ # If context only, content is None not empty string
143
+ if message_dict["content"] == "":
144
+ message_dict["content"] = None
145
+ elif isinstance(message, SystemMessage):
146
+ message_dict = {"role": "system", "content": message.content}
147
+ elif isinstance(message, FunctionMessage):
148
+ message_dict = {
149
+ "role": "function",
150
+ "content": message.content,
151
+ "name": message.name,
152
+ }
153
+ elif isinstance(message, ToolMessage):
154
+ message_dict = {
155
+ "role": "tool",
156
+ "content": message.content,
157
+ "tool_call_id": message.tool_call_id,
158
+ }
159
+ else:
160
+ raise TypeError(f"Got unknown type {message}")
161
+ if "name" in message.additional_kwargs:
162
+ message_dict["name"] = message.additional_kwargs["name"]
163
+ return message_dict
164
+
165
+
166
+ def convert_openai_messages(messages: Sequence[Dict[str, Any]]) -> List[BaseMessage]:
167
+ """Convert dictionaries representing OpenAI messages to LangChain format.
168
+
169
+ Args:
170
+ messages: List of dictionaries representing OpenAI messages
171
+
172
+ Returns:
173
+ List of LangChain BaseMessage objects.
174
+ """
175
+ return [convert_dict_to_message(m) for m in messages]
176
+
177
+
178
+ def _convert_message_chunk(chunk: BaseMessageChunk, i: int) -> dict:
179
+ _dict: Dict[str, Any] = {}
180
+ if isinstance(chunk, AIMessageChunk):
181
+ if i == 0:
182
+ # Only shows up in the first chunk
183
+ _dict["role"] = "assistant"
184
+ if "function_call" in chunk.additional_kwargs:
185
+ _dict["function_call"] = chunk.additional_kwargs["function_call"]
186
+ # If the first chunk is a function call, the content is not empty string,
187
+ # not missing, but None.
188
+ if i == 0:
189
+ _dict["content"] = None
190
+ if "tool_calls" in chunk.additional_kwargs:
191
+ _dict["tool_calls"] = chunk.additional_kwargs["tool_calls"]
192
+ # If the first chunk is tool calls, the content is not empty string,
193
+ # not missing, but None.
194
+ if i == 0:
195
+ _dict["content"] = None
196
+ else:
197
+ _dict["content"] = chunk.content
198
+ else:
199
+ raise ValueError(f"Got unexpected streaming chunk type: {type(chunk)}")
200
+ # This only happens at the end of streams, and OpenAI returns as empty dict
201
+ if _dict == {"content": ""}:
202
+ _dict = {}
203
+ return _dict
204
+
205
+
206
+ def _convert_message_chunk_to_delta(chunk: BaseMessageChunk, i: int) -> Dict[str, Any]:
207
+ _dict = _convert_message_chunk(chunk, i)
208
+ return {"choices": [{"delta": _dict}]}
209
+
210
+
211
+ class ChatCompletion:
212
+ """Chat completion."""
213
+
214
+ @overload
215
+ @staticmethod
216
+ def create(
217
+ messages: Sequence[Dict[str, Any]],
218
+ *,
219
+ provider: str = "ChatOpenAI",
220
+ stream: Literal[False] = False,
221
+ **kwargs: Any,
222
+ ) -> dict: ...
223
+
224
+ @overload
225
+ @staticmethod
226
+ def create(
227
+ messages: Sequence[Dict[str, Any]],
228
+ *,
229
+ provider: str = "ChatOpenAI",
230
+ stream: Literal[True],
231
+ **kwargs: Any,
232
+ ) -> Iterable: ...
233
+
234
+ @staticmethod
235
+ def create(
236
+ messages: Sequence[Dict[str, Any]],
237
+ *,
238
+ provider: str = "ChatOpenAI",
239
+ stream: bool = False,
240
+ **kwargs: Any,
241
+ ) -> Union[dict, Iterable]:
242
+ models = importlib.import_module("langchain.chat_models")
243
+ model_cls = getattr(models, provider)
244
+ model_config = model_cls(**kwargs)
245
+ converted_messages = convert_openai_messages(messages)
246
+ if not stream:
247
+ result = model_config.invoke(converted_messages)
248
+ return {"choices": [{"message": convert_message_to_dict(result)}]}
249
+ else:
250
+ return (
251
+ _convert_message_chunk_to_delta(c, i)
252
+ for i, c in enumerate(model_config.stream(converted_messages))
253
+ )
254
+
255
+ @overload
256
+ @staticmethod
257
+ async def acreate(
258
+ messages: Sequence[Dict[str, Any]],
259
+ *,
260
+ provider: str = "ChatOpenAI",
261
+ stream: Literal[False] = False,
262
+ **kwargs: Any,
263
+ ) -> dict: ...
264
+
265
+ @overload
266
+ @staticmethod
267
+ async def acreate(
268
+ messages: Sequence[Dict[str, Any]],
269
+ *,
270
+ provider: str = "ChatOpenAI",
271
+ stream: Literal[True],
272
+ **kwargs: Any,
273
+ ) -> AsyncIterator: ...
274
+
275
+ @staticmethod
276
+ async def acreate(
277
+ messages: Sequence[Dict[str, Any]],
278
+ *,
279
+ provider: str = "ChatOpenAI",
280
+ stream: bool = False,
281
+ **kwargs: Any,
282
+ ) -> Union[dict, AsyncIterator]:
283
+ models = importlib.import_module("langchain.chat_models")
284
+ model_cls = getattr(models, provider)
285
+ model_config = model_cls(**kwargs)
286
+ converted_messages = convert_openai_messages(messages)
287
+ if not stream:
288
+ result = await model_config.ainvoke(converted_messages)
289
+ return {"choices": [{"message": convert_message_to_dict(result)}]}
290
+ else:
291
+ return (
292
+ _convert_message_chunk_to_delta(c, i)
293
+ async for i, c in aenumerate(model_config.astream(converted_messages))
294
+ )
295
+
296
+
297
+ def _has_assistant_message(session: ChatSession) -> bool:
298
+ """Check if chat session has an assistant message."""
299
+ return any([isinstance(m, AIMessage) for m in session["messages"]])
300
+
301
+
302
+ def convert_messages_for_finetuning(
303
+ sessions: Iterable[ChatSession],
304
+ ) -> List[List[dict]]:
305
+ """Convert messages to a list of lists of dictionaries for fine-tuning.
306
+
307
+ Args:
308
+ sessions: The chat sessions.
309
+
310
+ Returns:
311
+ The list of lists of dictionaries.
312
+ """
313
+ return [
314
+ [convert_message_to_dict(s) for s in session["messages"]]
315
+ for session in sessions
316
+ if _has_assistant_message(session)
317
+ ]
318
+
319
+
320
+ class Completions:
321
+ """Completions."""
322
+
323
+ @overload
324
+ @staticmethod
325
+ def create(
326
+ messages: Sequence[Dict[str, Any]],
327
+ *,
328
+ provider: str = "ChatOpenAI",
329
+ stream: Literal[False] = False,
330
+ **kwargs: Any,
331
+ ) -> ChatCompletions: ...
332
+
333
+ @overload
334
+ @staticmethod
335
+ def create(
336
+ messages: Sequence[Dict[str, Any]],
337
+ *,
338
+ provider: str = "ChatOpenAI",
339
+ stream: Literal[True],
340
+ **kwargs: Any,
341
+ ) -> Iterable: ...
342
+
343
+ @staticmethod
344
+ def create(
345
+ messages: Sequence[Dict[str, Any]],
346
+ *,
347
+ provider: str = "ChatOpenAI",
348
+ stream: bool = False,
349
+ **kwargs: Any,
350
+ ) -> Union[ChatCompletions, Iterable]:
351
+ models = importlib.import_module("langchain.chat_models")
352
+ model_cls = getattr(models, provider)
353
+ model_config = model_cls(**kwargs)
354
+ converted_messages = convert_openai_messages(messages)
355
+ if not stream:
356
+ result = model_config.invoke(converted_messages)
357
+ return ChatCompletions(
358
+ choices=[Choice(message=convert_message_to_dict(result))]
359
+ )
360
+ else:
361
+ return (
362
+ ChatCompletionChunk(
363
+ choices=[ChoiceChunk(delta=_convert_message_chunk(c, i))]
364
+ )
365
+ for i, c in enumerate(model_config.stream(converted_messages))
366
+ )
367
+
368
+ @overload
369
+ @staticmethod
370
+ async def acreate(
371
+ messages: Sequence[Dict[str, Any]],
372
+ *,
373
+ provider: str = "ChatOpenAI",
374
+ stream: Literal[False] = False,
375
+ **kwargs: Any,
376
+ ) -> ChatCompletions: ...
377
+
378
+ @overload
379
+ @staticmethod
380
+ async def acreate(
381
+ messages: Sequence[Dict[str, Any]],
382
+ *,
383
+ provider: str = "ChatOpenAI",
384
+ stream: Literal[True],
385
+ **kwargs: Any,
386
+ ) -> AsyncIterator: ...
387
+
388
+ @staticmethod
389
+ async def acreate(
390
+ messages: Sequence[Dict[str, Any]],
391
+ *,
392
+ provider: str = "ChatOpenAI",
393
+ stream: bool = False,
394
+ **kwargs: Any,
395
+ ) -> Union[ChatCompletions, AsyncIterator]:
396
+ models = importlib.import_module("langchain.chat_models")
397
+ model_cls = getattr(models, provider)
398
+ model_config = model_cls(**kwargs)
399
+ converted_messages = convert_openai_messages(messages)
400
+ if not stream:
401
+ result = await model_config.ainvoke(converted_messages)
402
+ return ChatCompletions(
403
+ choices=[Choice(message=convert_message_to_dict(result))]
404
+ )
405
+ else:
406
+ return (
407
+ ChatCompletionChunk(
408
+ choices=[ChoiceChunk(delta=_convert_message_chunk(c, i))]
409
+ )
410
+ async for i, c in aenumerate(model_config.astream(converted_messages))
411
+ )
412
+
413
+
414
+ class Chat:
415
+ """Chat."""
416
+
417
+ def __init__(self) -> None:
418
+ self.completions = Completions()
419
+
420
+
421
+ chat = Chat()
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/__init__.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """**Toolkits** are sets of tools that can be used to interact with
2
+ various services and APIs.
3
+ """
4
+
5
+ import importlib
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ if TYPE_CHECKING:
9
+ from langchain_community.agent_toolkits.ainetwork.toolkit import (
10
+ AINetworkToolkit,
11
+ )
12
+ from langchain_community.agent_toolkits.amadeus.toolkit import (
13
+ AmadeusToolkit,
14
+ )
15
+ from langchain_community.agent_toolkits.azure_ai_services import (
16
+ AzureAiServicesToolkit,
17
+ )
18
+ from langchain_community.agent_toolkits.azure_cognitive_services import (
19
+ AzureCognitiveServicesToolkit,
20
+ )
21
+ from langchain_community.agent_toolkits.cassandra_database.toolkit import (
22
+ CassandraDatabaseToolkit, # noqa: F401
23
+ )
24
+ from langchain_community.agent_toolkits.cogniswitch.toolkit import (
25
+ CogniswitchToolkit,
26
+ )
27
+ from langchain_community.agent_toolkits.connery import (
28
+ ConneryToolkit,
29
+ )
30
+ from langchain_community.agent_toolkits.file_management.toolkit import (
31
+ FileManagementToolkit,
32
+ )
33
+ from langchain_community.agent_toolkits.gmail.toolkit import (
34
+ GmailToolkit,
35
+ )
36
+ from langchain_community.agent_toolkits.jira.toolkit import (
37
+ JiraToolkit,
38
+ )
39
+ from langchain_community.agent_toolkits.json.base import (
40
+ create_json_agent,
41
+ )
42
+ from langchain_community.agent_toolkits.json.toolkit import (
43
+ JsonToolkit,
44
+ )
45
+ from langchain_community.agent_toolkits.multion.toolkit import (
46
+ MultionToolkit,
47
+ )
48
+ from langchain_community.agent_toolkits.nasa.toolkit import (
49
+ NasaToolkit,
50
+ )
51
+ from langchain_community.agent_toolkits.nla.toolkit import (
52
+ NLAToolkit,
53
+ )
54
+ from langchain_community.agent_toolkits.office365.toolkit import (
55
+ O365Toolkit,
56
+ )
57
+ from langchain_community.agent_toolkits.openapi.base import (
58
+ create_openapi_agent,
59
+ )
60
+ from langchain_community.agent_toolkits.openapi.toolkit import (
61
+ OpenAPIToolkit,
62
+ )
63
+ from langchain_community.agent_toolkits.playwright.toolkit import (
64
+ PlayWrightBrowserToolkit,
65
+ )
66
+ from langchain_community.agent_toolkits.polygon.toolkit import (
67
+ PolygonToolkit,
68
+ )
69
+ from langchain_community.agent_toolkits.powerbi.base import (
70
+ create_pbi_agent,
71
+ )
72
+ from langchain_community.agent_toolkits.powerbi.chat_base import (
73
+ create_pbi_chat_agent,
74
+ )
75
+ from langchain_community.agent_toolkits.powerbi.toolkit import (
76
+ PowerBIToolkit,
77
+ )
78
+ from langchain_community.agent_toolkits.slack.toolkit import (
79
+ SlackToolkit,
80
+ )
81
+ from langchain_community.agent_toolkits.spark_sql.base import (
82
+ create_spark_sql_agent,
83
+ )
84
+ from langchain_community.agent_toolkits.spark_sql.toolkit import (
85
+ SparkSQLToolkit,
86
+ )
87
+ from langchain_community.agent_toolkits.sql.base import (
88
+ create_sql_agent,
89
+ )
90
+ from langchain_community.agent_toolkits.sql.toolkit import (
91
+ SQLDatabaseToolkit,
92
+ )
93
+ from langchain_community.agent_toolkits.steam.toolkit import (
94
+ SteamToolkit,
95
+ )
96
+ from langchain_community.agent_toolkits.zapier.toolkit import (
97
+ ZapierToolkit,
98
+ )
99
+
100
+ __all__ = [
101
+ "AINetworkToolkit",
102
+ "AmadeusToolkit",
103
+ "AzureAiServicesToolkit",
104
+ "AzureCognitiveServicesToolkit",
105
+ "CogniswitchToolkit",
106
+ "ConneryToolkit",
107
+ "FileManagementToolkit",
108
+ "GmailToolkit",
109
+ "JiraToolkit",
110
+ "JsonToolkit",
111
+ "MultionToolkit",
112
+ "NLAToolkit",
113
+ "NasaToolkit",
114
+ "O365Toolkit",
115
+ "OpenAPIToolkit",
116
+ "PlayWrightBrowserToolkit",
117
+ "PolygonToolkit",
118
+ "PowerBIToolkit",
119
+ "SQLDatabaseToolkit",
120
+ "SlackToolkit",
121
+ "SparkSQLToolkit",
122
+ "SteamToolkit",
123
+ "ZapierToolkit",
124
+ "create_json_agent",
125
+ "create_openapi_agent",
126
+ "create_pbi_agent",
127
+ "create_pbi_chat_agent",
128
+ "create_spark_sql_agent",
129
+ "create_sql_agent",
130
+ ]
131
+
132
+
133
+ _module_lookup = {
134
+ "AINetworkToolkit": "langchain_community.agent_toolkits.ainetwork.toolkit",
135
+ "AmadeusToolkit": "langchain_community.agent_toolkits.amadeus.toolkit",
136
+ "AzureAiServicesToolkit": "langchain_community.agent_toolkits.azure_ai_services",
137
+ "AzureCognitiveServicesToolkit": "langchain_community.agent_toolkits.azure_cognitive_services", # noqa: E501
138
+ "CogniswitchToolkit": "langchain_community.agent_toolkits.cogniswitch.toolkit",
139
+ "ConneryToolkit": "langchain_community.agent_toolkits.connery",
140
+ "FileManagementToolkit": "langchain_community.agent_toolkits.file_management.toolkit", # noqa: E501
141
+ "GmailToolkit": "langchain_community.agent_toolkits.gmail.toolkit",
142
+ "JiraToolkit": "langchain_community.agent_toolkits.jira.toolkit",
143
+ "JsonToolkit": "langchain_community.agent_toolkits.json.toolkit",
144
+ "MultionToolkit": "langchain_community.agent_toolkits.multion.toolkit",
145
+ "NLAToolkit": "langchain_community.agent_toolkits.nla.toolkit",
146
+ "NasaToolkit": "langchain_community.agent_toolkits.nasa.toolkit",
147
+ "O365Toolkit": "langchain_community.agent_toolkits.office365.toolkit",
148
+ "OpenAPIToolkit": "langchain_community.agent_toolkits.openapi.toolkit",
149
+ "PlayWrightBrowserToolkit": "langchain_community.agent_toolkits.playwright.toolkit",
150
+ "PolygonToolkit": "langchain_community.agent_toolkits.polygon.toolkit",
151
+ "PowerBIToolkit": "langchain_community.agent_toolkits.powerbi.toolkit",
152
+ "SQLDatabaseToolkit": "langchain_community.agent_toolkits.sql.toolkit",
153
+ "SlackToolkit": "langchain_community.agent_toolkits.slack.toolkit",
154
+ "SparkSQLToolkit": "langchain_community.agent_toolkits.spark_sql.toolkit",
155
+ "SteamToolkit": "langchain_community.agent_toolkits.steam.toolkit",
156
+ "ZapierToolkit": "langchain_community.agent_toolkits.zapier.toolkit",
157
+ "create_json_agent": "langchain_community.agent_toolkits.json.base",
158
+ "create_openapi_agent": "langchain_community.agent_toolkits.openapi.base",
159
+ "create_pbi_agent": "langchain_community.agent_toolkits.powerbi.base",
160
+ "create_pbi_chat_agent": "langchain_community.agent_toolkits.powerbi.chat_base",
161
+ "create_spark_sql_agent": "langchain_community.agent_toolkits.spark_sql.base",
162
+ "create_sql_agent": "langchain_community.agent_toolkits.sql.base",
163
+ }
164
+
165
+
166
+ def __getattr__(name: str) -> Any:
167
+ if name in _module_lookup:
168
+ module = importlib.import_module(_module_lookup[name])
169
+ return getattr(module, name)
170
+ raise AttributeError(f"module {__name__} has no attribute {name}")
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_ai_services.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import List
4
+
5
+ from langchain_core.tools import BaseTool
6
+ from langchain_core.tools.base import BaseToolkit
7
+
8
+ from langchain_community.tools.azure_ai_services import (
9
+ AzureAiServicesDocumentIntelligenceTool,
10
+ AzureAiServicesImageAnalysisTool,
11
+ AzureAiServicesSpeechToTextTool,
12
+ AzureAiServicesTextAnalyticsForHealthTool,
13
+ AzureAiServicesTextToSpeechTool,
14
+ )
15
+
16
+
17
+ class AzureAiServicesToolkit(BaseToolkit):
18
+ """Toolkit for Azure AI Services."""
19
+
20
+ def get_tools(self) -> List[BaseTool]:
21
+ """Get the tools in the toolkit."""
22
+
23
+ tools: List[BaseTool] = [
24
+ AzureAiServicesDocumentIntelligenceTool(), # type: ignore[call-arg]
25
+ AzureAiServicesImageAnalysisTool(),
26
+ AzureAiServicesSpeechToTextTool(), # type: ignore[call-arg]
27
+ AzureAiServicesTextToSpeechTool(), # type: ignore[call-arg]
28
+ AzureAiServicesTextAnalyticsForHealthTool(), # type: ignore[call-arg]
29
+ ]
30
+
31
+ return tools
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_cognitive_services.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from typing import List
5
+
6
+ from langchain_core.tools import BaseTool
7
+ from langchain_core.tools.base import BaseToolkit
8
+
9
+ from langchain_community.tools.azure_cognitive_services import (
10
+ AzureCogsFormRecognizerTool,
11
+ AzureCogsImageAnalysisTool,
12
+ AzureCogsSpeech2TextTool,
13
+ AzureCogsText2SpeechTool,
14
+ AzureCogsTextAnalyticsHealthTool,
15
+ )
16
+
17
+
18
+ class AzureCognitiveServicesToolkit(BaseToolkit):
19
+ """Toolkit for Azure Cognitive Services."""
20
+
21
+ def get_tools(self) -> List[BaseTool]:
22
+ """Get the tools in the toolkit."""
23
+
24
+ tools: List[BaseTool] = [
25
+ AzureCogsFormRecognizerTool(), # type: ignore[call-arg]
26
+ AzureCogsSpeech2TextTool(), # type: ignore[call-arg]
27
+ AzureCogsText2SpeechTool(), # type: ignore[call-arg]
28
+ AzureCogsTextAnalyticsHealthTool(), # type: ignore[call-arg]
29
+ ]
30
+
31
+ # TODO: Remove check once azure-ai-vision supports MacOS.
32
+ if sys.platform.startswith("linux") or sys.platform.startswith("win"):
33
+ tools.append(AzureCogsImageAnalysisTool()) # type: ignore[call-arg]
34
+ return tools
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/base.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Toolkits for agents."""
2
+
3
+ from langchain_core.tools.base import BaseToolkit
4
+
5
+ __all__ = ["BaseToolkit"]
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/load_tools.py ADDED
@@ -0,0 +1,771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+ """Tools provide access to various resources and services.
3
+
4
+ LangChain has a large ecosystem of integrations with various external resources
5
+ like local and remote file systems, APIs and databases.
6
+
7
+ These integrations allow developers to create versatile applications that combine the
8
+ power of LLMs with the ability to access, interact with and manipulate external
9
+ resources.
10
+
11
+ When developing an application, developers should inspect the capabilities and
12
+ permissions of the tools that underlie the given agent toolkit, and determine
13
+ whether permissions of the given toolkit are appropriate for the application.
14
+
15
+ See [Security](https://python.langchain.com/docs/security) for more information.
16
+ """
17
+
18
+ import warnings
19
+ from typing import Any, Dict, List, Optional, Callable, Tuple
20
+
21
+ from mypy_extensions import Arg, KwArg
22
+
23
+ from langchain_community.tools.arxiv.tool import ArxivQueryRun
24
+ from langchain_community.tools.bing_search.tool import BingSearchRun
25
+ from langchain_community.tools.dataforseo_api_search import DataForSeoAPISearchResults
26
+ from langchain_community.tools.dataforseo_api_search import DataForSeoAPISearchRun
27
+ from langchain_community.tools.ddg_search.tool import DuckDuckGoSearchRun
28
+ from langchain_community.tools.eleven_labs.text2speech import ElevenLabsText2SpeechTool
29
+ from langchain_community.tools.file_management import ReadFileTool
30
+ from langchain_community.tools.golden_query.tool import GoldenQueryRun
31
+ from langchain_community.tools.google_cloud.texttospeech import (
32
+ GoogleCloudTextToSpeechTool,
33
+ )
34
+ from langchain_community.tools.google_finance.tool import GoogleFinanceQueryRun
35
+ from langchain_community.tools.google_jobs.tool import GoogleJobsQueryRun
36
+ from langchain_community.tools.google_lens.tool import GoogleLensQueryRun
37
+ from langchain_community.tools.google_scholar.tool import GoogleScholarQueryRun
38
+ from langchain_community.tools.google_search.tool import (
39
+ GoogleSearchResults,
40
+ GoogleSearchRun,
41
+ )
42
+ from langchain_community.tools.google_serper.tool import (
43
+ GoogleSerperResults,
44
+ GoogleSerperRun,
45
+ )
46
+ from langchain_community.tools.google_trends.tool import GoogleTrendsQueryRun
47
+ from langchain_community.tools.graphql.tool import BaseGraphQLTool
48
+ from langchain_community.tools.human.tool import HumanInputRun
49
+ from langchain_community.tools.memorize.tool import Memorize
50
+ from langchain_community.tools.merriam_webster.tool import MerriamWebsterQueryRun
51
+ from langchain_community.tools.metaphor_search.tool import MetaphorSearchResults
52
+ from langchain_community.tools.openweathermap.tool import OpenWeatherMapQueryRun
53
+ from langchain_community.tools.pubmed.tool import PubmedQueryRun
54
+ from langchain_community.tools.reddit_search.tool import RedditSearchRun
55
+ from langchain_community.tools.requests.tool import (
56
+ RequestsDeleteTool,
57
+ RequestsGetTool,
58
+ RequestsPatchTool,
59
+ RequestsPostTool,
60
+ RequestsPutTool,
61
+ )
62
+ from langchain_community.tools.scenexplain.tool import SceneXplainTool
63
+ from langchain_community.tools.searchapi.tool import SearchAPIResults, SearchAPIRun
64
+ from langchain_community.tools.searx_search.tool import (
65
+ SearxSearchResults,
66
+ SearxSearchRun,
67
+ )
68
+ from langchain_community.tools.shell.tool import ShellTool
69
+ from langchain_community.tools.sleep.tool import SleepTool
70
+ from langchain_community.tools.stackexchange.tool import StackExchangeTool
71
+ from langchain_community.tools.wikipedia.tool import WikipediaQueryRun
72
+ from langchain_community.tools.wolfram_alpha.tool import WolframAlphaQueryRun
73
+ from langchain_community.utilities.arxiv import ArxivAPIWrapper
74
+ from langchain_community.utilities.awslambda import LambdaWrapper
75
+ from langchain_community.utilities.bing_search import BingSearchAPIWrapper
76
+ from langchain_community.utilities.dalle_image_generator import DallEAPIWrapper
77
+ from langchain_community.utilities.dataforseo_api_search import DataForSeoAPIWrapper
78
+ from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper
79
+ from langchain_community.utilities.golden_query import GoldenQueryAPIWrapper
80
+ from langchain_community.utilities.google_books import GoogleBooksAPIWrapper
81
+ from langchain_community.utilities.google_finance import GoogleFinanceAPIWrapper
82
+ from langchain_community.utilities.google_jobs import GoogleJobsAPIWrapper
83
+ from langchain_community.utilities.google_lens import GoogleLensAPIWrapper
84
+ from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper
85
+ from langchain_community.utilities.google_search import GoogleSearchAPIWrapper
86
+ from langchain_community.utilities.google_serper import GoogleSerperAPIWrapper
87
+ from langchain_community.utilities.google_trends import GoogleTrendsAPIWrapper
88
+ from langchain_community.utilities.graphql import GraphQLAPIWrapper
89
+ from langchain_community.utilities.merriam_webster import MerriamWebsterAPIWrapper
90
+ from langchain_community.utilities.metaphor_search import MetaphorSearchAPIWrapper
91
+ from langchain_community.utilities.openweathermap import OpenWeatherMapAPIWrapper
92
+ from langchain_community.utilities.pubmed import PubMedAPIWrapper
93
+ from langchain_community.utilities.reddit_search import RedditSearchAPIWrapper
94
+ from langchain_community.utilities.requests import TextRequestsWrapper
95
+ from langchain_community.utilities.searchapi import SearchApiAPIWrapper
96
+ from langchain_community.utilities.searx_search import SearxSearchWrapper
97
+ from langchain_community.utilities.serpapi import SerpAPIWrapper
98
+ from langchain_community.utilities.stackexchange import StackExchangeAPIWrapper
99
+ from langchain_community.utilities.twilio import TwilioAPIWrapper
100
+ from langchain_community.utilities.wikipedia import WikipediaAPIWrapper
101
+ from langchain_community.utilities.wolfram_alpha import WolframAlphaAPIWrapper
102
+ from langchain_core.callbacks import BaseCallbackManager
103
+ from langchain_core.callbacks import Callbacks
104
+ from langchain_core.language_models import BaseLanguageModel
105
+ from langchain_core.tools import BaseTool, Tool
106
+
107
+
108
+ def _get_tools_requests_get() -> BaseTool:
109
+ # Dangerous requests are allowed here, because there's another flag that the user
110
+ # has to provide in order to actually opt in.
111
+ # This is a private function and should not be used directly.
112
+ return RequestsGetTool(
113
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
114
+ )
115
+
116
+
117
+ def _get_tools_requests_post() -> BaseTool:
118
+ # Dangerous requests are allowed here, because there's another flag that the user
119
+ # has to provide in order to actually opt in.
120
+ # This is a private function and should not be used directly.
121
+ return RequestsPostTool(
122
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
123
+ )
124
+
125
+
126
+ def _get_tools_requests_patch() -> BaseTool:
127
+ # Dangerous requests are allowed here, because there's another flag that the user
128
+ # has to provide in order to actually opt in.
129
+ # This is a private function and should not be used directly.
130
+ return RequestsPatchTool(
131
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
132
+ )
133
+
134
+
135
+ def _get_tools_requests_put() -> BaseTool:
136
+ # Dangerous requests are allowed here, because there's another flag that the user
137
+ # has to provide in order to actually opt in.
138
+ # This is a private function and should not be used directly.
139
+ return RequestsPutTool(
140
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
141
+ )
142
+
143
+
144
+ def _get_tools_requests_delete() -> BaseTool:
145
+ # Dangerous requests are allowed here, because there's another flag that the user
146
+ # has to provide in order to actually opt in.
147
+ # This is a private function and should not be used directly.
148
+ return RequestsDeleteTool(
149
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
150
+ )
151
+
152
+
153
+ def _get_terminal() -> BaseTool:
154
+ return ShellTool()
155
+
156
+
157
+ def _get_sleep() -> BaseTool:
158
+ return SleepTool()
159
+
160
+
161
+ _BASE_TOOLS: Dict[str, Callable[[], BaseTool]] = {
162
+ "sleep": _get_sleep,
163
+ }
164
+
165
+ DANGEROUS_TOOLS = {
166
+ # Tools that contain some level of risk.
167
+ # Please use with caution and read the documentation of these tools
168
+ # to understand the risks and how to mitigate them.
169
+ # Refer to https://python.langchain.com/docs/security
170
+ # for more information.
171
+ "requests": _get_tools_requests_get, # preserved for backwards compatibility
172
+ "requests_get": _get_tools_requests_get,
173
+ "requests_post": _get_tools_requests_post,
174
+ "requests_patch": _get_tools_requests_patch,
175
+ "requests_put": _get_tools_requests_put,
176
+ "requests_delete": _get_tools_requests_delete,
177
+ "terminal": _get_terminal,
178
+ }
179
+
180
+
181
+ def _get_llm_math(llm: BaseLanguageModel) -> BaseTool:
182
+ try:
183
+ from langchain_classic.chains.llm_math.base import LLMMathChain
184
+ except ImportError:
185
+ raise ImportError(
186
+ "LLM Math tools require the library `langchain` to be installed."
187
+ " Please install it with `pip install langchain`."
188
+ )
189
+ return Tool(
190
+ name="Calculator",
191
+ description="Useful for when you need to answer questions about math.",
192
+ func=LLMMathChain.from_llm(llm=llm).run,
193
+ coroutine=LLMMathChain.from_llm(llm=llm).arun,
194
+ )
195
+
196
+
197
+ def _get_open_meteo_api(llm: BaseLanguageModel) -> BaseTool:
198
+ try:
199
+ from langchain_classic.chains.api.base import APIChain
200
+ from langchain_classic.chains.api import (
201
+ open_meteo_docs,
202
+ )
203
+ except ImportError:
204
+ raise ImportError(
205
+ "API tools require the library `langchain` to be installed."
206
+ " Please install it with `pip install langchain`."
207
+ )
208
+ chain = APIChain.from_llm_and_api_docs(
209
+ llm,
210
+ open_meteo_docs.OPEN_METEO_DOCS,
211
+ limit_to_domains=["https://api.open-meteo.com/"],
212
+ )
213
+ return Tool(
214
+ name="Open-Meteo-API",
215
+ description="Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer.",
216
+ func=chain.run,
217
+ )
218
+
219
+
220
+ _LLM_TOOLS: Dict[str, Callable[[BaseLanguageModel], BaseTool]] = {
221
+ "llm-math": _get_llm_math,
222
+ "open-meteo-api": _get_open_meteo_api,
223
+ }
224
+
225
+
226
+ def _get_news_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
227
+ news_api_key = kwargs["news_api_key"]
228
+ try:
229
+ from langchain_classic.chains.api.base import APIChain
230
+ from langchain_classic.chains.api import (
231
+ news_docs,
232
+ )
233
+ except ImportError:
234
+ raise ImportError(
235
+ "API tools require the library `langchain` to be installed."
236
+ " Please install it with `pip install langchain`."
237
+ )
238
+ chain = APIChain.from_llm_and_api_docs(
239
+ llm,
240
+ news_docs.NEWS_DOCS,
241
+ headers={"X-Api-Key": news_api_key},
242
+ limit_to_domains=["https://newsapi.org/"],
243
+ )
244
+ return Tool(
245
+ name="News-API",
246
+ description="Use this when you want to get information about the top headlines of current news stories. The input should be a question in natural language that this API can answer.",
247
+ func=chain.run,
248
+ )
249
+
250
+
251
+ def _get_tmdb_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
252
+ tmdb_bearer_token = kwargs["tmdb_bearer_token"]
253
+ try:
254
+ from langchain_classic.chains.api.base import APIChain
255
+ from langchain_classic.chains.api import (
256
+ tmdb_docs,
257
+ )
258
+ except ImportError:
259
+ raise ImportError(
260
+ "API tools require the library `langchain` to be installed."
261
+ " Please install it with `pip install langchain`."
262
+ )
263
+ chain = APIChain.from_llm_and_api_docs(
264
+ llm,
265
+ tmdb_docs.TMDB_DOCS,
266
+ headers={"Authorization": f"Bearer {tmdb_bearer_token}"},
267
+ limit_to_domains=["https://api.themoviedb.org/"],
268
+ )
269
+ return Tool(
270
+ name="TMDB-API",
271
+ description="Useful for when you want to get information from The Movie Database. The input should be a question in natural language that this API can answer.",
272
+ func=chain.run,
273
+ )
274
+
275
+
276
+ def _get_podcast_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
277
+ listen_api_key = kwargs["listen_api_key"]
278
+ try:
279
+ from langchain_classic.chains.api.base import APIChain
280
+ from langchain_classic.chains.api import (
281
+ podcast_docs,
282
+ )
283
+ except ImportError:
284
+ raise ImportError(
285
+ "API tools require the library `langchain` to be installed."
286
+ " Please install it with `pip install langchain`."
287
+ )
288
+ chain = APIChain.from_llm_and_api_docs(
289
+ llm,
290
+ podcast_docs.PODCAST_DOCS,
291
+ headers={"X-ListenAPI-Key": listen_api_key},
292
+ limit_to_domains=["https://listen-api.listennotes.com/"],
293
+ )
294
+ return Tool(
295
+ name="Podcast-API",
296
+ description="Use the Listen Notes Podcast API to search all podcasts or episodes. The input should be a question in natural language that this API can answer.",
297
+ func=chain.run,
298
+ )
299
+
300
+
301
+ def _get_lambda_api(**kwargs: Any) -> BaseTool:
302
+ return Tool(
303
+ name=kwargs["awslambda_tool_name"],
304
+ description=kwargs["awslambda_tool_description"],
305
+ func=LambdaWrapper(**kwargs).run,
306
+ )
307
+
308
+
309
+ def _get_wolfram_alpha(**kwargs: Any) -> BaseTool:
310
+ return WolframAlphaQueryRun(api_wrapper=WolframAlphaAPIWrapper(**kwargs))
311
+
312
+
313
+ def _get_google_search(**kwargs: Any) -> BaseTool:
314
+ return GoogleSearchRun(api_wrapper=GoogleSearchAPIWrapper(**kwargs))
315
+
316
+
317
+ def _get_merriam_webster(**kwargs: Any) -> BaseTool:
318
+ return MerriamWebsterQueryRun(api_wrapper=MerriamWebsterAPIWrapper(**kwargs))
319
+
320
+
321
+ def _get_wikipedia(**kwargs: Any) -> BaseTool:
322
+ return WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(**kwargs))
323
+
324
+
325
+ def _get_arxiv(**kwargs: Any) -> BaseTool:
326
+ return ArxivQueryRun(api_wrapper=ArxivAPIWrapper(**kwargs))
327
+
328
+
329
+ def _get_golden_query(**kwargs: Any) -> BaseTool:
330
+ return GoldenQueryRun(api_wrapper=GoldenQueryAPIWrapper(**kwargs))
331
+
332
+
333
+ def _get_pubmed(**kwargs: Any) -> BaseTool:
334
+ return PubmedQueryRun(api_wrapper=PubMedAPIWrapper(**kwargs))
335
+
336
+
337
+ def _get_google_books(**kwargs: Any) -> BaseTool:
338
+ from langchain_community.tools.google_books import GoogleBooksQueryRun
339
+
340
+ return GoogleBooksQueryRun(api_wrapper=GoogleBooksAPIWrapper(**kwargs))
341
+
342
+
343
+ def _get_google_jobs(**kwargs: Any) -> BaseTool:
344
+ return GoogleJobsQueryRun(api_wrapper=GoogleJobsAPIWrapper(**kwargs))
345
+
346
+
347
+ def _get_google_lens(**kwargs: Any) -> BaseTool:
348
+ return GoogleLensQueryRun(api_wrapper=GoogleLensAPIWrapper(**kwargs))
349
+
350
+
351
+ def _get_google_serper(**kwargs: Any) -> BaseTool:
352
+ return GoogleSerperRun(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
353
+
354
+
355
+ def _get_google_scholar(**kwargs: Any) -> BaseTool:
356
+ return GoogleScholarQueryRun(api_wrapper=GoogleScholarAPIWrapper(**kwargs))
357
+
358
+
359
+ def _get_google_finance(**kwargs: Any) -> BaseTool:
360
+ return GoogleFinanceQueryRun(api_wrapper=GoogleFinanceAPIWrapper(**kwargs))
361
+
362
+
363
+ def _get_google_trends(**kwargs: Any) -> BaseTool:
364
+ return GoogleTrendsQueryRun(api_wrapper=GoogleTrendsAPIWrapper(**kwargs))
365
+
366
+
367
+ def _get_google_serper_results_json(**kwargs: Any) -> BaseTool:
368
+ return GoogleSerperResults(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
369
+
370
+
371
+ def _get_google_search_results_json(**kwargs: Any) -> BaseTool:
372
+ return GoogleSearchResults(api_wrapper=GoogleSearchAPIWrapper(**kwargs))
373
+
374
+
375
+ def _get_searchapi(**kwargs: Any) -> BaseTool:
376
+ return SearchAPIRun(api_wrapper=SearchApiAPIWrapper(**kwargs))
377
+
378
+
379
+ def _get_searchapi_results_json(**kwargs: Any) -> BaseTool:
380
+ return SearchAPIResults(api_wrapper=SearchApiAPIWrapper(**kwargs))
381
+
382
+
383
+ def _get_serpapi(**kwargs: Any) -> BaseTool:
384
+ return Tool(
385
+ name="Search",
386
+ description="A search engine. Useful for when you need to answer questions about current events. Input should be a search query.",
387
+ func=SerpAPIWrapper(**kwargs).run,
388
+ coroutine=SerpAPIWrapper(**kwargs).arun,
389
+ )
390
+
391
+
392
+ def _get_stackexchange(**kwargs: Any) -> BaseTool:
393
+ return StackExchangeTool(api_wrapper=StackExchangeAPIWrapper(**kwargs))
394
+
395
+
396
+ def _get_dalle_image_generator(**kwargs: Any) -> Tool:
397
+ return Tool(
398
+ "Dall-E-Image-Generator",
399
+ DallEAPIWrapper(**kwargs).run,
400
+ "A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description.",
401
+ )
402
+
403
+
404
+ def _get_twilio(**kwargs: Any) -> BaseTool:
405
+ return Tool(
406
+ name="Text-Message",
407
+ description="Useful for when you need to send a text message to a provided phone number.",
408
+ func=TwilioAPIWrapper(**kwargs).run,
409
+ )
410
+
411
+
412
+ def _get_searx_search(**kwargs: Any) -> BaseTool:
413
+ return SearxSearchRun(wrapper=SearxSearchWrapper(**kwargs))
414
+
415
+
416
+ def _get_searx_search_results_json(**kwargs: Any) -> BaseTool:
417
+ wrapper_kwargs = {k: v for k, v in kwargs.items() if k != "num_results"}
418
+ return SearxSearchResults(wrapper=SearxSearchWrapper(**wrapper_kwargs), **kwargs)
419
+
420
+
421
+ def _get_bing_search(**kwargs: Any) -> BaseTool:
422
+ return BingSearchRun(api_wrapper=BingSearchAPIWrapper(**kwargs))
423
+
424
+
425
+ def _get_metaphor_search(**kwargs: Any) -> BaseTool:
426
+ return MetaphorSearchResults(api_wrapper=MetaphorSearchAPIWrapper(**kwargs))
427
+
428
+
429
+ def _get_ddg_search(**kwargs: Any) -> BaseTool:
430
+ return DuckDuckGoSearchRun(api_wrapper=DuckDuckGoSearchAPIWrapper(**kwargs))
431
+
432
+
433
+ def _get_human_tool(**kwargs: Any) -> BaseTool:
434
+ return HumanInputRun(**kwargs)
435
+
436
+
437
+ def _get_scenexplain(**kwargs: Any) -> BaseTool:
438
+ return SceneXplainTool(**kwargs)
439
+
440
+
441
+ def _get_graphql_tool(**kwargs: Any) -> BaseTool:
442
+ return BaseGraphQLTool(graphql_wrapper=GraphQLAPIWrapper(**kwargs))
443
+
444
+
445
+ def _get_openweathermap(**kwargs: Any) -> BaseTool:
446
+ return OpenWeatherMapQueryRun(api_wrapper=OpenWeatherMapAPIWrapper(**kwargs))
447
+
448
+
449
+ def _get_dataforseo_api_search(**kwargs: Any) -> BaseTool:
450
+ return DataForSeoAPISearchRun(api_wrapper=DataForSeoAPIWrapper(**kwargs))
451
+
452
+
453
+ def _get_dataforseo_api_search_json(**kwargs: Any) -> BaseTool:
454
+ return DataForSeoAPISearchResults(api_wrapper=DataForSeoAPIWrapper(**kwargs))
455
+
456
+
457
+ def _get_eleven_labs_text2speech(**kwargs: Any) -> BaseTool:
458
+ return ElevenLabsText2SpeechTool(**kwargs)
459
+
460
+
461
+ def _get_memorize(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
462
+ return Memorize(llm=llm) # type: ignore[arg-type]
463
+
464
+
465
+ def _get_google_cloud_texttospeech(**kwargs: Any) -> BaseTool:
466
+ return GoogleCloudTextToSpeechTool(**kwargs)
467
+
468
+
469
+ def _get_file_management_tool(**kwargs: Any) -> BaseTool:
470
+ return ReadFileTool(**kwargs)
471
+
472
+
473
+ def _get_reddit_search(**kwargs: Any) -> BaseTool:
474
+ return RedditSearchRun(api_wrapper=RedditSearchAPIWrapper(**kwargs))
475
+
476
+
477
+ _EXTRA_LLM_TOOLS: Dict[
478
+ str,
479
+ Tuple[Callable[[Arg(BaseLanguageModel, "llm"), KwArg(Any)], BaseTool], List[str]],
480
+ ] = {
481
+ "news-api": (_get_news_api, ["news_api_key"]),
482
+ "tmdb-api": (_get_tmdb_api, ["tmdb_bearer_token"]),
483
+ "podcast-api": (_get_podcast_api, ["listen_api_key"]),
484
+ "memorize": (_get_memorize, []),
485
+ }
486
+ _EXTRA_OPTIONAL_TOOLS: Dict[str, Tuple[Callable[[KwArg(Any)], BaseTool], List[str]]] = {
487
+ "wolfram-alpha": (_get_wolfram_alpha, ["wolfram_alpha_appid"]),
488
+ "google-search": (_get_google_search, ["google_api_key", "google_cse_id"]),
489
+ "google-search-results-json": (
490
+ _get_google_search_results_json,
491
+ ["google_api_key", "google_cse_id", "num_results"],
492
+ ),
493
+ "searx-search-results-json": (
494
+ _get_searx_search_results_json,
495
+ ["searx_host", "engines", "num_results", "aiosession"],
496
+ ),
497
+ "bing-search": (_get_bing_search, ["bing_subscription_key", "bing_search_url"]),
498
+ "metaphor-search": (_get_metaphor_search, ["metaphor_api_key"]),
499
+ "ddg-search": (_get_ddg_search, []),
500
+ "google-books": (_get_google_books, ["google_books_api_key"]),
501
+ "google-lens": (_get_google_lens, ["serp_api_key"]),
502
+ "google-serper": (_get_google_serper, ["serper_api_key", "aiosession"]),
503
+ "google-scholar": (
504
+ _get_google_scholar,
505
+ ["top_k_results", "hl", "lr", "serp_api_key"],
506
+ ),
507
+ "google-finance": (
508
+ _get_google_finance,
509
+ ["serp_api_key"],
510
+ ),
511
+ "google-trends": (
512
+ _get_google_trends,
513
+ ["serp_api_key"],
514
+ ),
515
+ "google-jobs": (
516
+ _get_google_jobs,
517
+ ["serp_api_key"],
518
+ ),
519
+ "google-serper-results-json": (
520
+ _get_google_serper_results_json,
521
+ ["serper_api_key", "aiosession"],
522
+ ),
523
+ "searchapi": (_get_searchapi, ["searchapi_api_key", "aiosession"]),
524
+ "searchapi-results-json": (
525
+ _get_searchapi_results_json,
526
+ ["searchapi_api_key", "aiosession"],
527
+ ),
528
+ "serpapi": (_get_serpapi, ["serpapi_api_key", "aiosession"]),
529
+ "dalle-image-generator": (_get_dalle_image_generator, ["openai_api_key"]),
530
+ "twilio": (_get_twilio, ["account_sid", "auth_token", "from_number"]),
531
+ "searx-search": (_get_searx_search, ["searx_host", "engines", "aiosession"]),
532
+ "merriam-webster": (_get_merriam_webster, ["merriam_webster_api_key"]),
533
+ "wikipedia": (_get_wikipedia, ["top_k_results", "lang"]),
534
+ "arxiv": (
535
+ _get_arxiv,
536
+ ["top_k_results", "load_max_docs", "load_all_available_meta"],
537
+ ),
538
+ "golden-query": (_get_golden_query, ["golden_api_key"]),
539
+ "pubmed": (_get_pubmed, ["top_k_results"]),
540
+ "human": (_get_human_tool, ["prompt_func", "input_func"]),
541
+ "awslambda": (
542
+ _get_lambda_api,
543
+ ["awslambda_tool_name", "awslambda_tool_description", "function_name"],
544
+ ),
545
+ "stackexchange": (_get_stackexchange, []),
546
+ "sceneXplain": (_get_scenexplain, []),
547
+ "graphql": (
548
+ _get_graphql_tool,
549
+ ["graphql_endpoint", "custom_headers", "fetch_schema_from_transport"],
550
+ ),
551
+ "openweathermap-api": (_get_openweathermap, ["openweathermap_api_key"]),
552
+ "dataforseo-api-search": (
553
+ _get_dataforseo_api_search,
554
+ ["api_login", "api_password", "aiosession"],
555
+ ),
556
+ "dataforseo-api-search-json": (
557
+ _get_dataforseo_api_search_json,
558
+ ["api_login", "api_password", "aiosession"],
559
+ ),
560
+ "eleven_labs_text2speech": (_get_eleven_labs_text2speech, ["elevenlabs_api_key"]),
561
+ "google_cloud_texttospeech": (_get_google_cloud_texttospeech, []),
562
+ "read_file": (_get_file_management_tool, []),
563
+ "reddit_search": (
564
+ _get_reddit_search,
565
+ ["reddit_client_id", "reddit_client_secret", "reddit_user_agent"],
566
+ ),
567
+ }
568
+
569
+
570
+ def _handle_callbacks(
571
+ callback_manager: Optional[BaseCallbackManager], callbacks: Callbacks
572
+ ) -> Callbacks:
573
+ if callback_manager is not None:
574
+ warnings.warn(
575
+ "callback_manager is deprecated. Please use callbacks instead.",
576
+ DeprecationWarning,
577
+ )
578
+ if callbacks is not None:
579
+ raise ValueError(
580
+ "Cannot specify both callback_manager and callbacks arguments."
581
+ )
582
+ return callback_manager
583
+ return callbacks
584
+
585
+
586
+ def load_huggingface_tool(
587
+ task_or_repo_id: str,
588
+ model_repo_id: Optional[str] = None,
589
+ token: Optional[str] = None,
590
+ remote: bool = False,
591
+ **kwargs: Any,
592
+ ) -> BaseTool:
593
+ """Loads a tool from the HuggingFace Hub.
594
+
595
+ Args:
596
+ task_or_repo_id: Task or model repo id.
597
+ model_repo_id: Optional model repo id. Defaults to None.
598
+ token: Optional token. Defaults to None.
599
+ remote: Optional remote. Defaults to False.
600
+ kwargs: Additional keyword arguments.
601
+
602
+ Returns:
603
+ A tool.
604
+
605
+ Raises:
606
+ ImportError: If the required libraries are not installed.
607
+ NotImplementedError: If multimodal outputs or inputs are not supported.
608
+ """
609
+ try:
610
+ from transformers import load_tool
611
+ except ImportError:
612
+ raise ImportError(
613
+ "HuggingFace tools require the libraries `transformers>=4.29.0`"
614
+ " and `huggingface_hub>=0.14.1` to be installed."
615
+ " Please install it with"
616
+ " `pip install --upgrade transformers huggingface_hub`."
617
+ )
618
+ hf_tool = load_tool(
619
+ task_or_repo_id,
620
+ model_repo_id=model_repo_id,
621
+ token=token,
622
+ remote=remote,
623
+ **kwargs,
624
+ )
625
+ outputs = hf_tool.outputs
626
+ if set(outputs) != {"text"}:
627
+ raise NotImplementedError("Multimodal outputs not supported yet.")
628
+ inputs = hf_tool.inputs
629
+ if set(inputs) != {"text"}:
630
+ raise NotImplementedError("Multimodal inputs not supported yet.")
631
+ return Tool.from_function(
632
+ hf_tool.__call__, name=hf_tool.name, description=hf_tool.description
633
+ )
634
+
635
+
636
+ def raise_dangerous_tools_exception(name: str) -> None:
637
+ raise ValueError(
638
+ f"{name} is a dangerous tool. You cannot use it without opting in "
639
+ "by setting allow_dangerous_tools to True. "
640
+ "Most tools have some inherit risk to them merely because they are "
641
+ 'allowed to interact with the "real world".'
642
+ "Please refer to LangChain security guidelines "
643
+ "to https://python.langchain.com/docs/security."
644
+ "Some tools have been designated as dangerous because they pose "
645
+ "risk that is not intuitively obvious. For example, a tool that "
646
+ "allows an agent to make requests to the web, can also be used "
647
+ "to make requests to a server that is only accessible from the "
648
+ "server hosting the code."
649
+ "Again, all tools carry some risk, and it's your responsibility to "
650
+ "understand which tools you're using and the risks associated with "
651
+ "them."
652
+ )
653
+
654
+
655
+ def load_tools(
656
+ tool_names: List[str],
657
+ llm: Optional[BaseLanguageModel] = None,
658
+ callbacks: Callbacks = None,
659
+ allow_dangerous_tools: bool = False,
660
+ **kwargs: Any,
661
+ ) -> List[BaseTool]:
662
+ """Load tools based on their name.
663
+
664
+ Tools allow agents to interact with various resources and services like
665
+ APIs, databases, file systems, etc.
666
+
667
+ Please scope the permissions of each tools to the minimum required for the
668
+ application.
669
+
670
+ For example, if an application only needs to read from a database,
671
+ the database tool should not be given write permissions. Moreover
672
+ consider scoping the permissions to only allow accessing specific
673
+ tables and impose user-level quota for limiting resource usage.
674
+
675
+ Please read the APIs of the individual tools to determine which configuration
676
+ they support.
677
+
678
+ See [Security](https://python.langchain.com/docs/security) for more information.
679
+
680
+ Args:
681
+ tool_names: name of tools to load.
682
+ llm: An optional language model may be needed to initialize certain tools.
683
+ Defaults to None.
684
+ callbacks: Optional callback manager or list of callback handlers.
685
+ If not provided, default global callback manager will be used.
686
+ allow_dangerous_tools: Optional flag to allow dangerous tools.
687
+ Tools that contain some level of risk.
688
+ Please use with caution and read the documentation of these tools
689
+ to understand the risks and how to mitigate them.
690
+ Refer to https://python.langchain.com/docs/security
691
+ for more information.
692
+ Please note that this list may not be fully exhaustive.
693
+ It is your responsibility to understand which tools
694
+ you're using and the risks associated with them.
695
+ Defaults to False.
696
+ kwargs: Additional keyword arguments.
697
+
698
+ Returns:
699
+ List of tools.
700
+
701
+ Raises:
702
+ ValueError: If the tool name is unknown.
703
+ ValueError: If the tool requires an LLM to be provided.
704
+ ValueError: If the tool requires some parameters that were not provided.
705
+ ValueError: If the tool is a dangerous tool and allow_dangerous_tools is False.
706
+ """
707
+ tools = []
708
+ callbacks = _handle_callbacks(
709
+ callback_manager=kwargs.get("callback_manager"), callbacks=callbacks
710
+ )
711
+ for name in tool_names:
712
+ if name in DANGEROUS_TOOLS and not allow_dangerous_tools:
713
+ raise_dangerous_tools_exception(name)
714
+
715
+ if name in {"requests"}:
716
+ warnings.warn(
717
+ "tool name `requests` is deprecated - "
718
+ "please use `requests_all` or specify the requests method"
719
+ )
720
+ if name == "requests_all":
721
+ # expand requests into various methods
722
+ if not allow_dangerous_tools:
723
+ raise_dangerous_tools_exception(name)
724
+ requests_method_tools = [
725
+ _tool for _tool in DANGEROUS_TOOLS if _tool.startswith("requests_")
726
+ ]
727
+ tool_names.extend(requests_method_tools)
728
+ elif name in _BASE_TOOLS:
729
+ tools.append(_BASE_TOOLS[name]())
730
+ elif name in DANGEROUS_TOOLS:
731
+ tools.append(DANGEROUS_TOOLS[name]())
732
+ elif name in _LLM_TOOLS:
733
+ if llm is None:
734
+ raise ValueError(f"Tool {name} requires an LLM to be provided")
735
+ tool = _LLM_TOOLS[name](llm)
736
+ tools.append(tool)
737
+ elif name in _EXTRA_LLM_TOOLS:
738
+ if llm is None:
739
+ raise ValueError(f"Tool {name} requires an LLM to be provided")
740
+ _get_llm_tool_func, extra_keys = _EXTRA_LLM_TOOLS[name]
741
+ missing_keys = set(extra_keys).difference(kwargs)
742
+ if missing_keys:
743
+ raise ValueError(
744
+ f"Tool {name} requires some parameters that were not "
745
+ f"provided: {missing_keys}"
746
+ )
747
+ sub_kwargs = {k: kwargs[k] for k in extra_keys}
748
+ tool = _get_llm_tool_func(llm=llm, **sub_kwargs)
749
+ tools.append(tool)
750
+ elif name in _EXTRA_OPTIONAL_TOOLS:
751
+ _get_tool_func, extra_keys = _EXTRA_OPTIONAL_TOOLS[name]
752
+ sub_kwargs = {k: kwargs[k] for k in extra_keys if k in kwargs}
753
+ tool = _get_tool_func(**sub_kwargs)
754
+ tools.append(tool)
755
+ else:
756
+ raise ValueError(f"Got unknown tool {name}")
757
+ if callbacks is not None:
758
+ for tool in tools:
759
+ tool.callbacks = callbacks
760
+ return tools
761
+
762
+
763
+ def get_all_tool_names() -> List[str]:
764
+ """Get a list of all possible tool names."""
765
+ return (
766
+ list(_BASE_TOOLS)
767
+ + list(_EXTRA_OPTIONAL_TOOLS)
768
+ + list(_EXTRA_LLM_TOOLS)
769
+ + list(_LLM_TOOLS)
770
+ + list(DANGEROUS_TOOLS)
771
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agents/__init__.py ADDED
File without changes
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/__init__.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """**Callback handlers** allow listening to events in LangChain.
2
+
3
+ **Class hierarchy:**
4
+
5
+ .. code-block::
6
+
7
+ BaseCallbackHandler --> <name>CallbackHandler # Example: AimCallbackHandler
8
+ """
9
+
10
+ import importlib
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ if TYPE_CHECKING:
14
+ from langchain_community.callbacks.aim_callback import (
15
+ AimCallbackHandler,
16
+ )
17
+ from langchain_community.callbacks.argilla_callback import (
18
+ ArgillaCallbackHandler,
19
+ )
20
+ from langchain_community.callbacks.arize_callback import (
21
+ ArizeCallbackHandler,
22
+ )
23
+ from langchain_community.callbacks.arthur_callback import (
24
+ ArthurCallbackHandler,
25
+ )
26
+ from langchain_community.callbacks.clearml_callback import (
27
+ ClearMLCallbackHandler,
28
+ )
29
+ from langchain_community.callbacks.comet_ml_callback import (
30
+ CometCallbackHandler,
31
+ )
32
+ from langchain_community.callbacks.context_callback import (
33
+ ContextCallbackHandler,
34
+ )
35
+ from langchain_community.callbacks.fiddler_callback import (
36
+ FiddlerCallbackHandler,
37
+ )
38
+ from langchain_community.callbacks.flyte_callback import (
39
+ FlyteCallbackHandler,
40
+ )
41
+ from langchain_community.callbacks.human import (
42
+ HumanApprovalCallbackHandler,
43
+ )
44
+ from langchain_community.callbacks.infino_callback import (
45
+ InfinoCallbackHandler,
46
+ )
47
+ from langchain_community.callbacks.labelstudio_callback import (
48
+ LabelStudioCallbackHandler,
49
+ )
50
+ from langchain_community.callbacks.llmonitor_callback import (
51
+ LLMonitorCallbackHandler,
52
+ )
53
+ from langchain_community.callbacks.manager import (
54
+ get_openai_callback,
55
+ wandb_tracing_enabled,
56
+ )
57
+ from langchain_community.callbacks.mlflow_callback import (
58
+ MlflowCallbackHandler,
59
+ )
60
+ from langchain_community.callbacks.openai_info import (
61
+ OpenAICallbackHandler,
62
+ )
63
+ from langchain_community.callbacks.promptlayer_callback import (
64
+ PromptLayerCallbackHandler,
65
+ )
66
+ from langchain_community.callbacks.sagemaker_callback import (
67
+ SageMakerCallbackHandler,
68
+ )
69
+ from langchain_community.callbacks.streamlit import (
70
+ LLMThoughtLabeler,
71
+ StreamlitCallbackHandler,
72
+ )
73
+ from langchain_community.callbacks.trubrics_callback import (
74
+ TrubricsCallbackHandler,
75
+ )
76
+ from langchain_community.callbacks.upstash_ratelimit_callback import (
77
+ UpstashRatelimitError,
78
+ UpstashRatelimitHandler, # noqa: F401
79
+ )
80
+ from langchain_community.callbacks.uptrain_callback import (
81
+ UpTrainCallbackHandler,
82
+ )
83
+ from langchain_community.callbacks.wandb_callback import (
84
+ WandbCallbackHandler,
85
+ )
86
+ from langchain_community.callbacks.whylabs_callback import (
87
+ WhyLabsCallbackHandler,
88
+ )
89
+
90
+
91
+ _module_lookup = {
92
+ "AimCallbackHandler": "langchain_community.callbacks.aim_callback",
93
+ "ArgillaCallbackHandler": "langchain_community.callbacks.argilla_callback",
94
+ "ArizeCallbackHandler": "langchain_community.callbacks.arize_callback",
95
+ "ArthurCallbackHandler": "langchain_community.callbacks.arthur_callback",
96
+ "ClearMLCallbackHandler": "langchain_community.callbacks.clearml_callback",
97
+ "CometCallbackHandler": "langchain_community.callbacks.comet_ml_callback",
98
+ "ContextCallbackHandler": "langchain_community.callbacks.context_callback",
99
+ "FiddlerCallbackHandler": "langchain_community.callbacks.fiddler_callback",
100
+ "FlyteCallbackHandler": "langchain_community.callbacks.flyte_callback",
101
+ "HumanApprovalCallbackHandler": "langchain_community.callbacks.human",
102
+ "InfinoCallbackHandler": "langchain_community.callbacks.infino_callback",
103
+ "LLMThoughtLabeler": "langchain_community.callbacks.streamlit",
104
+ "LLMonitorCallbackHandler": "langchain_community.callbacks.llmonitor_callback",
105
+ "LabelStudioCallbackHandler": "langchain_community.callbacks.labelstudio_callback",
106
+ "MlflowCallbackHandler": "langchain_community.callbacks.mlflow_callback",
107
+ "OpenAICallbackHandler": "langchain_community.callbacks.openai_info",
108
+ "PromptLayerCallbackHandler": "langchain_community.callbacks.promptlayer_callback",
109
+ "SageMakerCallbackHandler": "langchain_community.callbacks.sagemaker_callback",
110
+ "StreamlitCallbackHandler": "langchain_community.callbacks.streamlit",
111
+ "TrubricsCallbackHandler": "langchain_community.callbacks.trubrics_callback",
112
+ "UpstashRatelimitError": "langchain_community.callbacks.upstash_ratelimit_callback",
113
+ "UpstashRatelimitHandler": "langchain_community.callbacks.upstash_ratelimit_callback", # noqa
114
+ "UpTrainCallbackHandler": "langchain_community.callbacks.uptrain_callback",
115
+ "WandbCallbackHandler": "langchain_community.callbacks.wandb_callback",
116
+ "WhyLabsCallbackHandler": "langchain_community.callbacks.whylabs_callback",
117
+ "get_openai_callback": "langchain_community.callbacks.manager",
118
+ "wandb_tracing_enabled": "langchain_community.callbacks.manager",
119
+ }
120
+
121
+
122
+ def __getattr__(name: str) -> Any:
123
+ if name in _module_lookup:
124
+ module = importlib.import_module(_module_lookup[name])
125
+ return getattr(module, name)
126
+ raise AttributeError(f"module {__name__} has no attribute {name}")
127
+
128
+
129
+ __all__ = [
130
+ "AimCallbackHandler",
131
+ "ArgillaCallbackHandler",
132
+ "ArizeCallbackHandler",
133
+ "ArthurCallbackHandler",
134
+ "ClearMLCallbackHandler",
135
+ "CometCallbackHandler",
136
+ "ContextCallbackHandler",
137
+ "FiddlerCallbackHandler",
138
+ "FlyteCallbackHandler",
139
+ "HumanApprovalCallbackHandler",
140
+ "InfinoCallbackHandler",
141
+ "LLMThoughtLabeler",
142
+ "LLMonitorCallbackHandler",
143
+ "LabelStudioCallbackHandler",
144
+ "MlflowCallbackHandler",
145
+ "OpenAICallbackHandler",
146
+ "PromptLayerCallbackHandler",
147
+ "SageMakerCallbackHandler",
148
+ "StreamlitCallbackHandler",
149
+ "TrubricsCallbackHandler",
150
+ "UpstashRatelimitError",
151
+ "UpstashRatelimitHandler",
152
+ "UpTrainCallbackHandler",
153
+ "WandbCallbackHandler",
154
+ "WhyLabsCallbackHandler",
155
+ "get_openai_callback",
156
+ "wandb_tracing_enabled",
157
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/aim_callback.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+ from typing import Any, Dict, List, Optional
3
+
4
+ from langchain_core.agents import AgentAction, AgentFinish
5
+ from langchain_core.callbacks import BaseCallbackHandler
6
+ from langchain_core.outputs import LLMResult
7
+ from langchain_core.utils import guard_import
8
+
9
+
10
+ def import_aim() -> Any:
11
+ """Import the aim python package and raise an error if it is not installed."""
12
+ return guard_import("aim")
13
+
14
+
15
+ class BaseMetadataCallbackHandler:
16
+ """Callback handler for the metadata and associated function states for callbacks.
17
+
18
+ Attributes:
19
+ step (int): The current step.
20
+ starts (int): The number of times the start method has been called.
21
+ ends (int): The number of times the end method has been called.
22
+ errors (int): The number of times the error method has been called.
23
+ text_ctr (int): The number of times the text method has been called.
24
+ ignore_llm_ (bool): Whether to ignore llm callbacks.
25
+ ignore_chain_ (bool): Whether to ignore chain callbacks.
26
+ ignore_agent_ (bool): Whether to ignore agent callbacks.
27
+ ignore_retriever_ (bool): Whether to ignore retriever callbacks.
28
+ always_verbose_ (bool): Whether to always be verbose.
29
+ chain_starts (int): The number of times the chain start method has been called.
30
+ chain_ends (int): The number of times the chain end method has been called.
31
+ llm_starts (int): The number of times the llm start method has been called.
32
+ llm_ends (int): The number of times the llm end method has been called.
33
+ llm_streams (int): The number of times the text method has been called.
34
+ tool_starts (int): The number of times the tool start method has been called.
35
+ tool_ends (int): The number of times the tool end method has been called.
36
+ agent_ends (int): The number of times the agent end method has been called.
37
+ """
38
+
39
+ def __init__(self) -> None:
40
+ self.step = 0
41
+
42
+ self.starts = 0
43
+ self.ends = 0
44
+ self.errors = 0
45
+ self.text_ctr = 0
46
+
47
+ self.ignore_llm_ = False
48
+ self.ignore_chain_ = False
49
+ self.ignore_agent_ = False
50
+ self.ignore_retriever_ = False
51
+ self.always_verbose_ = False
52
+
53
+ self.chain_starts = 0
54
+ self.chain_ends = 0
55
+
56
+ self.llm_starts = 0
57
+ self.llm_ends = 0
58
+ self.llm_streams = 0
59
+
60
+ self.tool_starts = 0
61
+ self.tool_ends = 0
62
+
63
+ self.agent_ends = 0
64
+
65
+ @property
66
+ def always_verbose(self) -> bool:
67
+ """Whether to call verbose callbacks even if verbose is False."""
68
+ return self.always_verbose_
69
+
70
+ @property
71
+ def ignore_llm(self) -> bool:
72
+ """Whether to ignore LLM callbacks."""
73
+ return self.ignore_llm_
74
+
75
+ @property
76
+ def ignore_chain(self) -> bool:
77
+ """Whether to ignore chain callbacks."""
78
+ return self.ignore_chain_
79
+
80
+ @property
81
+ def ignore_agent(self) -> bool:
82
+ """Whether to ignore agent callbacks."""
83
+ return self.ignore_agent_
84
+
85
+ @property
86
+ def ignore_retriever(self) -> bool:
87
+ """Whether to ignore retriever callbacks."""
88
+ return self.ignore_retriever_
89
+
90
+ def get_custom_callback_meta(self) -> Dict[str, Any]:
91
+ return {
92
+ "step": self.step,
93
+ "starts": self.starts,
94
+ "ends": self.ends,
95
+ "errors": self.errors,
96
+ "text_ctr": self.text_ctr,
97
+ "chain_starts": self.chain_starts,
98
+ "chain_ends": self.chain_ends,
99
+ "llm_starts": self.llm_starts,
100
+ "llm_ends": self.llm_ends,
101
+ "llm_streams": self.llm_streams,
102
+ "tool_starts": self.tool_starts,
103
+ "tool_ends": self.tool_ends,
104
+ "agent_ends": self.agent_ends,
105
+ }
106
+
107
+ def reset_callback_meta(self) -> None:
108
+ """Reset the callback metadata."""
109
+ self.step = 0
110
+
111
+ self.starts = 0
112
+ self.ends = 0
113
+ self.errors = 0
114
+ self.text_ctr = 0
115
+
116
+ self.ignore_llm_ = False
117
+ self.ignore_chain_ = False
118
+ self.ignore_agent_ = False
119
+ self.always_verbose_ = False
120
+
121
+ self.chain_starts = 0
122
+ self.chain_ends = 0
123
+
124
+ self.llm_starts = 0
125
+ self.llm_ends = 0
126
+ self.llm_streams = 0
127
+
128
+ self.tool_starts = 0
129
+ self.tool_ends = 0
130
+
131
+ self.agent_ends = 0
132
+
133
+ return None
134
+
135
+
136
+ class AimCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
137
+ """Callback Handler that logs to Aim.
138
+
139
+ Parameters:
140
+ repo (:obj:`str`, optional): Aim repository path or Repo object to which
141
+ Run object is bound. If skipped, default Repo is used.
142
+ experiment_name (:obj:`str`, optional): Sets Run's `experiment` property.
143
+ 'default' if not specified. Can be used later to query runs/sequences.
144
+ system_tracking_interval (:obj:`int`, optional): Sets the tracking interval
145
+ in seconds for system usage metrics (CPU, Memory, etc.). Set to `None`
146
+ to disable system metrics tracking.
147
+ log_system_params (:obj:`bool`, optional): Enable/Disable logging of system
148
+ params such as installed packages, git info, environment variables, etc.
149
+
150
+ This handler will utilize the associated callback method called and formats
151
+ the input of each callback function with metadata regarding the state of LLM run
152
+ and then logs the response to Aim.
153
+ """
154
+
155
+ def __init__(
156
+ self,
157
+ repo: Optional[str] = None,
158
+ experiment_name: Optional[str] = None,
159
+ system_tracking_interval: Optional[int] = 10,
160
+ log_system_params: bool = True,
161
+ ) -> None:
162
+ """Initialize callback handler."""
163
+
164
+ super().__init__()
165
+
166
+ aim = import_aim()
167
+ self.repo = repo
168
+ self.experiment_name = experiment_name
169
+ self.system_tracking_interval = system_tracking_interval
170
+ self.log_system_params = log_system_params
171
+ self._run = aim.Run(
172
+ repo=self.repo,
173
+ experiment=self.experiment_name,
174
+ system_tracking_interval=self.system_tracking_interval,
175
+ log_system_params=self.log_system_params,
176
+ )
177
+ self._run_hash = self._run.hash
178
+ self.action_records: list = []
179
+
180
+ def setup(self, **kwargs: Any) -> None:
181
+ aim = import_aim()
182
+
183
+ if not self._run:
184
+ if self._run_hash:
185
+ self._run = aim.Run(
186
+ self._run_hash,
187
+ repo=self.repo,
188
+ system_tracking_interval=self.system_tracking_interval,
189
+ )
190
+ else:
191
+ self._run = aim.Run(
192
+ repo=self.repo,
193
+ experiment=self.experiment_name,
194
+ system_tracking_interval=self.system_tracking_interval,
195
+ log_system_params=self.log_system_params,
196
+ )
197
+ self._run_hash = self._run.hash
198
+
199
+ if kwargs:
200
+ for key, value in kwargs.items():
201
+ self._run.set(key, value, strict=False)
202
+
203
+ def on_llm_start(
204
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
205
+ ) -> None:
206
+ """Run when LLM starts."""
207
+ aim = import_aim()
208
+
209
+ self.step += 1
210
+ self.llm_starts += 1
211
+ self.starts += 1
212
+
213
+ resp = {"action": "on_llm_start"}
214
+ resp.update(self.get_custom_callback_meta())
215
+
216
+ prompts_res = deepcopy(prompts)
217
+
218
+ self._run.track(
219
+ [aim.Text(prompt) for prompt in prompts_res],
220
+ name="on_llm_start",
221
+ context=resp,
222
+ )
223
+
224
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
225
+ """Run when LLM ends running."""
226
+ aim = import_aim()
227
+ self.step += 1
228
+ self.llm_ends += 1
229
+ self.ends += 1
230
+
231
+ resp = {"action": "on_llm_end"}
232
+ resp.update(self.get_custom_callback_meta())
233
+
234
+ response_res = deepcopy(response)
235
+
236
+ generated = [
237
+ aim.Text(generation.text)
238
+ for generations in response_res.generations
239
+ for generation in generations
240
+ ]
241
+ self._run.track(
242
+ generated,
243
+ name="on_llm_end",
244
+ context=resp,
245
+ )
246
+
247
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
248
+ """Run when LLM generates a new token."""
249
+ self.step += 1
250
+ self.llm_streams += 1
251
+
252
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
253
+ """Run when LLM errors."""
254
+ self.step += 1
255
+ self.errors += 1
256
+
257
+ def on_chain_start(
258
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
259
+ ) -> None:
260
+ """Run when chain starts running."""
261
+ aim = import_aim()
262
+ self.step += 1
263
+ self.chain_starts += 1
264
+ self.starts += 1
265
+
266
+ resp = {"action": "on_chain_start"}
267
+ resp.update(self.get_custom_callback_meta())
268
+
269
+ inputs_res = deepcopy(inputs)
270
+
271
+ self._run.track(
272
+ aim.Text(inputs_res["input"]), name="on_chain_start", context=resp
273
+ )
274
+
275
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
276
+ """Run when chain ends running."""
277
+ aim = import_aim()
278
+ self.step += 1
279
+ self.chain_ends += 1
280
+ self.ends += 1
281
+
282
+ resp = {"action": "on_chain_end"}
283
+ resp.update(self.get_custom_callback_meta())
284
+
285
+ outputs_res = deepcopy(outputs)
286
+
287
+ self._run.track(
288
+ aim.Text(outputs_res["output"]), name="on_chain_end", context=resp
289
+ )
290
+
291
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
292
+ """Run when chain errors."""
293
+ self.step += 1
294
+ self.errors += 1
295
+
296
+ def on_tool_start(
297
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
298
+ ) -> None:
299
+ """Run when tool starts running."""
300
+ aim = import_aim()
301
+ self.step += 1
302
+ self.tool_starts += 1
303
+ self.starts += 1
304
+
305
+ resp = {"action": "on_tool_start"}
306
+ resp.update(self.get_custom_callback_meta())
307
+
308
+ self._run.track(aim.Text(input_str), name="on_tool_start", context=resp)
309
+
310
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
311
+ """Run when tool ends running."""
312
+ output = str(output)
313
+ aim = import_aim()
314
+ self.step += 1
315
+ self.tool_ends += 1
316
+ self.ends += 1
317
+
318
+ resp = {"action": "on_tool_end"}
319
+ resp.update(self.get_custom_callback_meta())
320
+
321
+ self._run.track(aim.Text(output), name="on_tool_end", context=resp)
322
+
323
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
324
+ """Run when tool errors."""
325
+ self.step += 1
326
+ self.errors += 1
327
+
328
+ def on_text(self, text: str, **kwargs: Any) -> None:
329
+ """
330
+ Run when agent is ending.
331
+ """
332
+ self.step += 1
333
+ self.text_ctr += 1
334
+
335
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
336
+ """Run when agent ends running."""
337
+ aim = import_aim()
338
+ self.step += 1
339
+ self.agent_ends += 1
340
+ self.ends += 1
341
+
342
+ resp = {"action": "on_agent_finish"}
343
+ resp.update(self.get_custom_callback_meta())
344
+
345
+ finish_res = deepcopy(finish)
346
+
347
+ text = "OUTPUT:\n{}\n\nLOG:\n{}".format(
348
+ finish_res.return_values["output"], finish_res.log
349
+ )
350
+ self._run.track(aim.Text(text), name="on_agent_finish", context=resp)
351
+
352
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
353
+ """Run on agent action."""
354
+ aim = import_aim()
355
+ self.step += 1
356
+ self.tool_starts += 1
357
+ self.starts += 1
358
+
359
+ resp = {
360
+ "action": "on_agent_action",
361
+ "tool": action.tool,
362
+ }
363
+ resp.update(self.get_custom_callback_meta())
364
+
365
+ action_res = deepcopy(action)
366
+
367
+ text = "TOOL INPUT:\n{}\n\nLOG:\n{}".format(
368
+ action_res.tool_input, action_res.log
369
+ )
370
+ self._run.track(aim.Text(text), name="on_agent_action", context=resp)
371
+
372
+ def flush_tracker(
373
+ self,
374
+ repo: Optional[str] = None,
375
+ experiment_name: Optional[str] = None,
376
+ system_tracking_interval: Optional[int] = 10,
377
+ log_system_params: bool = True,
378
+ langchain_asset: Any = None,
379
+ reset: bool = True,
380
+ finish: bool = False,
381
+ ) -> None:
382
+ """Flush the tracker and reset the session.
383
+
384
+ Args:
385
+ repo (:obj:`str`, optional): Aim repository path or Repo object to which
386
+ Run object is bound. If skipped, default Repo is used.
387
+ experiment_name (:obj:`str`, optional): Sets Run's `experiment` property.
388
+ 'default' if not specified. Can be used later to query runs/sequences.
389
+ system_tracking_interval (:obj:`int`, optional): Sets the tracking interval
390
+ in seconds for system usage metrics (CPU, Memory, etc.). Set to `None`
391
+ to disable system metrics tracking.
392
+ log_system_params (:obj:`bool`, optional): Enable/Disable logging of system
393
+ params such as installed packages, git info, environment variables, etc.
394
+ langchain_asset: The langchain asset to save.
395
+ reset: Whether to reset the session.
396
+ finish: Whether to finish the run.
397
+
398
+ Returns:
399
+ None
400
+ """
401
+
402
+ if langchain_asset:
403
+ try:
404
+ for key, value in langchain_asset.dict().items():
405
+ self._run.set(key, value, strict=False)
406
+ except Exception:
407
+ pass
408
+
409
+ if finish or reset:
410
+ self._run.close()
411
+ self.reset_callback_meta()
412
+ if reset:
413
+ aim = import_aim()
414
+ self.repo = repo if repo else self.repo
415
+ self.experiment_name = (
416
+ experiment_name if experiment_name else self.experiment_name
417
+ )
418
+ self.system_tracking_interval = (
419
+ system_tracking_interval
420
+ if system_tracking_interval
421
+ else self.system_tracking_interval
422
+ )
423
+ self.log_system_params = (
424
+ log_system_params if log_system_params else self.log_system_params
425
+ )
426
+
427
+ self._run = aim.Run(
428
+ repo=self.repo,
429
+ experiment=self.experiment_name,
430
+ system_tracking_interval=self.system_tracking_interval,
431
+ log_system_params=self.log_system_params,
432
+ )
433
+ self._run_hash = self._run.hash
434
+ self.action_records = []
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/argilla_callback.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import warnings
3
+ from typing import Any, Dict, List, Optional, cast
4
+
5
+ from langchain_core.agents import AgentAction, AgentFinish
6
+ from langchain_core.callbacks import BaseCallbackHandler
7
+ from langchain_core.outputs import LLMResult
8
+ from packaging.version import parse
9
+
10
+
11
+ class ArgillaCallbackHandler(BaseCallbackHandler):
12
+ """Callback Handler that logs into Argilla.
13
+
14
+ Args:
15
+ dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must
16
+ exist in advance. If you need help on how to create a `FeedbackDataset` in
17
+ Argilla, please visit
18
+ https://docs.argilla.io/en/latest/tutorials_and_integrations/integrations/use_argilla_callback_in_langchain.html.
19
+ workspace_name: name of the workspace in Argilla where the specified
20
+ `FeedbackDataset` lives in. Defaults to `None`, which means that the
21
+ default workspace will be used.
22
+ api_url: URL of the Argilla Server that we want to use, and where the
23
+ `FeedbackDataset` lives in. Defaults to `None`, which means that either
24
+ `ARGILLA_API_URL` environment variable or the default will be used.
25
+ api_key: API Key to connect to the Argilla Server. Defaults to `None`, which
26
+ means that either `ARGILLA_API_KEY` environment variable or the default
27
+ will be used.
28
+
29
+ Raises:
30
+ ImportError: if the `argilla` package is not installed.
31
+ ConnectionError: if the connection to Argilla fails.
32
+ FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails.
33
+
34
+ Examples:
35
+ >>> from langchain_community.llms import OpenAI
36
+ >>> from langchain_community.callbacks import ArgillaCallbackHandler
37
+ >>> argilla_callback = ArgillaCallbackHandler(
38
+ ... dataset_name="my-dataset",
39
+ ... workspace_name="my-workspace",
40
+ ... api_url="http://localhost:6900",
41
+ ... api_key="argilla.apikey",
42
+ ... )
43
+ >>> llm = OpenAI(
44
+ ... temperature=0,
45
+ ... callbacks=[argilla_callback],
46
+ ... verbose=True,
47
+ ... openai_api_key="API_KEY_HERE",
48
+ ... )
49
+ >>> llm.generate([
50
+ ... "What is the best NLP-annotation tool out there? (no bias at all)",
51
+ ... ])
52
+ "Argilla, no doubt about it."
53
+ """
54
+
55
+ REPO_URL: str = "https://github.com/argilla-io/argilla"
56
+ ISSUES_URL: str = f"{REPO_URL}/issues"
57
+ BLOG_URL: str = "https://docs.argilla.io/en/latest/tutorials_and_integrations/integrations/use_argilla_callback_in_langchain.html"
58
+
59
+ DEFAULT_API_URL: str = "http://localhost:6900"
60
+
61
+ def __init__(
62
+ self,
63
+ dataset_name: str,
64
+ workspace_name: Optional[str] = None,
65
+ api_url: Optional[str] = None,
66
+ api_key: Optional[str] = None,
67
+ ) -> None:
68
+ """Initializes the `ArgillaCallbackHandler`.
69
+
70
+ Args:
71
+ dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must
72
+ exist in advance. If you need help on how to create a `FeedbackDataset`
73
+ in Argilla, please visit
74
+ https://docs.argilla.io/en/latest/tutorials_and_integrations/integrations/use_argilla_callback_in_langchain.html.
75
+ workspace_name: name of the workspace in Argilla where the specified
76
+ `FeedbackDataset` lives in. Defaults to `None`, which means that the
77
+ default workspace will be used.
78
+ api_url: URL of the Argilla Server that we want to use, and where the
79
+ `FeedbackDataset` lives in. Defaults to `None`, which means that either
80
+ `ARGILLA_API_URL` environment variable or the default will be used.
81
+ api_key: API Key to connect to the Argilla Server. Defaults to `None`, which
82
+ means that either `ARGILLA_API_KEY` environment variable or the default
83
+ will be used.
84
+
85
+ Raises:
86
+ ImportError: if the `argilla` package is not installed.
87
+ ConnectionError: if the connection to Argilla fails.
88
+ FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails.
89
+ """
90
+
91
+ super().__init__()
92
+
93
+ # Import Argilla (not via `import_argilla` to keep hints in IDEs)
94
+ try:
95
+ import argilla as rg
96
+
97
+ self.ARGILLA_VERSION = rg.__version__
98
+ except ImportError:
99
+ raise ImportError(
100
+ "To use the Argilla callback manager you need to have the `argilla` "
101
+ "Python package installed. Please install it with `pip install argilla`"
102
+ )
103
+
104
+ # Check whether the Argilla version is compatible
105
+ if parse(self.ARGILLA_VERSION) < parse("1.8.0"):
106
+ raise ImportError(
107
+ f"The installed `argilla` version is {self.ARGILLA_VERSION} but "
108
+ "`ArgillaCallbackHandler` requires at least version 1.8.0. Please "
109
+ "upgrade `argilla` with `pip install --upgrade argilla`."
110
+ )
111
+
112
+ # Show a warning message if Argilla will assume the default values will be used
113
+ if api_url is None and os.getenv("ARGILLA_API_URL") is None:
114
+ warnings.warn(
115
+ (
116
+ "Since `api_url` is None, and the env var `ARGILLA_API_URL` is not"
117
+ f" set, it will default to `{self.DEFAULT_API_URL}`, which is the"
118
+ " default API URL in Argilla Quickstart."
119
+ ),
120
+ )
121
+ api_url = self.DEFAULT_API_URL
122
+
123
+ if api_key is None and os.getenv("ARGILLA_API_KEY") is None:
124
+ self.DEFAULT_API_KEY = (
125
+ "admin.apikey"
126
+ if parse(self.ARGILLA_VERSION) < parse("1.11.0")
127
+ else "owner.apikey"
128
+ )
129
+
130
+ warnings.warn(
131
+ (
132
+ "Since `api_key` is None, and the env var `ARGILLA_API_KEY` is not"
133
+ f" set, it will default to `{self.DEFAULT_API_KEY}`, which is the"
134
+ " default API key in Argilla Quickstart."
135
+ ),
136
+ )
137
+ api_key = self.DEFAULT_API_KEY
138
+
139
+ # Connect to Argilla with the provided credentials, if applicable
140
+ try:
141
+ rg.init(api_key=api_key, api_url=api_url)
142
+ except Exception as e:
143
+ raise ConnectionError(
144
+ f"Could not connect to Argilla with exception: '{e}'.\n"
145
+ "Please check your `api_key` and `api_url`, and make sure that "
146
+ "the Argilla server is up and running. If the problem persists "
147
+ f"please report it to {self.ISSUES_URL} as an `integration` issue."
148
+ ) from e
149
+
150
+ # Set the Argilla variables
151
+ self.dataset_name = dataset_name
152
+ self.workspace_name = workspace_name or rg.get_workspace()
153
+
154
+ # Retrieve the `FeedbackDataset` from Argilla (without existing records)
155
+ try:
156
+ extra_args = {}
157
+ if parse(self.ARGILLA_VERSION) < parse("1.14.0"):
158
+ warnings.warn(
159
+ f"You have Argilla {self.ARGILLA_VERSION}, but Argilla 1.14.0 or"
160
+ " higher is recommended.",
161
+ UserWarning,
162
+ )
163
+ extra_args = {"with_records": False}
164
+ self.dataset = rg.FeedbackDataset.from_argilla(
165
+ name=self.dataset_name,
166
+ workspace=self.workspace_name,
167
+ **extra_args,
168
+ )
169
+ except Exception as e:
170
+ raise FileNotFoundError(
171
+ f"`FeedbackDataset` retrieval from Argilla failed with exception `{e}`."
172
+ f"\nPlease check that the dataset with name={self.dataset_name} in the"
173
+ f" workspace={self.workspace_name} exists in advance. If you need help"
174
+ " on how to create a `langchain`-compatible `FeedbackDataset` in"
175
+ f" Argilla, please visit {self.BLOG_URL}. If the problem persists"
176
+ f" please report it to {self.ISSUES_URL} as an `integration` issue."
177
+ ) from e
178
+
179
+ supported_fields = ["prompt", "response"]
180
+ if supported_fields != [field.name for field in self.dataset.fields]:
181
+ raise ValueError(
182
+ f"`FeedbackDataset` with name={self.dataset_name} in the workspace="
183
+ f"{self.workspace_name} had fields that are not supported yet for the"
184
+ f"`langchain` integration. Supported fields are: {supported_fields},"
185
+ f" and the current `FeedbackDataset` fields are {[field.name for field in self.dataset.fields]}." # noqa: E501
186
+ " For more information on how to create a `langchain`-compatible"
187
+ f" `FeedbackDataset` in Argilla, please visit {self.BLOG_URL}."
188
+ )
189
+
190
+ self.prompts: Dict[str, List[str]] = {}
191
+
192
+ warnings.warn(
193
+ (
194
+ "The `ArgillaCallbackHandler` is currently in beta and is subject to"
195
+ " change based on updates to `langchain`. Please report any issues to"
196
+ f" {self.ISSUES_URL} as an `integration` issue."
197
+ ),
198
+ )
199
+
200
+ def on_llm_start(
201
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
202
+ ) -> None:
203
+ """Save the prompts in memory when an LLM starts."""
204
+ self.prompts.update({str(kwargs["parent_run_id"] or kwargs["run_id"]): prompts})
205
+
206
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
207
+ """Do nothing when a new token is generated."""
208
+ pass
209
+
210
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
211
+ """Log records to Argilla when an LLM ends."""
212
+ # Do nothing if there's a parent_run_id, since we will log the records when
213
+ # the chain ends
214
+ if kwargs["parent_run_id"]:
215
+ return
216
+
217
+ # Creates the records and adds them to the `FeedbackDataset`
218
+ prompts = self.prompts[str(kwargs["run_id"])]
219
+ for prompt, generations in zip(prompts, response.generations):
220
+ self.dataset.add_records(
221
+ records=[
222
+ {
223
+ "fields": {
224
+ "prompt": prompt,
225
+ "response": generation.text.strip(),
226
+ },
227
+ }
228
+ for generation in generations
229
+ ]
230
+ )
231
+
232
+ # Pop current run from `self.runs`
233
+ self.prompts.pop(str(kwargs["run_id"]))
234
+
235
+ if parse(self.ARGILLA_VERSION) < parse("1.14.0"):
236
+ # Push the records to Argilla
237
+ self.dataset.push_to_argilla()
238
+
239
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
240
+ """Do nothing when LLM outputs an error."""
241
+ pass
242
+
243
+ def on_chain_start(
244
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
245
+ ) -> None:
246
+ """If the key `input` is in `inputs`, then save it in `self.prompts` using
247
+ either the `parent_run_id` or the `run_id` as the key. This is done so that
248
+ we don't log the same input prompt twice, once when the LLM starts and once
249
+ when the chain starts.
250
+ """
251
+ if "input" in inputs:
252
+ self.prompts.update(
253
+ {
254
+ str(kwargs["parent_run_id"] or kwargs["run_id"]): (
255
+ inputs["input"]
256
+ if isinstance(inputs["input"], list)
257
+ else [inputs["input"]]
258
+ )
259
+ }
260
+ )
261
+
262
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
263
+ """If either the `parent_run_id` or the `run_id` is in `self.prompts`, then
264
+ log the outputs to Argilla, and pop the run from `self.prompts`. The behavior
265
+ differs if the output is a list or not.
266
+ """
267
+ if not any(
268
+ key in self.prompts
269
+ for key in [str(kwargs["parent_run_id"]), str(kwargs["run_id"])]
270
+ ):
271
+ return
272
+ prompts: List = self.prompts.get(str(kwargs["parent_run_id"])) or cast(
273
+ List, self.prompts.get(str(kwargs["run_id"]), [])
274
+ )
275
+ for chain_output_key, chain_output_val in outputs.items():
276
+ if isinstance(chain_output_val, list):
277
+ # Creates the records and adds them to the `FeedbackDataset`
278
+ self.dataset.add_records(
279
+ records=[
280
+ {
281
+ "fields": {
282
+ "prompt": prompt,
283
+ "response": output["text"].strip(),
284
+ },
285
+ }
286
+ for prompt, output in zip(prompts, chain_output_val)
287
+ ]
288
+ )
289
+ else:
290
+ # Creates the records and adds them to the `FeedbackDataset`
291
+ self.dataset.add_records(
292
+ records=[
293
+ {
294
+ "fields": {
295
+ "prompt": " ".join(prompts),
296
+ "response": chain_output_val.strip(),
297
+ },
298
+ }
299
+ ]
300
+ )
301
+
302
+ # Pop current run from `self.runs`
303
+ if str(kwargs["parent_run_id"]) in self.prompts:
304
+ self.prompts.pop(str(kwargs["parent_run_id"]))
305
+ if str(kwargs["run_id"]) in self.prompts:
306
+ self.prompts.pop(str(kwargs["run_id"]))
307
+
308
+ if parse(self.ARGILLA_VERSION) < parse("1.14.0"):
309
+ # Push the records to Argilla
310
+ self.dataset.push_to_argilla()
311
+
312
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
313
+ """Do nothing when LLM chain outputs an error."""
314
+ pass
315
+
316
+ def on_tool_start(
317
+ self,
318
+ serialized: Dict[str, Any],
319
+ input_str: str,
320
+ **kwargs: Any,
321
+ ) -> None:
322
+ """Do nothing when tool starts."""
323
+ pass
324
+
325
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
326
+ """Do nothing when agent takes a specific action."""
327
+ pass
328
+
329
+ def on_tool_end(
330
+ self,
331
+ output: Any,
332
+ observation_prefix: Optional[str] = None,
333
+ llm_prefix: Optional[str] = None,
334
+ **kwargs: Any,
335
+ ) -> None:
336
+ """Do nothing when tool ends."""
337
+ pass
338
+
339
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
340
+ """Do nothing when tool outputs an error."""
341
+ pass
342
+
343
+ def on_text(self, text: str, **kwargs: Any) -> None:
344
+ """Do nothing"""
345
+ pass
346
+
347
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
348
+ """Do nothing"""
349
+ pass
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arize_callback.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import Any, Dict, List, Optional
3
+
4
+ from langchain_core.agents import AgentAction, AgentFinish
5
+ from langchain_core.callbacks import BaseCallbackHandler
6
+ from langchain_core.outputs import LLMResult
7
+
8
+ from langchain_community.callbacks.utils import import_pandas
9
+
10
+
11
+ class ArizeCallbackHandler(BaseCallbackHandler):
12
+ """Callback Handler that logs to Arize."""
13
+
14
+ def __init__(
15
+ self,
16
+ model_id: Optional[str] = None,
17
+ model_version: Optional[str] = None,
18
+ SPACE_KEY: Optional[str] = None,
19
+ API_KEY: Optional[str] = None,
20
+ ) -> None:
21
+ """Initialize callback handler."""
22
+
23
+ super().__init__()
24
+ self.model_id = model_id
25
+ self.model_version = model_version
26
+ self.space_key = SPACE_KEY
27
+ self.api_key = API_KEY
28
+ self.prompt_records: List[str] = []
29
+ self.response_records: List[str] = []
30
+ self.prediction_ids: List[str] = []
31
+ self.pred_timestamps: List[int] = []
32
+ self.response_embeddings: List[float] = []
33
+ self.prompt_embeddings: List[float] = []
34
+ self.prompt_tokens = 0
35
+ self.completion_tokens = 0
36
+ self.total_tokens = 0
37
+ self.step = 0
38
+
39
+ from arize.pandas.embeddings import EmbeddingGenerator, UseCases
40
+ from arize.pandas.logger import Client
41
+
42
+ self.generator = EmbeddingGenerator.from_use_case(
43
+ use_case=UseCases.NLP.SEQUENCE_CLASSIFICATION,
44
+ model_name="distilbert-base-uncased",
45
+ tokenizer_max_length=512,
46
+ batch_size=256,
47
+ )
48
+ self.arize_client = Client(space_key=SPACE_KEY, api_key=API_KEY)
49
+ if SPACE_KEY == "SPACE_KEY" or API_KEY == "API_KEY":
50
+ raise ValueError("❌ CHANGE SPACE AND API KEYS")
51
+ else:
52
+ print("✅ Arize client setup done! Now you can start using Arize!") # noqa: T201
53
+
54
+ def on_llm_start(
55
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
56
+ ) -> None:
57
+ for prompt in prompts:
58
+ self.prompt_records.append(prompt.replace("\n", ""))
59
+
60
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
61
+ """Do nothing."""
62
+ pass
63
+
64
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
65
+ pd = import_pandas()
66
+ from arize.utils.types import (
67
+ EmbeddingColumnNames,
68
+ Environments,
69
+ ModelTypes,
70
+ Schema,
71
+ )
72
+
73
+ # Safe check if 'llm_output' and 'token_usage' exist
74
+ if response.llm_output and "token_usage" in response.llm_output:
75
+ self.prompt_tokens = response.llm_output["token_usage"].get(
76
+ "prompt_tokens", 0
77
+ )
78
+ self.total_tokens = response.llm_output["token_usage"].get(
79
+ "total_tokens", 0
80
+ )
81
+ self.completion_tokens = response.llm_output["token_usage"].get(
82
+ "completion_tokens", 0
83
+ )
84
+ else:
85
+ self.prompt_tokens = self.total_tokens = self.completion_tokens = (
86
+ 0 # assign default value
87
+ )
88
+
89
+ for generations in response.generations:
90
+ for generation in generations:
91
+ prompt = self.prompt_records[self.step]
92
+ self.step = self.step + 1
93
+ prompt_embedding = pd.Series(
94
+ self.generator.generate_embeddings(
95
+ text_col=pd.Series(prompt.replace("\n", " "))
96
+ ).reset_index(drop=True)
97
+ )
98
+
99
+ # Assigning text to response_text instead of response
100
+ response_text = generation.text.replace("\n", " ")
101
+ response_embedding = pd.Series(
102
+ self.generator.generate_embeddings(
103
+ text_col=pd.Series(generation.text.replace("\n", " "))
104
+ ).reset_index(drop=True)
105
+ )
106
+ pred_timestamp = datetime.now().timestamp()
107
+
108
+ # Define the columns and data
109
+ columns = [
110
+ "prediction_ts",
111
+ "response",
112
+ "prompt",
113
+ "response_vector",
114
+ "prompt_vector",
115
+ "prompt_token",
116
+ "completion_token",
117
+ "total_token",
118
+ ]
119
+ data = [
120
+ [
121
+ pred_timestamp,
122
+ response_text,
123
+ prompt,
124
+ response_embedding[0],
125
+ prompt_embedding[0],
126
+ self.prompt_tokens,
127
+ self.total_tokens,
128
+ self.completion_tokens,
129
+ ]
130
+ ]
131
+
132
+ # Create the DataFrame
133
+ df = pd.DataFrame(data, columns=columns)
134
+
135
+ # Declare prompt and response columns
136
+ prompt_columns = EmbeddingColumnNames(
137
+ vector_column_name="prompt_vector", data_column_name="prompt"
138
+ )
139
+
140
+ response_columns = EmbeddingColumnNames(
141
+ vector_column_name="response_vector", data_column_name="response"
142
+ )
143
+
144
+ schema = Schema(
145
+ timestamp_column_name="prediction_ts",
146
+ tag_column_names=[
147
+ "prompt_token",
148
+ "completion_token",
149
+ "total_token",
150
+ ],
151
+ prompt_column_names=prompt_columns,
152
+ response_column_names=response_columns,
153
+ )
154
+
155
+ response_from_arize = self.arize_client.log(
156
+ dataframe=df,
157
+ schema=schema,
158
+ model_id=self.model_id,
159
+ model_version=self.model_version,
160
+ model_type=ModelTypes.GENERATIVE_LLM,
161
+ environment=Environments.PRODUCTION,
162
+ )
163
+ if response_from_arize.status_code == 200:
164
+ print("✅ Successfully logged data to Arize!") # noqa: T201
165
+ else:
166
+ print(f'❌ Logging failed "{response_from_arize.text}"') # noqa: T201
167
+
168
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
169
+ """Do nothing."""
170
+ pass
171
+
172
+ def on_chain_start(
173
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
174
+ ) -> None:
175
+ pass
176
+
177
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
178
+ """Do nothing."""
179
+ pass
180
+
181
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
182
+ """Do nothing."""
183
+ pass
184
+
185
+ def on_tool_start(
186
+ self,
187
+ serialized: Dict[str, Any],
188
+ input_str: str,
189
+ **kwargs: Any,
190
+ ) -> None:
191
+ pass
192
+
193
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
194
+ """Do nothing."""
195
+ pass
196
+
197
+ def on_tool_end(
198
+ self,
199
+ output: Any,
200
+ observation_prefix: Optional[str] = None,
201
+ llm_prefix: Optional[str] = None,
202
+ **kwargs: Any,
203
+ ) -> None:
204
+ pass
205
+
206
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
207
+ pass
208
+
209
+ def on_text(self, text: str, **kwargs: Any) -> None:
210
+ pass
211
+
212
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
213
+ pass
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arthur_callback.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ArthurAI's Callback Handler."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import uuid
7
+ from collections import defaultdict
8
+ from datetime import datetime
9
+ from time import time
10
+ from typing import TYPE_CHECKING, Any, DefaultDict, Dict, List, Optional
11
+
12
+ import numpy as np
13
+ from langchain_core.agents import AgentAction, AgentFinish
14
+ from langchain_core.callbacks import BaseCallbackHandler
15
+ from langchain_core.outputs import LLMResult
16
+
17
+ if TYPE_CHECKING:
18
+ import arthurai
19
+ from arthurai.core.models import ArthurModel
20
+
21
+ PROMPT_TOKENS = "prompt_tokens"
22
+ COMPLETION_TOKENS = "completion_tokens"
23
+ TOKEN_USAGE = "token_usage"
24
+ FINISH_REASON = "finish_reason"
25
+ DURATION = "duration"
26
+
27
+
28
+ def _lazy_load_arthur() -> arthurai:
29
+ """Lazy load Arthur."""
30
+ try:
31
+ import arthurai
32
+ except ImportError as e:
33
+ raise ImportError(
34
+ "To use the ArthurCallbackHandler you need the"
35
+ " `arthurai` package. Please install it with"
36
+ " `pip install arthurai`.",
37
+ e,
38
+ )
39
+
40
+ return arthurai
41
+
42
+
43
+ class ArthurCallbackHandler(BaseCallbackHandler):
44
+ """Callback Handler that logs to Arthur platform.
45
+
46
+ Arthur helps enterprise teams optimize model operations
47
+ and performance at scale. The Arthur API tracks model
48
+ performance, explainability, and fairness across tabular,
49
+ NLP, and CV models. Our API is model- and platform-agnostic,
50
+ and continuously scales with complex and dynamic enterprise needs.
51
+ To learn more about Arthur, visit our website at
52
+ https://www.arthur.ai/ or read the Arthur docs at
53
+ https://docs.arthur.ai/
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ arthur_model: ArthurModel,
59
+ ) -> None:
60
+ """Initialize callback handler."""
61
+ super().__init__()
62
+ arthurai = _lazy_load_arthur()
63
+ Stage = arthurai.common.constants.Stage
64
+ ValueType = arthurai.common.constants.ValueType
65
+ self.arthur_model = arthur_model
66
+ # save the attributes of this model to be used when preparing
67
+ # inferences to log to Arthur in on_llm_end()
68
+ self.attr_names = set([a.name for a in self.arthur_model.get_attributes()])
69
+ self.input_attr = [
70
+ x
71
+ for x in self.arthur_model.get_attributes()
72
+ if x.stage == Stage.ModelPipelineInput
73
+ and x.value_type == ValueType.Unstructured_Text
74
+ ][0].name
75
+ self.output_attr = [
76
+ x
77
+ for x in self.arthur_model.get_attributes()
78
+ if x.stage == Stage.PredictedValue
79
+ and x.value_type == ValueType.Unstructured_Text
80
+ ][0].name
81
+ self.token_likelihood_attr = None
82
+ if (
83
+ len(
84
+ [
85
+ x
86
+ for x in self.arthur_model.get_attributes()
87
+ if x.value_type == ValueType.TokenLikelihoods
88
+ ]
89
+ )
90
+ > 0
91
+ ):
92
+ self.token_likelihood_attr = [
93
+ x
94
+ for x in self.arthur_model.get_attributes()
95
+ if x.value_type == ValueType.TokenLikelihoods
96
+ ][0].name
97
+
98
+ self.run_map: DefaultDict[str, Any] = defaultdict(dict)
99
+
100
+ @classmethod
101
+ def from_credentials(
102
+ cls,
103
+ model_id: str,
104
+ arthur_url: Optional[str] = "https://app.arthur.ai",
105
+ arthur_login: Optional[str] = None,
106
+ arthur_password: Optional[str] = None,
107
+ ) -> ArthurCallbackHandler:
108
+ """Initialize callback handler from Arthur credentials.
109
+
110
+ Args:
111
+ model_id (str): The ID of the arthur model to log to.
112
+ arthur_url (str, optional): The URL of the Arthur instance to log to.
113
+ Defaults to "https://app.arthur.ai".
114
+ arthur_login (str, optional): The login to use to connect to Arthur.
115
+ Defaults to None.
116
+ arthur_password (str, optional): The password to use to connect to
117
+ Arthur. Defaults to None.
118
+
119
+ Returns:
120
+ ArthurCallbackHandler: The initialized callback handler.
121
+ """
122
+ arthurai = _lazy_load_arthur()
123
+ ArthurAI = arthurai.ArthurAI
124
+ ResponseClientError = arthurai.common.exceptions.ResponseClientError
125
+
126
+ # connect to Arthur
127
+ if arthur_login is None:
128
+ try:
129
+ arthur_api_key = os.environ["ARTHUR_API_KEY"]
130
+ except KeyError:
131
+ raise ValueError(
132
+ "No Arthur authentication provided. Either give"
133
+ " a login to the ArthurCallbackHandler"
134
+ " or set an ARTHUR_API_KEY as an environment variable."
135
+ )
136
+ arthur = ArthurAI(url=arthur_url, access_key=arthur_api_key)
137
+ else:
138
+ if arthur_password is None:
139
+ arthur = ArthurAI(url=arthur_url, login=arthur_login)
140
+ else:
141
+ arthur = ArthurAI(
142
+ url=arthur_url, login=arthur_login, password=arthur_password
143
+ )
144
+ # get model from Arthur by the provided model ID
145
+ try:
146
+ arthur_model = arthur.get_model(model_id)
147
+ except ResponseClientError:
148
+ raise ValueError(
149
+ f"Was unable to retrieve model with id {model_id} from Arthur."
150
+ " Make sure the ID corresponds to a model that is currently"
151
+ " registered with your Arthur account."
152
+ )
153
+ return cls(arthur_model)
154
+
155
+ def on_llm_start(
156
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
157
+ ) -> None:
158
+ """On LLM start, save the input prompts"""
159
+ run_id = kwargs["run_id"]
160
+ self.run_map[run_id]["input_texts"] = prompts
161
+ self.run_map[run_id]["start_time"] = time()
162
+
163
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
164
+ """On LLM end, send data to Arthur."""
165
+ try:
166
+ import pytz
167
+ except ImportError as e:
168
+ raise ImportError(
169
+ "Could not import pytz. Please install it with 'pip install pytz'."
170
+ ) from e
171
+
172
+ run_id = kwargs["run_id"]
173
+
174
+ # get the run params from this run ID,
175
+ # or raise an error if this run ID has no corresponding metadata in self.run_map
176
+ try:
177
+ run_map_data = self.run_map[run_id]
178
+ except KeyError as e:
179
+ raise KeyError(
180
+ "This function has been called with a run_id"
181
+ " that was never registered in on_llm_start()."
182
+ " Restart and try running the LLM again"
183
+ ) from e
184
+
185
+ # mark the duration time between on_llm_start() and on_llm_end()
186
+ time_from_start_to_end = time() - run_map_data["start_time"]
187
+
188
+ # create inferences to log to Arthur
189
+ inferences = []
190
+ for i, generations in enumerate(response.generations):
191
+ for generation in generations:
192
+ inference = {
193
+ "partner_inference_id": str(uuid.uuid4()),
194
+ "inference_timestamp": datetime.now(tz=pytz.UTC),
195
+ self.input_attr: run_map_data["input_texts"][i],
196
+ self.output_attr: generation.text,
197
+ }
198
+
199
+ if generation.generation_info is not None:
200
+ # add finish reason to the inference
201
+ # if generation info contains a finish reason and
202
+ # if the ArthurModel was registered to monitor finish_reason
203
+ if (
204
+ FINISH_REASON in generation.generation_info
205
+ and FINISH_REASON in self.attr_names
206
+ ):
207
+ inference[FINISH_REASON] = generation.generation_info[
208
+ FINISH_REASON
209
+ ]
210
+
211
+ # add token likelihoods data to the inference if the ArthurModel
212
+ # was registered to monitor token likelihoods
213
+ logprobs_data = generation.generation_info["logprobs"]
214
+ if (
215
+ logprobs_data is not None
216
+ and self.token_likelihood_attr is not None
217
+ ):
218
+ logprobs = logprobs_data["top_logprobs"]
219
+ likelihoods = [
220
+ {k: np.exp(v) for k, v in logprobs[i].items()}
221
+ for i in range(len(logprobs))
222
+ ]
223
+ inference[self.token_likelihood_attr] = likelihoods
224
+
225
+ # add token usage counts to the inference if the
226
+ # ArthurModel was registered to monitor token usage
227
+ if (
228
+ isinstance(response.llm_output, dict)
229
+ and TOKEN_USAGE in response.llm_output
230
+ ):
231
+ token_usage = response.llm_output[TOKEN_USAGE]
232
+ if (
233
+ PROMPT_TOKENS in token_usage
234
+ and PROMPT_TOKENS in self.attr_names
235
+ ):
236
+ inference[PROMPT_TOKENS] = token_usage[PROMPT_TOKENS]
237
+ if (
238
+ COMPLETION_TOKENS in token_usage
239
+ and COMPLETION_TOKENS in self.attr_names
240
+ ):
241
+ inference[COMPLETION_TOKENS] = token_usage[COMPLETION_TOKENS]
242
+
243
+ # add inference duration to the inference if the ArthurModel
244
+ # was registered to monitor inference duration
245
+ if DURATION in self.attr_names:
246
+ inference[DURATION] = time_from_start_to_end
247
+
248
+ inferences.append(inference)
249
+
250
+ # send inferences to arthur
251
+ self.arthur_model.send_inferences(inferences)
252
+
253
+ def on_chain_start(
254
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
255
+ ) -> None:
256
+ """On chain start, do nothing."""
257
+
258
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
259
+ """On chain end, do nothing."""
260
+
261
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
262
+ """Do nothing when LLM outputs an error."""
263
+
264
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
265
+ """On new token, pass."""
266
+
267
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
268
+ """Do nothing when LLM chain outputs an error."""
269
+
270
+ def on_tool_start(
271
+ self,
272
+ serialized: Dict[str, Any],
273
+ input_str: str,
274
+ **kwargs: Any,
275
+ ) -> None:
276
+ """Do nothing when tool starts."""
277
+
278
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
279
+ """Do nothing when agent takes a specific action."""
280
+
281
+ def on_tool_end(
282
+ self,
283
+ output: Any,
284
+ observation_prefix: Optional[str] = None,
285
+ llm_prefix: Optional[str] = None,
286
+ **kwargs: Any,
287
+ ) -> None:
288
+ """Do nothing when tool ends."""
289
+
290
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
291
+ """Do nothing when tool outputs an error."""
292
+
293
+ def on_text(self, text: str, **kwargs: Any) -> None:
294
+ """Do nothing"""
295
+
296
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
297
+ """Do nothing"""
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/bedrock_anthropic_callback.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from typing import Any, Dict, List, Union
3
+
4
+ from langchain_core.callbacks import BaseCallbackHandler
5
+ from langchain_core.outputs import LLMResult
6
+
7
+ MODEL_COST_PER_1K_INPUT_TOKENS = {
8
+ "anthropic.claude-instant-v1": 0.0008,
9
+ "anthropic.claude-v2": 0.008,
10
+ "anthropic.claude-v2:1": 0.008,
11
+ "anthropic.claude-3-sonnet-20240229-v1:0": 0.003,
12
+ "anthropic.claude-3-5-sonnet-20240620-v1:0": 0.003,
13
+ "anthropic.claude-3-5-sonnet-20241022-v2:0": 0.003,
14
+ "anthropic.claude-3-7-sonnet-20250219-v1:0": 0.003,
15
+ "anthropic.claude-sonnet-4-20250514-v1:0": 0.003,
16
+ "anthropic.claude-3-haiku-20240307-v1:0": 0.00025,
17
+ "anthropic.claude-3-opus-20240229-v1:0": 0.015,
18
+ "anthropic.claude-opus-4-20250514-v1:0": 0.015,
19
+ "anthropic.claude-3-5-haiku-20241022-v1:0": 0.0008,
20
+ }
21
+
22
+ MODEL_COST_PER_1K_OUTPUT_TOKENS = {
23
+ "anthropic.claude-instant-v1": 0.0024,
24
+ "anthropic.claude-v2": 0.024,
25
+ "anthropic.claude-v2:1": 0.024,
26
+ "anthropic.claude-3-sonnet-20240229-v1:0": 0.015,
27
+ "anthropic.claude-3-5-sonnet-20240620-v1:0": 0.015,
28
+ "anthropic.claude-3-5-sonnet-20241022-v2:0": 0.015,
29
+ "anthropic.claude-3-7-sonnet-20250219-v1:0": 0.015,
30
+ "anthropic.claude-sonnet-4-20250514-v1:0": 0.015,
31
+ "anthropic.claude-3-haiku-20240307-v1:0": 0.00125,
32
+ "anthropic.claude-3-opus-20240229-v1:0": 0.075,
33
+ "anthropic.claude-opus-4-20250514-v1:0": 0.075,
34
+ "anthropic.claude-3-5-haiku-20241022-v1:0": 0.004,
35
+ }
36
+
37
+
38
+ def _get_anthropic_claude_token_cost(
39
+ prompt_tokens: int, completion_tokens: int, model_id: Union[str, None]
40
+ ) -> float:
41
+ if model_id:
42
+ # The model ID can be a cross-region (system-defined) inference profile ID,
43
+ # which has a prefix indicating the region (e.g., 'us', 'eu') but
44
+ # shares the same token costs as the "base model".
45
+ # By extracting the "base model ID", by taking the last two segments
46
+ # of the model ID, we can map cross-region inference profile IDs to
47
+ # their corresponding cost entries.
48
+ base_model_id = model_id.split(".")[-2] + "." + model_id.split(".")[-1]
49
+ else:
50
+ base_model_id = None
51
+ """Get the cost of tokens for the Claude model."""
52
+ if base_model_id not in MODEL_COST_PER_1K_INPUT_TOKENS:
53
+ raise ValueError(
54
+ f"Unknown model: {model_id}. Please provide a valid Anthropic model name."
55
+ "Known models are: " + ", ".join(MODEL_COST_PER_1K_INPUT_TOKENS.keys())
56
+ )
57
+ return (prompt_tokens / 1000) * MODEL_COST_PER_1K_INPUT_TOKENS[base_model_id] + (
58
+ completion_tokens / 1000
59
+ ) * MODEL_COST_PER_1K_OUTPUT_TOKENS[base_model_id]
60
+
61
+
62
+ class BedrockAnthropicTokenUsageCallbackHandler(BaseCallbackHandler):
63
+ """Callback Handler that tracks bedrock anthropic info."""
64
+
65
+ total_tokens: int = 0
66
+ prompt_tokens: int = 0
67
+ completion_tokens: int = 0
68
+ successful_requests: int = 0
69
+ total_cost: float = 0.0
70
+
71
+ def __init__(self) -> None:
72
+ super().__init__()
73
+ self._lock = threading.Lock()
74
+
75
+ def __repr__(self) -> str:
76
+ return (
77
+ f"Tokens Used: {self.total_tokens}\n"
78
+ f"\tPrompt Tokens: {self.prompt_tokens}\n"
79
+ f"\tCompletion Tokens: {self.completion_tokens}\n"
80
+ f"Successful Requests: {self.successful_requests}\n"
81
+ f"Total Cost (USD): ${self.total_cost}"
82
+ )
83
+
84
+ @property
85
+ def always_verbose(self) -> bool:
86
+ """Whether to call verbose callbacks even if verbose is False."""
87
+ return True
88
+
89
+ def on_llm_start(
90
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
91
+ ) -> None:
92
+ """Print out the prompts."""
93
+ pass
94
+
95
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
96
+ """Print out the token."""
97
+ pass
98
+
99
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
100
+ """Collect token usage."""
101
+ if response.llm_output is None:
102
+ return None
103
+
104
+ if "usage" not in response.llm_output:
105
+ with self._lock:
106
+ self.successful_requests += 1
107
+ return None
108
+
109
+ # compute tokens and cost for this request
110
+ token_usage = response.llm_output["usage"]
111
+ completion_tokens = token_usage.get("completion_tokens", 0)
112
+ prompt_tokens = token_usage.get("prompt_tokens", 0)
113
+ total_tokens = token_usage.get("total_tokens", 0)
114
+ model_id = response.llm_output.get("model_id", None)
115
+ total_cost = _get_anthropic_claude_token_cost(
116
+ prompt_tokens=prompt_tokens,
117
+ completion_tokens=completion_tokens,
118
+ model_id=model_id,
119
+ )
120
+
121
+ # update shared state behind lock
122
+ with self._lock:
123
+ self.total_cost += total_cost
124
+ self.total_tokens += total_tokens
125
+ self.prompt_tokens += prompt_tokens
126
+ self.completion_tokens += completion_tokens
127
+ self.successful_requests += 1
128
+
129
+ def __copy__(self) -> "BedrockAnthropicTokenUsageCallbackHandler":
130
+ """Return a copy of the callback handler."""
131
+ return self
132
+
133
+ def __deepcopy__(self, memo: Any) -> "BedrockAnthropicTokenUsageCallbackHandler":
134
+ """Return a deep copy of the callback handler."""
135
+ return self
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/clearml_callback.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import tempfile
4
+ from copy import deepcopy
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence
7
+
8
+ from langchain_core.agents import AgentAction, AgentFinish
9
+ from langchain_core.callbacks import BaseCallbackHandler
10
+ from langchain_core.outputs import LLMResult
11
+ from langchain_core.utils import guard_import
12
+
13
+ from langchain_community.callbacks.utils import (
14
+ BaseMetadataCallbackHandler,
15
+ flatten_dict,
16
+ hash_string,
17
+ import_pandas,
18
+ import_spacy,
19
+ import_textstat,
20
+ load_json,
21
+ )
22
+
23
+ if TYPE_CHECKING:
24
+ import pandas as pd
25
+
26
+
27
+ def import_clearml() -> Any:
28
+ """Import the clearml python package and raise an error if it is not installed."""
29
+ return guard_import("clearml")
30
+
31
+
32
+ class ClearMLCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
33
+ """Callback Handler that logs to ClearML.
34
+
35
+ Parameters:
36
+ job_type (str): The type of clearml task such as "inference", "testing" or "qc"
37
+ project_name (str): The clearml project name
38
+ tags (list): Tags to add to the task
39
+ task_name (str): Name of the clearml task
40
+ visualize (bool): Whether to visualize the run.
41
+ complexity_metrics (bool): Whether to log complexity metrics
42
+ stream_logs (bool): Whether to stream callback actions to ClearML
43
+
44
+ This handler will utilize the associated callback method and formats
45
+ the input of each callback function with metadata regarding the state of LLM run,
46
+ and adds the response to the list of records for both the {method}_records and
47
+ action. It then logs the response to the ClearML console.
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ task_type: Optional[str] = "inference",
53
+ project_name: Optional[str] = "langchain_callback_demo",
54
+ tags: Optional[Sequence] = None,
55
+ task_name: Optional[str] = None,
56
+ visualize: bool = False,
57
+ complexity_metrics: bool = False,
58
+ stream_logs: bool = False,
59
+ ) -> None:
60
+ """Initialize callback handler."""
61
+
62
+ clearml = import_clearml()
63
+ spacy = import_spacy()
64
+ super().__init__()
65
+
66
+ self.task_type = task_type
67
+ self.project_name = project_name
68
+ self.tags = tags
69
+ self.task_name = task_name
70
+ self.visualize = visualize
71
+ self.complexity_metrics = complexity_metrics
72
+ self.stream_logs = stream_logs
73
+
74
+ self.temp_dir = tempfile.TemporaryDirectory()
75
+
76
+ # Check if ClearML task already exists (e.g. in pipeline)
77
+ if clearml.Task.current_task():
78
+ self.task = clearml.Task.current_task()
79
+ else:
80
+ self.task = clearml.Task.init(
81
+ task_type=self.task_type,
82
+ project_name=self.project_name,
83
+ tags=self.tags,
84
+ task_name=self.task_name,
85
+ output_uri=True,
86
+ )
87
+ self.logger = self.task.get_logger()
88
+ warning = (
89
+ "The clearml callback is currently in beta and is subject to change "
90
+ "based on updates to `langchain`. Please report any issues to "
91
+ "https://github.com/allegroai/clearml/issues with the tag `langchain`."
92
+ )
93
+ self.logger.report_text(warning, level=30, print_console=True)
94
+ self.callback_columns: list = []
95
+ self.action_records: list = []
96
+ self.complexity_metrics = complexity_metrics
97
+ self.visualize = visualize
98
+ self.nlp = spacy.load("en_core_web_sm")
99
+
100
+ def _init_resp(self) -> Dict:
101
+ return {k: None for k in self.callback_columns}
102
+
103
+ def on_llm_start(
104
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
105
+ ) -> None:
106
+ """Run when LLM starts."""
107
+ self.step += 1
108
+ self.llm_starts += 1
109
+ self.starts += 1
110
+
111
+ resp = self._init_resp()
112
+ resp.update({"action": "on_llm_start"})
113
+ resp.update(flatten_dict(serialized))
114
+ resp.update(self.get_custom_callback_meta())
115
+
116
+ for prompt in prompts:
117
+ prompt_resp = deepcopy(resp)
118
+ prompt_resp["prompts"] = prompt
119
+ self.on_llm_start_records.append(prompt_resp)
120
+ self.action_records.append(prompt_resp)
121
+ if self.stream_logs:
122
+ self.logger.report_text(prompt_resp)
123
+
124
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
125
+ """Run when LLM generates a new token."""
126
+ self.step += 1
127
+ self.llm_streams += 1
128
+
129
+ resp = self._init_resp()
130
+ resp.update({"action": "on_llm_new_token", "token": token})
131
+ resp.update(self.get_custom_callback_meta())
132
+
133
+ self.on_llm_token_records.append(resp)
134
+ self.action_records.append(resp)
135
+ if self.stream_logs:
136
+ self.logger.report_text(resp)
137
+
138
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
139
+ """Run when LLM ends running."""
140
+ self.step += 1
141
+ self.llm_ends += 1
142
+ self.ends += 1
143
+
144
+ resp = self._init_resp()
145
+ resp.update({"action": "on_llm_end"})
146
+ resp.update(flatten_dict(response.llm_output or {}))
147
+ resp.update(self.get_custom_callback_meta())
148
+
149
+ for generations in response.generations:
150
+ for generation in generations:
151
+ generation_resp = deepcopy(resp)
152
+ generation_resp.update(flatten_dict(generation.dict()))
153
+ generation_resp.update(self.analyze_text(generation.text))
154
+ self.on_llm_end_records.append(generation_resp)
155
+ self.action_records.append(generation_resp)
156
+ if self.stream_logs:
157
+ self.logger.report_text(generation_resp)
158
+
159
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
160
+ """Run when LLM errors."""
161
+ self.step += 1
162
+ self.errors += 1
163
+
164
+ def on_chain_start(
165
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
166
+ ) -> None:
167
+ """Run when chain starts running."""
168
+ self.step += 1
169
+ self.chain_starts += 1
170
+ self.starts += 1
171
+
172
+ resp = self._init_resp()
173
+ resp.update({"action": "on_chain_start"})
174
+ resp.update(flatten_dict(serialized))
175
+ resp.update(self.get_custom_callback_meta())
176
+
177
+ chain_input = inputs.get("input", inputs.get("human_input"))
178
+
179
+ if isinstance(chain_input, str):
180
+ input_resp = deepcopy(resp)
181
+ input_resp["input"] = chain_input
182
+ self.on_chain_start_records.append(input_resp)
183
+ self.action_records.append(input_resp)
184
+ if self.stream_logs:
185
+ self.logger.report_text(input_resp)
186
+ elif isinstance(chain_input, list):
187
+ for inp in chain_input:
188
+ input_resp = deepcopy(resp)
189
+ input_resp.update(inp)
190
+ self.on_chain_start_records.append(input_resp)
191
+ self.action_records.append(input_resp)
192
+ if self.stream_logs:
193
+ self.logger.report_text(input_resp)
194
+ else:
195
+ raise ValueError("Unexpected data format provided!")
196
+
197
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
198
+ """Run when chain ends running."""
199
+ self.step += 1
200
+ self.chain_ends += 1
201
+ self.ends += 1
202
+
203
+ resp = self._init_resp()
204
+ resp.update(
205
+ {
206
+ "action": "on_chain_end",
207
+ "outputs": outputs.get("output", outputs.get("text")),
208
+ }
209
+ )
210
+ resp.update(self.get_custom_callback_meta())
211
+
212
+ self.on_chain_end_records.append(resp)
213
+ self.action_records.append(resp)
214
+ if self.stream_logs:
215
+ self.logger.report_text(resp)
216
+
217
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
218
+ """Run when chain errors."""
219
+ self.step += 1
220
+ self.errors += 1
221
+
222
+ def on_tool_start(
223
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
224
+ ) -> None:
225
+ """Run when tool starts running."""
226
+ self.step += 1
227
+ self.tool_starts += 1
228
+ self.starts += 1
229
+
230
+ resp = self._init_resp()
231
+ resp.update({"action": "on_tool_start", "input_str": input_str})
232
+ resp.update(flatten_dict(serialized))
233
+ resp.update(self.get_custom_callback_meta())
234
+
235
+ self.on_tool_start_records.append(resp)
236
+ self.action_records.append(resp)
237
+ if self.stream_logs:
238
+ self.logger.report_text(resp)
239
+
240
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
241
+ """Run when tool ends running."""
242
+ output = str(output)
243
+ self.step += 1
244
+ self.tool_ends += 1
245
+ self.ends += 1
246
+
247
+ resp = self._init_resp()
248
+ resp.update({"action": "on_tool_end", "output": output})
249
+ resp.update(self.get_custom_callback_meta())
250
+
251
+ self.on_tool_end_records.append(resp)
252
+ self.action_records.append(resp)
253
+ if self.stream_logs:
254
+ self.logger.report_text(resp)
255
+
256
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
257
+ """Run when tool errors."""
258
+ self.step += 1
259
+ self.errors += 1
260
+
261
+ def on_text(self, text: str, **kwargs: Any) -> None:
262
+ """
263
+ Run when agent is ending.
264
+ """
265
+ self.step += 1
266
+ self.text_ctr += 1
267
+
268
+ resp = self._init_resp()
269
+ resp.update({"action": "on_text", "text": text})
270
+ resp.update(self.get_custom_callback_meta())
271
+
272
+ self.on_text_records.append(resp)
273
+ self.action_records.append(resp)
274
+ if self.stream_logs:
275
+ self.logger.report_text(resp)
276
+
277
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
278
+ """Run when agent ends running."""
279
+ self.step += 1
280
+ self.agent_ends += 1
281
+ self.ends += 1
282
+
283
+ resp = self._init_resp()
284
+ resp.update(
285
+ {
286
+ "action": "on_agent_finish",
287
+ "output": finish.return_values["output"],
288
+ "log": finish.log,
289
+ }
290
+ )
291
+ resp.update(self.get_custom_callback_meta())
292
+
293
+ self.on_agent_finish_records.append(resp)
294
+ self.action_records.append(resp)
295
+ if self.stream_logs:
296
+ self.logger.report_text(resp)
297
+
298
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
299
+ """Run on agent action."""
300
+ self.step += 1
301
+ self.tool_starts += 1
302
+ self.starts += 1
303
+
304
+ resp = self._init_resp()
305
+ resp.update(
306
+ {
307
+ "action": "on_agent_action",
308
+ "tool": action.tool,
309
+ "tool_input": action.tool_input,
310
+ "log": action.log,
311
+ }
312
+ )
313
+ resp.update(self.get_custom_callback_meta())
314
+ self.on_agent_action_records.append(resp)
315
+ self.action_records.append(resp)
316
+ if self.stream_logs:
317
+ self.logger.report_text(resp)
318
+
319
+ def analyze_text(self, text: str) -> dict:
320
+ """Analyze text using textstat and spacy.
321
+
322
+ Parameters:
323
+ text (str): The text to analyze.
324
+
325
+ Returns:
326
+ `dict` containing the complexity metrics.
327
+ """
328
+ resp = {}
329
+ textstat = import_textstat()
330
+ spacy = import_spacy()
331
+ if self.complexity_metrics:
332
+ text_complexity_metrics = {
333
+ "flesch_reading_ease": textstat.flesch_reading_ease(text),
334
+ "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
335
+ "smog_index": textstat.smog_index(text),
336
+ "coleman_liau_index": textstat.coleman_liau_index(text),
337
+ "automated_readability_index": textstat.automated_readability_index(
338
+ text
339
+ ),
340
+ "dale_chall_readability_score": textstat.dale_chall_readability_score(
341
+ text
342
+ ),
343
+ "difficult_words": textstat.difficult_words(text),
344
+ "linsear_write_formula": textstat.linsear_write_formula(text),
345
+ "gunning_fog": textstat.gunning_fog(text),
346
+ "text_standard": textstat.text_standard(text),
347
+ "fernandez_huerta": textstat.fernandez_huerta(text),
348
+ "szigriszt_pazos": textstat.szigriszt_pazos(text),
349
+ "gutierrez_polini": textstat.gutierrez_polini(text),
350
+ "crawford": textstat.crawford(text),
351
+ "gulpease_index": textstat.gulpease_index(text),
352
+ "osman": textstat.osman(text),
353
+ }
354
+ resp.update(text_complexity_metrics)
355
+
356
+ if self.visualize and self.nlp and self.temp_dir.name is not None:
357
+ doc = self.nlp(text)
358
+
359
+ dep_out = spacy.displacy.render(doc, style="dep", jupyter=False, page=True)
360
+ dep_output_path = Path(
361
+ self.temp_dir.name, hash_string(f"dep-{text}") + ".html"
362
+ )
363
+ dep_output_path.open("w", encoding="utf-8").write(dep_out)
364
+
365
+ ent_out = spacy.displacy.render(doc, style="ent", jupyter=False, page=True)
366
+ ent_output_path = Path(
367
+ self.temp_dir.name, hash_string(f"ent-{text}") + ".html"
368
+ )
369
+ ent_output_path.open("w", encoding="utf-8").write(ent_out)
370
+
371
+ self.logger.report_media(
372
+ "Dependencies Plot", text, local_path=dep_output_path
373
+ )
374
+ self.logger.report_media("Entities Plot", text, local_path=ent_output_path)
375
+
376
+ return resp
377
+
378
+ @staticmethod
379
+ def _build_llm_df(
380
+ base_df: pd.DataFrame, base_df_fields: Sequence, rename_map: Mapping
381
+ ) -> pd.DataFrame:
382
+ base_df_fields = [field for field in base_df_fields if field in base_df]
383
+ rename_map = {
384
+ map_entry_k: map_entry_v
385
+ for map_entry_k, map_entry_v in rename_map.items()
386
+ if map_entry_k in base_df_fields
387
+ }
388
+ llm_df = base_df[base_df_fields].dropna(axis=1)
389
+ if rename_map:
390
+ llm_df = llm_df.rename(rename_map, axis=1)
391
+ return llm_df
392
+
393
+ def _create_session_analysis_df(self) -> Any:
394
+ """Create a dataframe with all the information from the session."""
395
+ pd = import_pandas()
396
+ on_llm_end_records_df = pd.DataFrame(self.on_llm_end_records)
397
+
398
+ llm_input_prompts_df = ClearMLCallbackHandler._build_llm_df(
399
+ base_df=on_llm_end_records_df,
400
+ base_df_fields=["step", "prompts"]
401
+ + (["name"] if "name" in on_llm_end_records_df else ["id"]),
402
+ rename_map={"step": "prompt_step"},
403
+ )
404
+ complexity_metrics_columns = []
405
+ visualizations_columns: List = []
406
+
407
+ if self.complexity_metrics:
408
+ complexity_metrics_columns = [
409
+ "flesch_reading_ease",
410
+ "flesch_kincaid_grade",
411
+ "smog_index",
412
+ "coleman_liau_index",
413
+ "automated_readability_index",
414
+ "dale_chall_readability_score",
415
+ "difficult_words",
416
+ "linsear_write_formula",
417
+ "gunning_fog",
418
+ "text_standard",
419
+ "fernandez_huerta",
420
+ "szigriszt_pazos",
421
+ "gutierrez_polini",
422
+ "crawford",
423
+ "gulpease_index",
424
+ "osman",
425
+ ]
426
+
427
+ llm_outputs_df = ClearMLCallbackHandler._build_llm_df(
428
+ on_llm_end_records_df,
429
+ [
430
+ "step",
431
+ "text",
432
+ "token_usage_total_tokens",
433
+ "token_usage_prompt_tokens",
434
+ "token_usage_completion_tokens",
435
+ ]
436
+ + complexity_metrics_columns
437
+ + visualizations_columns,
438
+ {"step": "output_step", "text": "output"},
439
+ )
440
+ session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1)
441
+ return session_analysis_df
442
+
443
+ def flush_tracker(
444
+ self,
445
+ name: Optional[str] = None,
446
+ langchain_asset: Any = None,
447
+ finish: bool = False,
448
+ ) -> None:
449
+ """Flush the tracker and setup the session.
450
+
451
+ Everything after this will be a new table.
452
+
453
+ Args:
454
+ name: Name of the performed session so far so it is identifiable
455
+ langchain_asset: The langchain asset to save.
456
+ finish: Whether to finish the run.
457
+
458
+ Returns:
459
+ None
460
+ """
461
+ pd = import_pandas()
462
+ clearml = import_clearml()
463
+
464
+ # Log the action records
465
+ self.logger.report_table(
466
+ "Action Records", name, table_plot=pd.DataFrame(self.action_records)
467
+ )
468
+
469
+ # Session analysis
470
+ session_analysis_df = self._create_session_analysis_df()
471
+ self.logger.report_table(
472
+ "Session Analysis", name, table_plot=session_analysis_df
473
+ )
474
+
475
+ if self.stream_logs:
476
+ self.logger.report_text(
477
+ {
478
+ "action_records": pd.DataFrame(self.action_records),
479
+ "session_analysis": session_analysis_df,
480
+ }
481
+ )
482
+
483
+ if langchain_asset:
484
+ langchain_asset_path = Path(self.temp_dir.name, "model.json")
485
+ try:
486
+ langchain_asset.save(langchain_asset_path)
487
+ # Create output model and connect it to the task
488
+ output_model = clearml.OutputModel(
489
+ task=self.task, config_text=load_json(langchain_asset_path)
490
+ )
491
+ output_model.update_weights(
492
+ weights_filename=str(langchain_asset_path),
493
+ auto_delete_file=False,
494
+ target_filename=name,
495
+ )
496
+ except ValueError:
497
+ langchain_asset.save_agent(langchain_asset_path)
498
+ output_model = clearml.OutputModel(
499
+ task=self.task, config_text=load_json(langchain_asset_path)
500
+ )
501
+ output_model.update_weights(
502
+ weights_filename=str(langchain_asset_path),
503
+ auto_delete_file=False,
504
+ target_filename=name,
505
+ )
506
+ except NotImplementedError as e:
507
+ print("Could not save model.") # noqa: T201
508
+ print(repr(e)) # noqa: T201
509
+ pass
510
+
511
+ # Cleanup after adding everything to ClearML
512
+ self.task.flush(wait_for_uploads=True)
513
+ self.temp_dir.cleanup()
514
+ self.temp_dir = tempfile.TemporaryDirectory()
515
+ self.reset_callback_meta()
516
+
517
+ if finish:
518
+ self.task.close()
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/comet_ml_callback.py ADDED
@@ -0,0 +1,639 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ from copy import deepcopy
3
+ from pathlib import Path
4
+ from typing import Any, Callable, Dict, List, Optional, Sequence
5
+
6
+ from langchain_core.agents import AgentAction, AgentFinish
7
+ from langchain_core.callbacks import BaseCallbackHandler
8
+ from langchain_core.outputs import Generation, LLMResult
9
+ from langchain_core.utils import guard_import
10
+
11
+ import langchain_community
12
+ from langchain_community.callbacks.utils import (
13
+ BaseMetadataCallbackHandler,
14
+ flatten_dict,
15
+ import_pandas,
16
+ import_spacy,
17
+ import_textstat,
18
+ )
19
+
20
+ LANGCHAIN_MODEL_NAME = "langchain-model"
21
+
22
+
23
+ def import_comet_ml() -> Any:
24
+ """Import comet_ml and raise an error if it is not installed."""
25
+ return guard_import("comet_ml")
26
+
27
+
28
+ def _get_experiment(
29
+ workspace: Optional[str] = None, project_name: Optional[str] = None
30
+ ) -> Any:
31
+ comet_ml = import_comet_ml()
32
+
33
+ experiment = comet_ml.Experiment(
34
+ workspace=workspace,
35
+ project_name=project_name,
36
+ )
37
+
38
+ return experiment
39
+
40
+
41
+ def _fetch_text_complexity_metrics(text: str) -> dict:
42
+ textstat = import_textstat()
43
+ text_complexity_metrics = {
44
+ "flesch_reading_ease": textstat.flesch_reading_ease(text),
45
+ "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
46
+ "smog_index": textstat.smog_index(text),
47
+ "coleman_liau_index": textstat.coleman_liau_index(text),
48
+ "automated_readability_index": textstat.automated_readability_index(text),
49
+ "dale_chall_readability_score": textstat.dale_chall_readability_score(text),
50
+ "difficult_words": textstat.difficult_words(text),
51
+ "linsear_write_formula": textstat.linsear_write_formula(text),
52
+ "gunning_fog": textstat.gunning_fog(text),
53
+ "text_standard": textstat.text_standard(text),
54
+ "fernandez_huerta": textstat.fernandez_huerta(text),
55
+ "szigriszt_pazos": textstat.szigriszt_pazos(text),
56
+ "gutierrez_polini": textstat.gutierrez_polini(text),
57
+ "crawford": textstat.crawford(text),
58
+ "gulpease_index": textstat.gulpease_index(text),
59
+ "osman": textstat.osman(text),
60
+ }
61
+ return text_complexity_metrics
62
+
63
+
64
+ def _summarize_metrics_for_generated_outputs(metrics: Sequence) -> dict:
65
+ pd = import_pandas()
66
+ metrics_df = pd.DataFrame(metrics)
67
+ metrics_summary = metrics_df.describe()
68
+
69
+ return metrics_summary.to_dict()
70
+
71
+
72
+ class CometCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
73
+ """Callback Handler that logs to Comet.
74
+
75
+ Parameters:
76
+ job_type (str): The type of comet_ml task such as "inference",
77
+ "testing" or "qc"
78
+ project_name (str): The comet_ml project name
79
+ tags (list): Tags to add to the task
80
+ task_name (str): Name of the comet_ml task
81
+ visualize (bool): Whether to visualize the run.
82
+ complexity_metrics (bool): Whether to log complexity metrics
83
+ stream_logs (bool): Whether to stream callback actions to Comet
84
+
85
+ This handler will utilize the associated callback method and formats
86
+ the input of each callback function with metadata regarding the state of LLM run,
87
+ and adds the response to the list of records for both the {method}_records and
88
+ action. It then logs the response to Comet.
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ task_type: Optional[str] = "inference",
94
+ workspace: Optional[str] = None,
95
+ project_name: Optional[str] = None,
96
+ tags: Optional[Sequence] = None,
97
+ name: Optional[str] = None,
98
+ visualizations: Optional[List[str]] = None,
99
+ complexity_metrics: bool = False,
100
+ custom_metrics: Optional[Callable] = None,
101
+ stream_logs: bool = True,
102
+ ) -> None:
103
+ """Initialize callback handler."""
104
+
105
+ self.comet_ml = import_comet_ml()
106
+ super().__init__()
107
+
108
+ self.task_type = task_type
109
+ self.workspace = workspace
110
+ self.project_name = project_name
111
+ self.tags = tags
112
+ self.visualizations = visualizations
113
+ self.complexity_metrics = complexity_metrics
114
+ self.custom_metrics = custom_metrics
115
+ self.stream_logs = stream_logs
116
+ self.temp_dir = tempfile.TemporaryDirectory()
117
+
118
+ self.experiment = _get_experiment(workspace, project_name)
119
+ self.experiment.log_other("Created from", "langchain")
120
+ if tags:
121
+ self.experiment.add_tags(tags)
122
+ self.name = name
123
+ if self.name:
124
+ self.experiment.set_name(self.name)
125
+
126
+ warning = (
127
+ "The comet_ml callback is currently in beta and is subject to change "
128
+ "based on updates to `langchain`. Please report any issues to "
129
+ "https://github.com/comet-ml/issue-tracking/issues with the tag "
130
+ "`langchain`."
131
+ )
132
+ self.comet_ml.LOGGER.warning(warning)
133
+
134
+ self.callback_columns: list = []
135
+ self.action_records: list = []
136
+ self.complexity_metrics = complexity_metrics
137
+ if self.visualizations:
138
+ spacy = import_spacy()
139
+ self.nlp = spacy.load("en_core_web_sm")
140
+ else:
141
+ self.nlp = None
142
+
143
+ def _init_resp(self) -> Dict:
144
+ return {k: None for k in self.callback_columns}
145
+
146
+ def on_llm_start(
147
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
148
+ ) -> None:
149
+ """Run when LLM starts."""
150
+ self.step += 1
151
+ self.llm_starts += 1
152
+ self.starts += 1
153
+
154
+ metadata = self._init_resp()
155
+ metadata.update({"action": "on_llm_start"})
156
+ metadata.update(flatten_dict(serialized))
157
+ metadata.update(self.get_custom_callback_meta())
158
+
159
+ for prompt in prompts:
160
+ prompt_resp = deepcopy(metadata)
161
+ prompt_resp["prompts"] = prompt
162
+ self.on_llm_start_records.append(prompt_resp)
163
+ self.action_records.append(prompt_resp)
164
+
165
+ if self.stream_logs:
166
+ self._log_stream(prompt, metadata, self.step)
167
+
168
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
169
+ """Run when LLM generates a new token."""
170
+ self.step += 1
171
+ self.llm_streams += 1
172
+
173
+ resp = self._init_resp()
174
+ resp.update({"action": "on_llm_new_token", "token": token})
175
+ resp.update(self.get_custom_callback_meta())
176
+
177
+ self.action_records.append(resp)
178
+
179
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
180
+ """Run when LLM ends running."""
181
+ self.step += 1
182
+ self.llm_ends += 1
183
+ self.ends += 1
184
+
185
+ metadata = self._init_resp()
186
+ metadata.update({"action": "on_llm_end"})
187
+ metadata.update(flatten_dict(response.llm_output or {}))
188
+ metadata.update(self.get_custom_callback_meta())
189
+
190
+ output_complexity_metrics = []
191
+ output_custom_metrics = []
192
+
193
+ for prompt_idx, generations in enumerate(response.generations):
194
+ for gen_idx, generation in enumerate(generations):
195
+ text = generation.text
196
+
197
+ generation_resp = deepcopy(metadata)
198
+ generation_resp.update(flatten_dict(generation.dict()))
199
+
200
+ complexity_metrics = self._get_complexity_metrics(text)
201
+ if complexity_metrics:
202
+ output_complexity_metrics.append(complexity_metrics)
203
+ generation_resp.update(complexity_metrics)
204
+
205
+ custom_metrics = self._get_custom_metrics(
206
+ generation, prompt_idx, gen_idx
207
+ )
208
+ if custom_metrics:
209
+ output_custom_metrics.append(custom_metrics)
210
+ generation_resp.update(custom_metrics)
211
+
212
+ if self.stream_logs:
213
+ self._log_stream(text, metadata, self.step)
214
+
215
+ self.action_records.append(generation_resp)
216
+ self.on_llm_end_records.append(generation_resp)
217
+
218
+ self._log_text_metrics(output_complexity_metrics, step=self.step)
219
+ self._log_text_metrics(output_custom_metrics, step=self.step)
220
+
221
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
222
+ """Run when LLM errors."""
223
+ self.step += 1
224
+ self.errors += 1
225
+
226
+ def on_chain_start(
227
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
228
+ ) -> None:
229
+ """Run when chain starts running."""
230
+ self.step += 1
231
+ self.chain_starts += 1
232
+ self.starts += 1
233
+
234
+ resp = self._init_resp()
235
+ resp.update({"action": "on_chain_start"})
236
+ resp.update(flatten_dict(serialized))
237
+ resp.update(self.get_custom_callback_meta())
238
+
239
+ for chain_input_key, chain_input_val in inputs.items():
240
+ if isinstance(chain_input_val, str):
241
+ input_resp = deepcopy(resp)
242
+ if self.stream_logs:
243
+ self._log_stream(chain_input_val, resp, self.step)
244
+ input_resp.update({chain_input_key: chain_input_val})
245
+ self.action_records.append(input_resp)
246
+
247
+ else:
248
+ self.comet_ml.LOGGER.warning(
249
+ f"Unexpected data format provided! "
250
+ f"Input Value for {chain_input_key} will not be logged"
251
+ )
252
+
253
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
254
+ """Run when chain ends running."""
255
+ self.step += 1
256
+ self.chain_ends += 1
257
+ self.ends += 1
258
+
259
+ resp = self._init_resp()
260
+ resp.update({"action": "on_chain_end"})
261
+ resp.update(self.get_custom_callback_meta())
262
+
263
+ for chain_output_key, chain_output_val in outputs.items():
264
+ if isinstance(chain_output_val, str):
265
+ output_resp = deepcopy(resp)
266
+ if self.stream_logs:
267
+ self._log_stream(chain_output_val, resp, self.step)
268
+ output_resp.update({chain_output_key: chain_output_val})
269
+ self.action_records.append(output_resp)
270
+ else:
271
+ self.comet_ml.LOGGER.warning(
272
+ f"Unexpected data format provided! "
273
+ f"Output Value for {chain_output_key} will not be logged"
274
+ )
275
+
276
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
277
+ """Run when chain errors."""
278
+ self.step += 1
279
+ self.errors += 1
280
+
281
+ def on_tool_start(
282
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
283
+ ) -> None:
284
+ """Run when tool starts running."""
285
+ self.step += 1
286
+ self.tool_starts += 1
287
+ self.starts += 1
288
+
289
+ resp = self._init_resp()
290
+ resp.update({"action": "on_tool_start"})
291
+ resp.update(flatten_dict(serialized))
292
+ resp.update(self.get_custom_callback_meta())
293
+ if self.stream_logs:
294
+ self._log_stream(input_str, resp, self.step)
295
+
296
+ resp.update({"input_str": input_str})
297
+ self.action_records.append(resp)
298
+
299
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
300
+ """Run when tool ends running."""
301
+ output = str(output)
302
+ self.step += 1
303
+ self.tool_ends += 1
304
+ self.ends += 1
305
+
306
+ resp = self._init_resp()
307
+ resp.update({"action": "on_tool_end"})
308
+ resp.update(self.get_custom_callback_meta())
309
+ if self.stream_logs:
310
+ self._log_stream(output, resp, self.step)
311
+
312
+ resp.update({"output": output})
313
+ self.action_records.append(resp)
314
+
315
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
316
+ """Run when tool errors."""
317
+ self.step += 1
318
+ self.errors += 1
319
+
320
+ def on_text(self, text: str, **kwargs: Any) -> None:
321
+ """
322
+ Run when agent is ending.
323
+ """
324
+ self.step += 1
325
+ self.text_ctr += 1
326
+
327
+ resp = self._init_resp()
328
+ resp.update({"action": "on_text"})
329
+ resp.update(self.get_custom_callback_meta())
330
+ if self.stream_logs:
331
+ self._log_stream(text, resp, self.step)
332
+
333
+ resp.update({"text": text})
334
+ self.action_records.append(resp)
335
+
336
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
337
+ """Run when agent ends running."""
338
+ self.step += 1
339
+ self.agent_ends += 1
340
+ self.ends += 1
341
+
342
+ resp = self._init_resp()
343
+ output = finish.return_values["output"]
344
+ log = finish.log
345
+
346
+ resp.update({"action": "on_agent_finish", "log": log})
347
+ resp.update(self.get_custom_callback_meta())
348
+ if self.stream_logs:
349
+ self._log_stream(output, resp, self.step)
350
+
351
+ resp.update({"output": output})
352
+ self.action_records.append(resp)
353
+
354
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
355
+ """Run on agent action."""
356
+ self.step += 1
357
+ self.tool_starts += 1
358
+ self.starts += 1
359
+
360
+ tool = action.tool
361
+ tool_input = str(action.tool_input)
362
+ log = action.log
363
+
364
+ resp = self._init_resp()
365
+ resp.update({"action": "on_agent_action", "log": log, "tool": tool})
366
+ resp.update(self.get_custom_callback_meta())
367
+ if self.stream_logs:
368
+ self._log_stream(tool_input, resp, self.step)
369
+
370
+ resp.update({"tool_input": tool_input})
371
+ self.action_records.append(resp)
372
+
373
+ def _get_complexity_metrics(self, text: str) -> dict:
374
+ """Compute text complexity metrics using textstat.
375
+
376
+ Parameters:
377
+ text (str): The text to analyze.
378
+
379
+ Returns:
380
+ `dict` containing the complexity metrics.
381
+ """
382
+ resp = {}
383
+ if self.complexity_metrics:
384
+ text_complexity_metrics = _fetch_text_complexity_metrics(text)
385
+ resp.update(text_complexity_metrics)
386
+
387
+ return resp
388
+
389
+ def _get_custom_metrics(
390
+ self, generation: Generation, prompt_idx: int, gen_idx: int
391
+ ) -> dict:
392
+ """Compute Custom Metrics for an LLM Generated Output
393
+
394
+ Args:
395
+ generation (LLMResult): Output generation from an LLM
396
+ prompt_idx (int): List index of the input prompt
397
+ gen_idx (int): List index of the generated output
398
+
399
+ Returns:
400
+ dict: `dict` containing the custom metrics.
401
+ """
402
+
403
+ resp = {}
404
+ if self.custom_metrics:
405
+ custom_metrics = self.custom_metrics(generation, prompt_idx, gen_idx)
406
+ resp.update(custom_metrics)
407
+
408
+ return resp
409
+
410
+ def flush_tracker(
411
+ self,
412
+ langchain_asset: Any = None,
413
+ task_type: Optional[str] = "inference",
414
+ workspace: Optional[str] = None,
415
+ project_name: Optional[str] = "comet-langchain-demo",
416
+ tags: Optional[Sequence] = None,
417
+ name: Optional[str] = None,
418
+ visualizations: Optional[List[str]] = None,
419
+ complexity_metrics: bool = False,
420
+ custom_metrics: Optional[Callable] = None,
421
+ finish: bool = False,
422
+ reset: bool = False,
423
+ ) -> None:
424
+ """Flush the tracker and setup the session.
425
+
426
+ Everything after this will be a new table.
427
+
428
+ Args:
429
+ name: Name of the performed session so far so it is identifiable
430
+ langchain_asset: The langchain asset to save.
431
+ finish: Whether to finish the run.
432
+
433
+ Returns:
434
+ None
435
+ """
436
+ self._log_session(langchain_asset)
437
+
438
+ if langchain_asset:
439
+ try:
440
+ self._log_model(langchain_asset)
441
+ except Exception:
442
+ self.comet_ml.LOGGER.error(
443
+ "Failed to export agent or LLM to Comet",
444
+ exc_info=True,
445
+ extra={"show_traceback": True},
446
+ )
447
+
448
+ if finish:
449
+ self.experiment.end()
450
+
451
+ if reset:
452
+ self._reset(
453
+ task_type,
454
+ workspace,
455
+ project_name,
456
+ tags,
457
+ name,
458
+ visualizations,
459
+ complexity_metrics,
460
+ custom_metrics,
461
+ )
462
+
463
+ def _log_stream(self, prompt: str, metadata: dict, step: int) -> None:
464
+ self.experiment.log_text(prompt, metadata=metadata, step=step)
465
+
466
+ def _log_model(self, langchain_asset: Any) -> None:
467
+ model_parameters = self._get_llm_parameters(langchain_asset)
468
+ self.experiment.log_parameters(model_parameters, prefix="model")
469
+
470
+ langchain_asset_path = Path(self.temp_dir.name, "model.json")
471
+ model_name = self.name if self.name else LANGCHAIN_MODEL_NAME
472
+
473
+ try:
474
+ if hasattr(langchain_asset, "save"):
475
+ langchain_asset.save(langchain_asset_path)
476
+ self.experiment.log_model(model_name, str(langchain_asset_path))
477
+ except (ValueError, AttributeError, NotImplementedError) as e:
478
+ if hasattr(langchain_asset, "save_agent"):
479
+ langchain_asset.save_agent(langchain_asset_path)
480
+ self.experiment.log_model(model_name, str(langchain_asset_path))
481
+ else:
482
+ self.comet_ml.LOGGER.error(
483
+ f"{e}"
484
+ " Could not save Langchain Asset "
485
+ f"for {langchain_asset.__class__.__name__}"
486
+ )
487
+
488
+ def _log_session(self, langchain_asset: Optional[Any] = None) -> None:
489
+ try:
490
+ llm_session_df = self._create_session_analysis_dataframe(langchain_asset)
491
+ # Log the cleaned dataframe as a table
492
+ self.experiment.log_table("langchain-llm-session.csv", llm_session_df)
493
+ except Exception:
494
+ self.comet_ml.LOGGER.warning(
495
+ "Failed to log session data to Comet",
496
+ exc_info=True,
497
+ extra={"show_traceback": True},
498
+ )
499
+
500
+ try:
501
+ metadata = {"langchain_version": str(langchain_community.__version__)}
502
+ # Log the langchain low-level records as a JSON file directly
503
+ self.experiment.log_asset_data(
504
+ self.action_records, "langchain-action_records.json", metadata=metadata
505
+ )
506
+ except Exception:
507
+ self.comet_ml.LOGGER.warning(
508
+ "Failed to log session data to Comet",
509
+ exc_info=True,
510
+ extra={"show_traceback": True},
511
+ )
512
+
513
+ try:
514
+ self._log_visualizations(llm_session_df)
515
+ except Exception:
516
+ self.comet_ml.LOGGER.warning(
517
+ "Failed to log visualizations to Comet",
518
+ exc_info=True,
519
+ extra={"show_traceback": True},
520
+ )
521
+
522
+ def _log_text_metrics(self, metrics: Sequence[dict], step: int) -> None:
523
+ if not metrics:
524
+ return
525
+
526
+ metrics_summary = _summarize_metrics_for_generated_outputs(metrics)
527
+ for key, value in metrics_summary.items():
528
+ self.experiment.log_metrics(value, prefix=key, step=step)
529
+
530
+ def _log_visualizations(self, session_df: Any) -> None:
531
+ if not (self.visualizations and self.nlp):
532
+ return
533
+
534
+ spacy = import_spacy()
535
+
536
+ prompts = session_df["prompts"].tolist()
537
+ outputs = session_df["text"].tolist()
538
+
539
+ for idx, (prompt, output) in enumerate(zip(prompts, outputs)):
540
+ doc = self.nlp(output)
541
+ sentence_spans = list(doc.sents)
542
+
543
+ for visualization in self.visualizations:
544
+ try:
545
+ html = spacy.displacy.render(
546
+ sentence_spans,
547
+ style=visualization,
548
+ options={"compact": True},
549
+ jupyter=False,
550
+ page=True,
551
+ )
552
+ self.experiment.log_asset_data(
553
+ html,
554
+ name=f"langchain-viz-{visualization}-{idx}.html",
555
+ metadata={"prompt": prompt},
556
+ step=idx,
557
+ )
558
+ except Exception as e:
559
+ self.comet_ml.LOGGER.warning(
560
+ e, exc_info=True, extra={"show_traceback": True}
561
+ )
562
+
563
+ return
564
+
565
+ def _reset(
566
+ self,
567
+ task_type: Optional[str] = None,
568
+ workspace: Optional[str] = None,
569
+ project_name: Optional[str] = None,
570
+ tags: Optional[Sequence] = None,
571
+ name: Optional[str] = None,
572
+ visualizations: Optional[List[str]] = None,
573
+ complexity_metrics: bool = False,
574
+ custom_metrics: Optional[Callable] = None,
575
+ ) -> None:
576
+ _task_type = task_type if task_type else self.task_type
577
+ _workspace = workspace if workspace else self.workspace
578
+ _project_name = project_name if project_name else self.project_name
579
+ _tags = tags if tags else self.tags
580
+ _name = name if name else self.name
581
+ _visualizations = visualizations if visualizations else self.visualizations
582
+ _complexity_metrics = (
583
+ complexity_metrics if complexity_metrics else self.complexity_metrics
584
+ )
585
+ _custom_metrics = custom_metrics if custom_metrics else self.custom_metrics
586
+
587
+ self.__init__( # type: ignore[misc]
588
+ task_type=_task_type,
589
+ workspace=_workspace,
590
+ project_name=_project_name,
591
+ tags=_tags,
592
+ name=_name,
593
+ visualizations=_visualizations,
594
+ complexity_metrics=_complexity_metrics,
595
+ custom_metrics=_custom_metrics,
596
+ )
597
+
598
+ self.reset_callback_meta()
599
+ self.temp_dir = tempfile.TemporaryDirectory()
600
+
601
+ def _create_session_analysis_dataframe(self, langchain_asset: Any = None) -> dict:
602
+ pd = import_pandas()
603
+
604
+ llm_parameters = self._get_llm_parameters(langchain_asset)
605
+ num_generations_per_prompt = llm_parameters.get("n", 1)
606
+
607
+ llm_start_records_df = pd.DataFrame(self.on_llm_start_records)
608
+ # Repeat each input row based on the number of outputs generated per prompt
609
+ llm_start_records_df = llm_start_records_df.loc[
610
+ llm_start_records_df.index.repeat(num_generations_per_prompt)
611
+ ].reset_index(drop=True)
612
+ llm_end_records_df = pd.DataFrame(self.on_llm_end_records)
613
+
614
+ llm_session_df = pd.merge(
615
+ llm_start_records_df,
616
+ llm_end_records_df,
617
+ left_index=True,
618
+ right_index=True,
619
+ suffixes=["_llm_start", "_llm_end"],
620
+ )
621
+
622
+ return llm_session_df
623
+
624
+ def _get_llm_parameters(self, langchain_asset: Any = None) -> dict:
625
+ if not langchain_asset:
626
+ return {}
627
+ try:
628
+ if hasattr(langchain_asset, "agent"):
629
+ llm_parameters = langchain_asset.agent.llm_chain.llm.dict()
630
+ elif hasattr(langchain_asset, "llm_chain"):
631
+ llm_parameters = langchain_asset.llm_chain.llm.dict()
632
+ elif hasattr(langchain_asset, "llm"):
633
+ llm_parameters = langchain_asset.llm.dict()
634
+ else:
635
+ llm_parameters = langchain_asset.dict()
636
+ except Exception:
637
+ return {}
638
+
639
+ return llm_parameters
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/confident_callback.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+ import os
3
+ import warnings
4
+ from typing import Any, Dict, List, Optional, Union
5
+
6
+ from langchain_core.callbacks import BaseCallbackHandler
7
+ from langchain_core.agents import AgentAction, AgentFinish
8
+ from langchain_core.outputs import LLMResult
9
+
10
+
11
+ class DeepEvalCallbackHandler(BaseCallbackHandler):
12
+ """Callback Handler that logs into deepeval.
13
+
14
+ Args:
15
+ implementation_name: name of the `implementation` in deepeval
16
+ metrics: A list of metrics
17
+
18
+ Raises:
19
+ ImportError: if the `deepeval` package is not installed.
20
+
21
+ Examples:
22
+ >>> from langchain_community.llms import OpenAI
23
+ >>> from langchain_community.callbacks import DeepEvalCallbackHandler
24
+ >>> from deepeval.metrics import AnswerRelevancy
25
+ >>> metric = AnswerRelevancy(minimum_score=0.3)
26
+ >>> deepeval_callback = DeepEvalCallbackHandler(
27
+ ... implementation_name="exampleImplementation",
28
+ ... metrics=[metric],
29
+ ... )
30
+ >>> llm = OpenAI(
31
+ ... temperature=0,
32
+ ... callbacks=[deepeval_callback],
33
+ ... verbose=True,
34
+ ... openai_api_key="API_KEY_HERE",
35
+ ... )
36
+ >>> llm.generate([
37
+ ... "What is the best evaluation tool out there? (no bias at all)",
38
+ ... ])
39
+ "Deepeval, no doubt about it."
40
+ """
41
+
42
+ REPO_URL: str = "https://github.com/confident-ai/deepeval"
43
+ ISSUES_URL: str = f"{REPO_URL}/issues"
44
+ BLOG_URL: str = "https://docs.confident-ai.com" # noqa: E501
45
+
46
+ def __init__(
47
+ self,
48
+ metrics: List[Any],
49
+ implementation_name: Optional[str] = None,
50
+ ) -> None:
51
+ """Initializes the `deepevalCallbackHandler`.
52
+
53
+ Args:
54
+ implementation_name: Name of the implementation you want.
55
+ metrics: What metrics do you want to track?
56
+
57
+ Raises:
58
+ ImportError: if the `deepeval` package is not installed.
59
+ ConnectionError: if the connection to deepeval fails.
60
+ """
61
+
62
+ super().__init__()
63
+
64
+ # Import deepeval (not via `import_deepeval` to keep hints in IDEs)
65
+ try:
66
+ import deepeval # ignore: F401,I001
67
+ except ImportError:
68
+ raise ImportError(
69
+ """To use the deepeval callback manager you need to have the
70
+ `deepeval` Python package installed. Please install it with
71
+ `pip install deepeval`"""
72
+ )
73
+
74
+ if os.path.exists(".deepeval"):
75
+ warnings.warn(
76
+ """You are currently not logging anything to the dashboard, we
77
+ recommend using `deepeval login`."""
78
+ )
79
+
80
+ # Set the deepeval variables
81
+ self.implementation_name = implementation_name
82
+ self.metrics = metrics
83
+
84
+ warnings.warn(
85
+ (
86
+ "The `DeepEvalCallbackHandler` is currently in beta and is subject to"
87
+ " change based on updates to `langchain`. Please report any issues to"
88
+ f" {self.ISSUES_URL} as an `integration` issue."
89
+ ),
90
+ )
91
+
92
+ def on_llm_start(
93
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
94
+ ) -> None:
95
+ """Store the prompts"""
96
+ self.prompts = prompts
97
+
98
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
99
+ """Do nothing when a new token is generated."""
100
+ pass
101
+
102
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
103
+ """Log records to deepeval when an LLM ends."""
104
+ from deepeval.metrics.answer_relevancy import AnswerRelevancy
105
+ from deepeval.metrics.bias_classifier import UnBiasedMetric
106
+ from deepeval.metrics.metric import Metric
107
+ from deepeval.metrics.toxic_classifier import NonToxicMetric
108
+
109
+ for metric in self.metrics:
110
+ for i, generation in enumerate(response.generations):
111
+ # Here, we only measure the first generation's output
112
+ output = generation[0].text
113
+ query = self.prompts[i]
114
+ if isinstance(metric, AnswerRelevancy):
115
+ result = metric.measure(
116
+ output=output,
117
+ query=query,
118
+ )
119
+ print(f"Answer Relevancy: {result}") # noqa: T201
120
+ elif isinstance(metric, UnBiasedMetric):
121
+ score = metric.measure(output)
122
+ print(f"Bias Score: {score}") # noqa: T201
123
+ elif isinstance(metric, NonToxicMetric):
124
+ score = metric.measure(output)
125
+ print(f"Toxic Score: {score}") # noqa: T201
126
+ else:
127
+ raise ValueError(
128
+ f"""Metric {metric.__name__} is not supported by deepeval
129
+ callbacks."""
130
+ )
131
+
132
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
133
+ """Do nothing when LLM outputs an error."""
134
+ pass
135
+
136
+ def on_chain_start(
137
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
138
+ ) -> None:
139
+ """Do nothing when chain starts"""
140
+ pass
141
+
142
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
143
+ """Do nothing when chain ends."""
144
+ pass
145
+
146
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
147
+ """Do nothing when LLM chain outputs an error."""
148
+ pass
149
+
150
+ def on_tool_start(
151
+ self,
152
+ serialized: Dict[str, Any],
153
+ input_str: str,
154
+ **kwargs: Any,
155
+ ) -> None:
156
+ """Do nothing when tool starts."""
157
+ pass
158
+
159
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
160
+ """Do nothing when agent takes a specific action."""
161
+ pass
162
+
163
+ def on_tool_end(
164
+ self,
165
+ output: Any,
166
+ observation_prefix: Optional[str] = None,
167
+ llm_prefix: Optional[str] = None,
168
+ **kwargs: Any,
169
+ ) -> None:
170
+ """Do nothing when tool ends."""
171
+ pass
172
+
173
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
174
+ """Do nothing when tool outputs an error."""
175
+ pass
176
+
177
+ def on_text(self, text: str, **kwargs: Any) -> None:
178
+ """Do nothing"""
179
+ pass
180
+
181
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
182
+ """Do nothing"""
183
+ pass
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/context_callback.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Callback handler for Context AI"""
2
+
3
+ import os
4
+ from typing import Any, Dict, List
5
+ from uuid import UUID
6
+
7
+ from langchain_core.callbacks import BaseCallbackHandler
8
+ from langchain_core.messages import BaseMessage
9
+ from langchain_core.outputs import LLMResult
10
+ from langchain_core.utils import guard_import
11
+
12
+
13
+ def import_context() -> Any:
14
+ """Import the `getcontext` package."""
15
+ return (
16
+ guard_import("getcontext", pip_name="python-context"),
17
+ guard_import("getcontext.token", pip_name="python-context").Credential,
18
+ guard_import(
19
+ "getcontext.generated.models", pip_name="python-context"
20
+ ).Conversation,
21
+ guard_import("getcontext.generated.models", pip_name="python-context").Message,
22
+ guard_import(
23
+ "getcontext.generated.models", pip_name="python-context"
24
+ ).MessageRole,
25
+ guard_import("getcontext.generated.models", pip_name="python-context").Rating,
26
+ )
27
+
28
+
29
+ class ContextCallbackHandler(BaseCallbackHandler):
30
+ """Callback Handler that records transcripts to the Context service.
31
+
32
+ (https://context.ai).
33
+
34
+ Keyword Args:
35
+ token (optional): The token with which to authenticate requests to Context.
36
+ Visit https://with.context.ai/settings to generate a token.
37
+ If not provided, the value of the `CONTEXT_TOKEN` environment
38
+ variable will be used.
39
+
40
+ Raises:
41
+ ImportError: if the `context-python` package is not installed.
42
+
43
+ Chat Example:
44
+ >>> from langchain_community.llms import ChatOpenAI
45
+ >>> from langchain_community.callbacks import ContextCallbackHandler
46
+ >>> context_callback = ContextCallbackHandler(
47
+ ... token="<CONTEXT_TOKEN_HERE>",
48
+ ... )
49
+ >>> chat = ChatOpenAI(
50
+ ... temperature=0,
51
+ ... headers={"user_id": "123"},
52
+ ... callbacks=[context_callback],
53
+ ... openai_api_key="API_KEY_HERE",
54
+ ... )
55
+ >>> messages = [
56
+ ... SystemMessage(content="You translate English to French."),
57
+ ... HumanMessage(content="I love programming with LangChain."),
58
+ ... ]
59
+ >>> chat.invoke(messages)
60
+
61
+ Chain Example:
62
+ >>> from langchain_classic.chains import LLMChain
63
+ >>> from langchain_community.chat_models import ChatOpenAI
64
+ >>> from langchain_community.callbacks import ContextCallbackHandler
65
+ >>> context_callback = ContextCallbackHandler(
66
+ ... token="<CONTEXT_TOKEN_HERE>",
67
+ ... )
68
+ >>> human_message_prompt = HumanMessagePromptTemplate(
69
+ ... prompt=PromptTemplate(
70
+ ... template="What is a good name for a company that makes {product}?",
71
+ ... input_variables=["product"],
72
+ ... ),
73
+ ... )
74
+ >>> chat_prompt_template = ChatPromptTemplate.from_messages(
75
+ ... [human_message_prompt]
76
+ ... )
77
+ >>> callback = ContextCallbackHandler(token)
78
+ >>> # Note: the same callback object must be shared between the
79
+ ... LLM and the chain.
80
+ >>> chat = ChatOpenAI(temperature=0.9, callbacks=[callback])
81
+ >>> chain = LLMChain(
82
+ ... llm=chat,
83
+ ... prompt=chat_prompt_template,
84
+ ... callbacks=[callback]
85
+ ... )
86
+ >>> chain.run("colorful socks")
87
+ """
88
+
89
+ def __init__(self, token: str = "", verbose: bool = False, **kwargs: Any) -> None:
90
+ (
91
+ self.context,
92
+ self.credential,
93
+ self.conversation_model,
94
+ self.message_model,
95
+ self.message_role_model,
96
+ self.rating_model,
97
+ ) = import_context()
98
+
99
+ token = token or os.environ.get("CONTEXT_TOKEN") or ""
100
+
101
+ self.client = self.context.ContextAPI(credential=self.credential(token))
102
+
103
+ self.chain_run_id = None
104
+
105
+ self.llm_model = None
106
+
107
+ self.messages: List[Any] = []
108
+ self.metadata: Dict[str, str] = {}
109
+
110
+ def on_chat_model_start(
111
+ self,
112
+ serialized: Dict[str, Any],
113
+ messages: List[List[BaseMessage]],
114
+ *,
115
+ run_id: UUID,
116
+ **kwargs: Any,
117
+ ) -> Any:
118
+ """Run when the chat model is started."""
119
+ llm_model = kwargs.get("invocation_params", {}).get("model", None)
120
+ if llm_model is not None:
121
+ self.metadata["model"] = llm_model
122
+
123
+ if len(messages) == 0:
124
+ return
125
+
126
+ for message in messages[0]:
127
+ role = self.message_role_model.SYSTEM
128
+ if message.type == "human":
129
+ role = self.message_role_model.USER
130
+ elif message.type == "system":
131
+ role = self.message_role_model.SYSTEM
132
+ elif message.type == "ai":
133
+ role = self.message_role_model.ASSISTANT
134
+
135
+ self.messages.append(
136
+ self.message_model(
137
+ message=message.content,
138
+ role=role,
139
+ )
140
+ )
141
+
142
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
143
+ """Run when LLM ends."""
144
+ if len(response.generations) == 0 or len(response.generations[0]) == 0:
145
+ return
146
+
147
+ if not self.chain_run_id:
148
+ generation = response.generations[0][0]
149
+ self.messages.append(
150
+ self.message_model(
151
+ message=generation.text,
152
+ role=self.message_role_model.ASSISTANT,
153
+ )
154
+ )
155
+
156
+ self._log_conversation()
157
+
158
+ def on_chain_start(
159
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
160
+ ) -> None:
161
+ """Run when chain starts."""
162
+ self.chain_run_id = kwargs.get("run_id", None)
163
+
164
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
165
+ """Run when chain ends."""
166
+ self.messages.append(
167
+ self.message_model(
168
+ message=outputs["text"],
169
+ role=self.message_role_model.ASSISTANT,
170
+ )
171
+ )
172
+
173
+ self._log_conversation()
174
+
175
+ self.chain_run_id = None
176
+
177
+ def _log_conversation(self) -> None:
178
+ """Log the conversation to the context API."""
179
+ if len(self.messages) == 0:
180
+ return
181
+
182
+ self.client.log.conversation_upsert(
183
+ body={
184
+ "conversation": self.conversation_model(
185
+ messages=self.messages,
186
+ metadata=self.metadata,
187
+ )
188
+ }
189
+ )
190
+
191
+ self.messages = []
192
+ self.metadata = {}
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/fiddler_callback.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from typing import Any, Dict, List, Optional
3
+ from uuid import UUID
4
+
5
+ from langchain_core.callbacks import BaseCallbackHandler
6
+ from langchain_core.outputs import LLMResult
7
+ from langchain_core.utils import guard_import
8
+
9
+ from langchain_community.callbacks.utils import import_pandas
10
+
11
+ # Define constants
12
+
13
+ # LLMResult keys
14
+ TOKEN_USAGE = "token_usage"
15
+ TOTAL_TOKENS = "total_tokens"
16
+ PROMPT_TOKENS = "prompt_tokens"
17
+ COMPLETION_TOKENS = "completion_tokens"
18
+ RUN_ID = "run_id"
19
+ MODEL_NAME = "model_name"
20
+ GOOD = "good"
21
+ BAD = "bad"
22
+ NEUTRAL = "neutral"
23
+ SUCCESS = "success"
24
+ FAILURE = "failure"
25
+
26
+ # Default values
27
+ DEFAULT_MAX_TOKEN = 65536
28
+ DEFAULT_MAX_DURATION = 120000
29
+
30
+ # Fiddler specific constants
31
+ PROMPT = "prompt"
32
+ RESPONSE = "response"
33
+ CONTEXT = "context"
34
+ DURATION = "duration"
35
+ FEEDBACK = "feedback"
36
+ LLM_STATUS = "llm_status"
37
+
38
+ FEEDBACK_POSSIBLE_VALUES = [GOOD, BAD, NEUTRAL]
39
+
40
+ # Define a dataset dictionary
41
+ _dataset_dict = {
42
+ PROMPT: ["fiddler"] * 10,
43
+ RESPONSE: ["fiddler"] * 10,
44
+ CONTEXT: ["fiddler"] * 10,
45
+ FEEDBACK: ["good"] * 10,
46
+ LLM_STATUS: ["success"] * 10,
47
+ MODEL_NAME: ["fiddler"] * 10,
48
+ RUN_ID: ["123e4567-e89b-12d3-a456-426614174000"] * 10,
49
+ TOTAL_TOKENS: [0, DEFAULT_MAX_TOKEN] * 5,
50
+ PROMPT_TOKENS: [0, DEFAULT_MAX_TOKEN] * 5,
51
+ COMPLETION_TOKENS: [0, DEFAULT_MAX_TOKEN] * 5,
52
+ DURATION: [1, DEFAULT_MAX_DURATION] * 5,
53
+ }
54
+
55
+
56
+ def import_fiddler() -> Any:
57
+ """Import the fiddler python package and raise an error if it is not installed."""
58
+ return guard_import("fiddler", pip_name="fiddler-client")
59
+
60
+
61
+ # First, define custom callback handler implementations
62
+ class FiddlerCallbackHandler(BaseCallbackHandler):
63
+ def __init__(
64
+ self,
65
+ url: str,
66
+ org: str,
67
+ project: str,
68
+ model: str,
69
+ api_key: str,
70
+ ) -> None:
71
+ """
72
+ Initialize Fiddler callback handler.
73
+
74
+ Args:
75
+ url: Fiddler URL (e.g. https://demo.fiddler.ai).
76
+ Make sure to include the protocol (http/https).
77
+ org: Fiddler organization id
78
+ project: Fiddler project name to publish events to
79
+ model: Fiddler model name to publish events to
80
+ api_key: Fiddler authentication token
81
+ """
82
+ super().__init__()
83
+ # Initialize Fiddler client and other necessary properties
84
+ self.fdl = import_fiddler()
85
+ self.pd = import_pandas()
86
+
87
+ self.url = url
88
+ self.org = org
89
+ self.project = project
90
+ self.model = model
91
+ self.api_key = api_key
92
+ self._df = self.pd.DataFrame(_dataset_dict)
93
+
94
+ self.run_id_prompts: Dict[UUID, List[str]] = {}
95
+ self.run_id_response: Dict[UUID, List[str]] = {}
96
+ self.run_id_starttime: Dict[UUID, int] = {}
97
+
98
+ # Initialize Fiddler client here
99
+ self.fiddler_client = self.fdl.FiddlerApi(url, org_id=org, auth_token=api_key)
100
+
101
+ if self.project not in self.fiddler_client.get_project_names():
102
+ print( # noqa: T201
103
+ f"adding project {self.project}.This only has to be done once."
104
+ )
105
+ try:
106
+ self.fiddler_client.add_project(self.project)
107
+ except Exception as e:
108
+ print( # noqa: T201
109
+ f"Error adding project {self.project}:"
110
+ "{e}. Fiddler integration will not work."
111
+ )
112
+ raise e
113
+
114
+ dataset_info = self.fdl.DatasetInfo.from_dataframe(
115
+ self._df, max_inferred_cardinality=0
116
+ )
117
+
118
+ # Set feedback column to categorical
119
+ for i in range(len(dataset_info.columns)):
120
+ if dataset_info.columns[i].name == FEEDBACK:
121
+ dataset_info.columns[i].data_type = self.fdl.DataType.CATEGORY
122
+ dataset_info.columns[i].possible_values = FEEDBACK_POSSIBLE_VALUES
123
+
124
+ elif dataset_info.columns[i].name == LLM_STATUS:
125
+ dataset_info.columns[i].data_type = self.fdl.DataType.CATEGORY
126
+ dataset_info.columns[i].possible_values = [SUCCESS, FAILURE]
127
+
128
+ if self.model not in self.fiddler_client.get_model_names(self.project):
129
+ if self.model not in self.fiddler_client.get_dataset_names(self.project):
130
+ print( # noqa: T201
131
+ f"adding dataset {self.model} to project {self.project}."
132
+ "This only has to be done once."
133
+ )
134
+ try:
135
+ self.fiddler_client.upload_dataset(
136
+ project_id=self.project,
137
+ dataset_id=self.model,
138
+ dataset={"train": self._df},
139
+ info=dataset_info,
140
+ )
141
+ except Exception as e:
142
+ print( # noqa: T201
143
+ f"Error adding dataset {self.model}: {e}."
144
+ "Fiddler integration will not work."
145
+ )
146
+ raise e
147
+
148
+ model_info = self.fdl.ModelInfo.from_dataset_info(
149
+ dataset_info=dataset_info,
150
+ dataset_id="train",
151
+ model_task=self.fdl.ModelTask.LLM,
152
+ features=[PROMPT, CONTEXT, RESPONSE],
153
+ target=FEEDBACK,
154
+ metadata_cols=[
155
+ RUN_ID,
156
+ TOTAL_TOKENS,
157
+ PROMPT_TOKENS,
158
+ COMPLETION_TOKENS,
159
+ MODEL_NAME,
160
+ DURATION,
161
+ ],
162
+ custom_features=self.custom_features,
163
+ )
164
+ print( # noqa: T201
165
+ f"adding model {self.model} to project {self.project}."
166
+ "This only has to be done once."
167
+ )
168
+ try:
169
+ self.fiddler_client.add_model(
170
+ project_id=self.project,
171
+ dataset_id=self.model,
172
+ model_id=self.model,
173
+ model_info=model_info,
174
+ )
175
+ except Exception as e:
176
+ print( # noqa: T201
177
+ f"Error adding model {self.model}: {e}."
178
+ "Fiddler integration will not work."
179
+ )
180
+ raise e
181
+
182
+ @property
183
+ def custom_features(self) -> list:
184
+ """
185
+ Define custom features for the model to automatically enrich the data with.
186
+ Here, we enable the following enrichments:
187
+ - Automatic Embedding generation for prompt and response
188
+ - Text Statistics such as:
189
+ - Automated Readability Index
190
+ - Coleman Liau Index
191
+ - Dale Chall Readability Score
192
+ - Difficult Words
193
+ - Flesch Reading Ease
194
+ - Flesch Kincaid Grade
195
+ - Gunning Fog
196
+ - Linsear Write Formula
197
+ - PII - Personal Identifiable Information
198
+ - Sentiment Analysis
199
+
200
+ """
201
+
202
+ return [
203
+ self.fdl.Enrichment(
204
+ name="Prompt Embedding",
205
+ enrichment="embedding",
206
+ columns=[PROMPT],
207
+ ),
208
+ self.fdl.TextEmbedding(
209
+ name="Prompt CF",
210
+ source_column=PROMPT,
211
+ column="Prompt Embedding",
212
+ ),
213
+ self.fdl.Enrichment(
214
+ name="Response Embedding",
215
+ enrichment="embedding",
216
+ columns=[RESPONSE],
217
+ ),
218
+ self.fdl.TextEmbedding(
219
+ name="Response CF",
220
+ source_column=RESPONSE,
221
+ column="Response Embedding",
222
+ ),
223
+ self.fdl.Enrichment(
224
+ name="Text Statistics",
225
+ enrichment="textstat",
226
+ columns=[PROMPT, RESPONSE],
227
+ config={
228
+ "statistics": [
229
+ "automated_readability_index",
230
+ "coleman_liau_index",
231
+ "dale_chall_readability_score",
232
+ "difficult_words",
233
+ "flesch_reading_ease",
234
+ "flesch_kincaid_grade",
235
+ "gunning_fog",
236
+ "linsear_write_formula",
237
+ ]
238
+ },
239
+ ),
240
+ self.fdl.Enrichment(
241
+ name="PII",
242
+ enrichment="pii",
243
+ columns=[PROMPT, RESPONSE],
244
+ ),
245
+ self.fdl.Enrichment(
246
+ name="Sentiment",
247
+ enrichment="sentiment",
248
+ columns=[PROMPT, RESPONSE],
249
+ ),
250
+ ]
251
+
252
+ def _publish_events(
253
+ self,
254
+ run_id: UUID,
255
+ prompt_responses: List[str],
256
+ duration: int,
257
+ llm_status: str,
258
+ model_name: Optional[str] = "",
259
+ token_usage_dict: Optional[Dict[str, Any]] = None,
260
+ ) -> None:
261
+ """
262
+ Publish events to fiddler
263
+ """
264
+
265
+ prompt_count = len(self.run_id_prompts[run_id])
266
+ df = self.pd.DataFrame(
267
+ {
268
+ PROMPT: self.run_id_prompts[run_id],
269
+ RESPONSE: prompt_responses,
270
+ RUN_ID: [str(run_id)] * prompt_count,
271
+ DURATION: [duration] * prompt_count,
272
+ LLM_STATUS: [llm_status] * prompt_count,
273
+ MODEL_NAME: [model_name] * prompt_count,
274
+ }
275
+ )
276
+
277
+ if token_usage_dict:
278
+ for key, value in token_usage_dict.items():
279
+ df[key] = [value] * prompt_count if isinstance(value, int) else value
280
+
281
+ try:
282
+ if df.shape[0] > 1:
283
+ self.fiddler_client.publish_events_batch(self.project, self.model, df)
284
+ else:
285
+ df_dict = df.to_dict(orient="records")
286
+ self.fiddler_client.publish_event(
287
+ self.project, self.model, event=df_dict[0]
288
+ )
289
+ except Exception as e:
290
+ print( # noqa: T201
291
+ f"Error publishing events to fiddler: {e}. continuing..."
292
+ )
293
+
294
+ def on_llm_start(
295
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
296
+ ) -> Any:
297
+ run_id = kwargs[RUN_ID]
298
+ self.run_id_prompts[run_id] = prompts
299
+ self.run_id_starttime[run_id] = int(time.time() * 1000)
300
+
301
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
302
+ flattened_llmresult = response.flatten()
303
+ run_id = kwargs[RUN_ID]
304
+ run_duration = int(time.time() * 1000) - self.run_id_starttime[run_id]
305
+ model_name = ""
306
+ token_usage_dict = {}
307
+
308
+ if isinstance(response.llm_output, dict):
309
+ token_usage_dict = {
310
+ k: v
311
+ for k, v in response.llm_output.items()
312
+ if k in [TOTAL_TOKENS, PROMPT_TOKENS, COMPLETION_TOKENS]
313
+ }
314
+ model_name = response.llm_output.get(MODEL_NAME, "")
315
+
316
+ prompt_responses = [
317
+ llmresult.generations[0][0].text for llmresult in flattened_llmresult
318
+ ]
319
+
320
+ self._publish_events(
321
+ run_id,
322
+ prompt_responses,
323
+ run_duration,
324
+ SUCCESS,
325
+ model_name,
326
+ token_usage_dict,
327
+ )
328
+
329
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
330
+ run_id = kwargs[RUN_ID]
331
+ duration = int(time.time() * 1000) - self.run_id_starttime[run_id]
332
+
333
+ self._publish_events(
334
+ run_id, [""] * len(self.run_id_prompts[run_id]), duration, FAILURE
335
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/flyte_callback.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FlyteKit callback handler."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from copy import deepcopy
7
+ from typing import TYPE_CHECKING, Any, Dict, List, Tuple
8
+
9
+ from langchain_core.agents import AgentAction, AgentFinish
10
+ from langchain_core.callbacks import BaseCallbackHandler
11
+ from langchain_core.outputs import LLMResult
12
+ from langchain_core.utils import guard_import
13
+
14
+ from langchain_community.callbacks.utils import (
15
+ BaseMetadataCallbackHandler,
16
+ flatten_dict,
17
+ import_pandas,
18
+ import_spacy,
19
+ import_textstat,
20
+ )
21
+
22
+ if TYPE_CHECKING:
23
+ import flytekit
24
+ from flytekitplugins.deck import renderer
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def import_flytekit() -> Tuple[flytekit, renderer]:
30
+ """Import flytekit and flytekitplugins-deck-standard."""
31
+ return (
32
+ guard_import("flytekit"),
33
+ guard_import(
34
+ "flytekitplugins.deck", pip_name="flytekitplugins-deck-standard"
35
+ ).renderer,
36
+ )
37
+
38
+
39
+ def analyze_text(
40
+ text: str,
41
+ nlp: Any = None,
42
+ textstat: Any = None,
43
+ ) -> dict:
44
+ """Analyze text using textstat and spacy.
45
+
46
+ Parameters:
47
+ text (str): The text to analyze.
48
+ nlp (spacy.lang): The spacy language model to use for visualization.
49
+
50
+ Returns:
51
+ `dict` containing the complexity metrics and visualization
52
+ files serialized to HTML string.
53
+ """
54
+ resp: Dict[str, Any] = {}
55
+ if textstat is not None:
56
+ text_complexity_metrics = {
57
+ "flesch_reading_ease": textstat.flesch_reading_ease(text),
58
+ "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
59
+ "smog_index": textstat.smog_index(text),
60
+ "coleman_liau_index": textstat.coleman_liau_index(text),
61
+ "automated_readability_index": textstat.automated_readability_index(text),
62
+ "dale_chall_readability_score": textstat.dale_chall_readability_score(text),
63
+ "difficult_words": textstat.difficult_words(text),
64
+ "linsear_write_formula": textstat.linsear_write_formula(text),
65
+ "gunning_fog": textstat.gunning_fog(text),
66
+ "fernandez_huerta": textstat.fernandez_huerta(text),
67
+ "szigriszt_pazos": textstat.szigriszt_pazos(text),
68
+ "gutierrez_polini": textstat.gutierrez_polini(text),
69
+ "crawford": textstat.crawford(text),
70
+ "gulpease_index": textstat.gulpease_index(text),
71
+ "osman": textstat.osman(text),
72
+ }
73
+ resp.update({"text_complexity_metrics": text_complexity_metrics})
74
+ resp.update(text_complexity_metrics)
75
+
76
+ if nlp is not None:
77
+ spacy = import_spacy()
78
+ doc = nlp(text)
79
+ dep_out = spacy.displacy.render(doc, style="dep", jupyter=False, page=True)
80
+ ent_out = spacy.displacy.render(doc, style="ent", jupyter=False, page=True)
81
+ text_visualizations = {
82
+ "dependency_tree": dep_out,
83
+ "entities": ent_out,
84
+ }
85
+ resp.update(text_visualizations)
86
+
87
+ return resp
88
+
89
+
90
+ class FlyteCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
91
+ """Callback handler that is used within a Flyte task."""
92
+
93
+ def __init__(self) -> None:
94
+ """Initialize callback handler."""
95
+ flytekit, renderer = import_flytekit()
96
+ self.pandas = import_pandas()
97
+
98
+ self.textstat = None
99
+ try:
100
+ self.textstat = import_textstat()
101
+ except ImportError:
102
+ logger.warning(
103
+ "Textstat library is not installed. \
104
+ It may result in the inability to log \
105
+ certain metrics that can be captured with Textstat."
106
+ )
107
+
108
+ spacy = None
109
+ try:
110
+ spacy = import_spacy()
111
+ except ImportError:
112
+ logger.warning(
113
+ "Spacy library is not installed. \
114
+ It may result in the inability to log \
115
+ certain metrics that can be captured with Spacy."
116
+ )
117
+
118
+ super().__init__()
119
+
120
+ self.nlp = None
121
+ if spacy:
122
+ try:
123
+ self.nlp = spacy.load("en_core_web_sm")
124
+ except OSError:
125
+ logger.warning(
126
+ "FlyteCallbackHandler uses spacy's en_core_web_sm model"
127
+ " for certain metrics. To download,"
128
+ " run the following command in your terminal:"
129
+ " `python -m spacy download en_core_web_sm`"
130
+ )
131
+
132
+ self.table_renderer = renderer.TableRenderer
133
+ self.markdown_renderer = renderer.MarkdownRenderer
134
+
135
+ self.deck = flytekit.Deck(
136
+ "LangChain Metrics",
137
+ self.markdown_renderer().to_html("## LangChain Metrics"),
138
+ )
139
+
140
+ def on_llm_start(
141
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
142
+ ) -> None:
143
+ """Run when LLM starts."""
144
+
145
+ self.step += 1
146
+ self.llm_starts += 1
147
+ self.starts += 1
148
+
149
+ resp: Dict[str, Any] = {}
150
+ resp.update({"action": "on_llm_start"})
151
+ resp.update(flatten_dict(serialized))
152
+ resp.update(self.get_custom_callback_meta())
153
+
154
+ prompt_responses = []
155
+ for prompt in prompts:
156
+ prompt_responses.append(prompt)
157
+
158
+ resp.update({"prompts": prompt_responses})
159
+
160
+ self.deck.append(self.markdown_renderer().to_html("### LLM Start"))
161
+ self.deck.append(
162
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
163
+ )
164
+
165
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
166
+ """Run when LLM generates a new token."""
167
+
168
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
169
+ """Run when LLM ends running."""
170
+ self.step += 1
171
+ self.llm_ends += 1
172
+ self.ends += 1
173
+
174
+ resp: Dict[str, Any] = {}
175
+ resp.update({"action": "on_llm_end"})
176
+ resp.update(flatten_dict(response.llm_output or {}))
177
+ resp.update(self.get_custom_callback_meta())
178
+
179
+ self.deck.append(self.markdown_renderer().to_html("### LLM End"))
180
+ self.deck.append(self.table_renderer().to_html(self.pandas.DataFrame([resp])))
181
+
182
+ for generations in response.generations:
183
+ for generation in generations:
184
+ generation_resp = deepcopy(resp)
185
+ generation_resp.update(flatten_dict(generation.dict()))
186
+ if self.nlp or self.textstat:
187
+ generation_resp.update(
188
+ analyze_text(
189
+ generation.text, nlp=self.nlp, textstat=self.textstat
190
+ )
191
+ )
192
+
193
+ complexity_metrics: Dict[str, float] = generation_resp.pop(
194
+ "text_complexity_metrics"
195
+ )
196
+ self.deck.append(
197
+ self.markdown_renderer().to_html("#### Text Complexity Metrics")
198
+ )
199
+ self.deck.append(
200
+ self.table_renderer().to_html(
201
+ self.pandas.DataFrame([complexity_metrics])
202
+ )
203
+ + "\n"
204
+ )
205
+
206
+ dependency_tree = generation_resp["dependency_tree"]
207
+ self.deck.append(
208
+ self.markdown_renderer().to_html("#### Dependency Tree")
209
+ )
210
+ self.deck.append(dependency_tree)
211
+
212
+ entities = generation_resp["entities"]
213
+ self.deck.append(self.markdown_renderer().to_html("#### Entities"))
214
+ self.deck.append(entities)
215
+ else:
216
+ self.deck.append(
217
+ self.markdown_renderer().to_html("#### Generated Response")
218
+ )
219
+ self.deck.append(self.markdown_renderer().to_html(generation.text))
220
+
221
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
222
+ """Run when LLM errors."""
223
+ self.step += 1
224
+ self.errors += 1
225
+
226
+ def on_chain_start(
227
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
228
+ ) -> None:
229
+ """Run when chain starts running."""
230
+ self.step += 1
231
+ self.chain_starts += 1
232
+ self.starts += 1
233
+
234
+ resp: Dict[str, Any] = {}
235
+ resp.update({"action": "on_chain_start"})
236
+ resp.update(flatten_dict(serialized))
237
+ resp.update(self.get_custom_callback_meta())
238
+
239
+ chain_input = ",".join([f"{k}={v}" for k, v in inputs.items()])
240
+ input_resp = deepcopy(resp)
241
+ input_resp["inputs"] = chain_input
242
+
243
+ self.deck.append(self.markdown_renderer().to_html("### Chain Start"))
244
+ self.deck.append(
245
+ self.table_renderer().to_html(self.pandas.DataFrame([input_resp])) + "\n"
246
+ )
247
+
248
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
249
+ """Run when chain ends running."""
250
+ self.step += 1
251
+ self.chain_ends += 1
252
+ self.ends += 1
253
+
254
+ resp: Dict[str, Any] = {}
255
+ chain_output = ",".join([f"{k}={v}" for k, v in outputs.items()])
256
+ resp.update({"action": "on_chain_end", "outputs": chain_output})
257
+ resp.update(self.get_custom_callback_meta())
258
+
259
+ self.deck.append(self.markdown_renderer().to_html("### Chain End"))
260
+ self.deck.append(
261
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
262
+ )
263
+
264
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
265
+ """Run when chain errors."""
266
+ self.step += 1
267
+ self.errors += 1
268
+
269
+ def on_tool_start(
270
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
271
+ ) -> None:
272
+ """Run when tool starts running."""
273
+ self.step += 1
274
+ self.tool_starts += 1
275
+ self.starts += 1
276
+
277
+ resp: Dict[str, Any] = {}
278
+ resp.update({"action": "on_tool_start", "input_str": input_str})
279
+ resp.update(flatten_dict(serialized))
280
+ resp.update(self.get_custom_callback_meta())
281
+
282
+ self.deck.append(self.markdown_renderer().to_html("### Tool Start"))
283
+ self.deck.append(
284
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
285
+ )
286
+
287
+ def on_tool_end(self, output: str, **kwargs: Any) -> None:
288
+ """Run when tool ends running."""
289
+ self.step += 1
290
+ self.tool_ends += 1
291
+ self.ends += 1
292
+
293
+ resp: Dict[str, Any] = {}
294
+ resp.update({"action": "on_tool_end", "output": output})
295
+ resp.update(self.get_custom_callback_meta())
296
+
297
+ self.deck.append(self.markdown_renderer().to_html("### Tool End"))
298
+ self.deck.append(
299
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
300
+ )
301
+
302
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
303
+ """Run when tool errors."""
304
+ self.step += 1
305
+ self.errors += 1
306
+
307
+ def on_text(self, text: str, **kwargs: Any) -> None:
308
+ """
309
+ Run when agent is ending.
310
+ """
311
+ self.step += 1
312
+ self.text_ctr += 1
313
+
314
+ resp: Dict[str, Any] = {}
315
+ resp.update({"action": "on_text", "text": text})
316
+ resp.update(self.get_custom_callback_meta())
317
+
318
+ self.deck.append(self.markdown_renderer().to_html("### On Text"))
319
+ self.deck.append(
320
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
321
+ )
322
+
323
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
324
+ """Run when agent ends running."""
325
+ self.step += 1
326
+ self.agent_ends += 1
327
+ self.ends += 1
328
+
329
+ resp: Dict[str, Any] = {}
330
+ resp.update(
331
+ {
332
+ "action": "on_agent_finish",
333
+ "output": finish.return_values["output"],
334
+ "log": finish.log,
335
+ }
336
+ )
337
+ resp.update(self.get_custom_callback_meta())
338
+
339
+ self.deck.append(self.markdown_renderer().to_html("### Agent Finish"))
340
+ self.deck.append(
341
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
342
+ )
343
+
344
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
345
+ """Run on agent action."""
346
+ self.step += 1
347
+ self.tool_starts += 1
348
+ self.starts += 1
349
+
350
+ resp: Dict[str, Any] = {}
351
+ resp.update(
352
+ {
353
+ "action": "on_agent_action",
354
+ "tool": action.tool,
355
+ "tool_input": action.tool_input,
356
+ "log": action.log,
357
+ }
358
+ )
359
+ resp.update(self.get_custom_callback_meta())
360
+
361
+ self.deck.append(self.markdown_renderer().to_html("### Agent Action"))
362
+ self.deck.append(
363
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
364
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/human.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Awaitable, Callable, Dict, Optional
2
+ from uuid import UUID
3
+
4
+ from langchain_core.callbacks import AsyncCallbackHandler, BaseCallbackHandler
5
+
6
+
7
+ def _default_approve(_input: str) -> bool:
8
+ msg = (
9
+ "Do you approve of the following input? "
10
+ "Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no."
11
+ )
12
+ msg += "\n\n" + _input + "\n"
13
+ resp = input(msg)
14
+ return resp.lower() in ("yes", "y")
15
+
16
+
17
+ async def _adefault_approve(_input: str) -> bool:
18
+ msg = (
19
+ "Do you approve of the following input? "
20
+ "Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no."
21
+ )
22
+ msg += "\n\n" + _input + "\n"
23
+ resp = input(msg)
24
+ return resp.lower() in ("yes", "y")
25
+
26
+
27
+ def _default_true(_: Dict[str, Any]) -> bool:
28
+ return True
29
+
30
+
31
+ class HumanRejectedException(Exception):
32
+ """Exception to raise when a person manually review and rejects a value."""
33
+
34
+
35
+ class HumanApprovalCallbackHandler(BaseCallbackHandler):
36
+ """Callback for manually validating values."""
37
+
38
+ raise_error: bool = True
39
+
40
+ def __init__(
41
+ self,
42
+ approve: Callable[[Any], bool] = _default_approve,
43
+ should_check: Callable[[Dict[str, Any]], bool] = _default_true,
44
+ ):
45
+ self._approve = approve
46
+ self._should_check = should_check
47
+
48
+ def on_tool_start(
49
+ self,
50
+ serialized: Dict[str, Any],
51
+ input_str: str,
52
+ *,
53
+ run_id: UUID,
54
+ parent_run_id: Optional[UUID] = None,
55
+ **kwargs: Any,
56
+ ) -> Any:
57
+ if self._should_check(serialized) and not self._approve(input_str):
58
+ raise HumanRejectedException(
59
+ f"Inputs {input_str} to tool {serialized} were rejected."
60
+ )
61
+
62
+
63
+ class AsyncHumanApprovalCallbackHandler(AsyncCallbackHandler):
64
+ """Asynchronous callback for manually validating values."""
65
+
66
+ raise_error: bool = True
67
+
68
+ def __init__(
69
+ self,
70
+ approve: Callable[[Any], Awaitable[bool]] = _adefault_approve,
71
+ should_check: Callable[[Dict[str, Any]], bool] = _default_true,
72
+ ):
73
+ self._approve = approve
74
+ self._should_check = should_check
75
+
76
+ async def on_tool_start(
77
+ self,
78
+ serialized: Dict[str, Any],
79
+ input_str: str,
80
+ *,
81
+ run_id: UUID,
82
+ parent_run_id: Optional[UUID] = None,
83
+ **kwargs: Any,
84
+ ) -> Any:
85
+ if self._should_check(serialized) and not await self._approve(input_str):
86
+ raise HumanRejectedException(
87
+ f"Inputs {input_str} to tool {serialized} were rejected."
88
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/infino_callback.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from typing import Any, Dict, List, Optional, cast
3
+
4
+ from langchain_core.agents import AgentAction, AgentFinish
5
+ from langchain_core.callbacks import BaseCallbackHandler
6
+ from langchain_core.messages import BaseMessage
7
+ from langchain_core.outputs import ChatGeneration, LLMResult
8
+ from langchain_core.utils import guard_import
9
+
10
+
11
+ def import_infino() -> Any:
12
+ """Import the infino client."""
13
+ return guard_import("infinopy").InfinoClient()
14
+
15
+
16
+ def import_tiktoken() -> Any:
17
+ """Import tiktoken for counting tokens for OpenAI models."""
18
+ return guard_import("tiktoken")
19
+
20
+
21
+ def get_num_tokens(string: str, openai_model_name: str) -> int:
22
+ """Calculate num tokens for OpenAI with tiktoken package.
23
+
24
+ Official documentation: https://github.com/openai/openai-cookbook/blob/main
25
+ /examples/How_to_count_tokens_with_tiktoken.ipynb
26
+ """
27
+ tiktoken = import_tiktoken()
28
+
29
+ encoding = tiktoken.encoding_for_model(openai_model_name)
30
+ num_tokens = len(encoding.encode(string))
31
+ return num_tokens
32
+
33
+
34
+ class InfinoCallbackHandler(BaseCallbackHandler):
35
+ """Callback Handler that logs to Infino."""
36
+
37
+ def __init__(
38
+ self,
39
+ model_id: Optional[str] = None,
40
+ model_version: Optional[str] = None,
41
+ verbose: bool = False,
42
+ ) -> None:
43
+ # Set Infino client
44
+ self.client = import_infino()
45
+ self.model_id = model_id
46
+ self.model_version = model_version
47
+ self.verbose = verbose
48
+ self.is_chat_openai_model = False
49
+ self.chat_openai_model_name = "gpt-3.5-turbo"
50
+
51
+ def _send_to_infino(
52
+ self,
53
+ key: str,
54
+ value: Any,
55
+ is_ts: bool = True,
56
+ ) -> None:
57
+ """Send the key-value to Infino.
58
+
59
+ Parameters:
60
+ key (str): the key to send to Infino.
61
+ value (Any): the value to send to Infino.
62
+ is_ts (bool): if True, the value is part of a time series, else it
63
+ is sent as a log message.
64
+ """
65
+ payload = {
66
+ "date": int(time.time()),
67
+ key: value,
68
+ "labels": {
69
+ "model_id": self.model_id,
70
+ "model_version": self.model_version,
71
+ },
72
+ }
73
+ if self.verbose:
74
+ print(f"Tracking {key} with Infino: {payload}") # noqa: T201
75
+
76
+ # Append to Infino time series only if is_ts is True, otherwise
77
+ # append to Infino log.
78
+ if is_ts:
79
+ self.client.append_ts(payload)
80
+ else:
81
+ self.client.append_log(payload)
82
+
83
+ def on_llm_start(
84
+ self,
85
+ serialized: Dict[str, Any],
86
+ prompts: List[str],
87
+ **kwargs: Any,
88
+ ) -> None:
89
+ """Log the prompts to Infino, and set start time and error flag."""
90
+ for prompt in prompts:
91
+ self._send_to_infino("prompt", prompt, is_ts=False)
92
+
93
+ # Set the error flag to indicate no error (this will get overridden
94
+ # in on_llm_error if an error occurs).
95
+ self.error = 0
96
+
97
+ # Set the start time (so that we can calculate the request
98
+ # duration in on_llm_end).
99
+ self.start_time = time.time()
100
+
101
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
102
+ """Do nothing when a new token is generated."""
103
+ pass
104
+
105
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
106
+ """Log the latency, error, token usage, and response to Infino."""
107
+ # Calculate and track the request latency.
108
+ self.end_time = time.time()
109
+ duration = self.end_time - self.start_time
110
+ self._send_to_infino("latency", duration)
111
+
112
+ # Track success or error flag.
113
+ self._send_to_infino("error", self.error)
114
+
115
+ # Track prompt response.
116
+ for generations in response.generations:
117
+ for generation in generations:
118
+ self._send_to_infino("prompt_response", generation.text, is_ts=False)
119
+
120
+ # Track token usage (for non-chat models).
121
+ if (response.llm_output is not None) and isinstance(response.llm_output, Dict):
122
+ token_usage = response.llm_output["token_usage"]
123
+ if token_usage is not None:
124
+ prompt_tokens = token_usage["prompt_tokens"]
125
+ total_tokens = token_usage["total_tokens"]
126
+ completion_tokens = token_usage["completion_tokens"]
127
+ self._send_to_infino("prompt_tokens", prompt_tokens)
128
+ self._send_to_infino("total_tokens", total_tokens)
129
+ self._send_to_infino("completion_tokens", completion_tokens)
130
+
131
+ # Track completion token usage (for openai chat models).
132
+ if self.is_chat_openai_model:
133
+ messages = " ".join(
134
+ cast(str, cast(ChatGeneration, generation).message.content)
135
+ for generation in generations
136
+ )
137
+ completion_tokens = get_num_tokens(
138
+ messages, openai_model_name=self.chat_openai_model_name
139
+ )
140
+ self._send_to_infino("completion_tokens", completion_tokens)
141
+
142
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
143
+ """Set the error flag."""
144
+ self.error = 1
145
+
146
+ def on_chain_start(
147
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
148
+ ) -> None:
149
+ """Do nothing when LLM chain starts."""
150
+ pass
151
+
152
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
153
+ """Do nothing when LLM chain ends."""
154
+ pass
155
+
156
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
157
+ """Need to log the error."""
158
+ pass
159
+
160
+ def on_tool_start(
161
+ self,
162
+ serialized: Dict[str, Any],
163
+ input_str: str,
164
+ **kwargs: Any,
165
+ ) -> None:
166
+ """Do nothing when tool starts."""
167
+ pass
168
+
169
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
170
+ """Do nothing when agent takes a specific action."""
171
+ pass
172
+
173
+ def on_tool_end(
174
+ self,
175
+ output: str,
176
+ observation_prefix: Optional[str] = None,
177
+ llm_prefix: Optional[str] = None,
178
+ **kwargs: Any,
179
+ ) -> None:
180
+ """Do nothing when tool ends."""
181
+ pass
182
+
183
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
184
+ """Do nothing when tool outputs an error."""
185
+ pass
186
+
187
+ def on_text(self, text: str, **kwargs: Any) -> None:
188
+ """Do nothing."""
189
+ pass
190
+
191
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
192
+ """Do nothing."""
193
+ pass
194
+
195
+ def on_chat_model_start(
196
+ self,
197
+ serialized: Dict[str, Any],
198
+ messages: List[List[BaseMessage]],
199
+ **kwargs: Any,
200
+ ) -> None:
201
+ """Run when LLM starts running."""
202
+
203
+ # Currently, for chat models, we only support input prompts for ChatOpenAI.
204
+ # Check if this model is a ChatOpenAI model.
205
+ values = serialized.get("id")
206
+ if values:
207
+ for value in values:
208
+ if value == "ChatOpenAI":
209
+ self.is_chat_openai_model = True
210
+ break
211
+
212
+ # Track prompt tokens for ChatOpenAI model.
213
+ if self.is_chat_openai_model:
214
+ invocation_params = kwargs.get("invocation_params")
215
+ if invocation_params:
216
+ model_name = invocation_params.get("model_name")
217
+ if model_name:
218
+ self.chat_openai_model_name = model_name
219
+ prompt_tokens = 0
220
+ for message_list in messages:
221
+ message_string = " ".join(
222
+ cast(str, msg.content) for msg in message_list
223
+ )
224
+ num_tokens = get_num_tokens(
225
+ message_string,
226
+ openai_model_name=self.chat_openai_model_name,
227
+ )
228
+ prompt_tokens += num_tokens
229
+
230
+ self._send_to_infino("prompt_tokens", prompt_tokens)
231
+
232
+ if self.verbose:
233
+ print( # noqa: T201
234
+ f"on_chat_model_start: is_chat_openai_model= \
235
+ {self.is_chat_openai_model}, \
236
+ chat_openai_model_name={self.chat_openai_model_name}"
237
+ )
238
+
239
+ # Send the prompt to infino
240
+ prompt = " ".join(
241
+ cast(str, msg.content) for sublist in messages for msg in sublist
242
+ )
243
+ self._send_to_infino("prompt", prompt, is_ts=False)
244
+
245
+ # Set the error flag to indicate no error (this will get overridden
246
+ # in on_llm_error if an error occurs).
247
+ self.error = 0
248
+
249
+ # Set the start time (so that we can calculate the request
250
+ # duration in on_llm_end).
251
+ self.start_time = time.time()
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/labelstudio_callback.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import warnings
3
+ from datetime import datetime
4
+ from enum import Enum
5
+ from typing import Any, Dict, List, Optional, Tuple, Union
6
+ from uuid import UUID
7
+
8
+ from langchain_core.agents import AgentAction, AgentFinish
9
+ from langchain_core.callbacks import BaseCallbackHandler
10
+ from langchain_core.messages import BaseMessage, ChatMessage
11
+ from langchain_core.outputs import Generation, LLMResult
12
+
13
+
14
+ class LabelStudioMode(Enum):
15
+ """Label Studio mode enumerator."""
16
+
17
+ PROMPT = "prompt"
18
+ CHAT = "chat"
19
+
20
+
21
+ def get_default_label_configs(
22
+ mode: Union[str, LabelStudioMode],
23
+ ) -> Tuple[str, LabelStudioMode]:
24
+ """Get default Label Studio configs for the given mode.
25
+
26
+ Parameters:
27
+ mode: Label Studio mode ("prompt" or "chat")
28
+
29
+ Returns: Tuple of Label Studio config and mode
30
+ """
31
+ _default_label_configs = {
32
+ LabelStudioMode.PROMPT.value: """
33
+ <View>
34
+ <Style>
35
+ .prompt-box {
36
+ background-color: white;
37
+ border-radius: 10px;
38
+ box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
39
+ padding: 20px;
40
+ }
41
+ </Style>
42
+ <View className="root">
43
+ <View className="prompt-box">
44
+ <Text name="prompt" value="$prompt"/>
45
+ </View>
46
+ <TextArea name="response" toName="prompt"
47
+ maxSubmissions="1" editable="true"
48
+ required="true"/>
49
+ </View>
50
+ <Header value="Rate the response:"/>
51
+ <Rating name="rating" toName="prompt"/>
52
+ </View>""",
53
+ LabelStudioMode.CHAT.value: """
54
+ <View>
55
+ <View className="root">
56
+ <Paragraphs name="dialogue"
57
+ value="$prompt"
58
+ layout="dialogue"
59
+ textKey="content"
60
+ nameKey="role"
61
+ granularity="sentence"/>
62
+ <Header value="Final response:"/>
63
+ <TextArea name="response" toName="dialogue"
64
+ maxSubmissions="1" editable="true"
65
+ required="true"/>
66
+ </View>
67
+ <Header value="Rate the response:"/>
68
+ <Rating name="rating" toName="dialogue"/>
69
+ </View>""",
70
+ }
71
+
72
+ if isinstance(mode, str):
73
+ mode = LabelStudioMode(mode)
74
+
75
+ return _default_label_configs[mode.value], mode
76
+
77
+
78
+ class LabelStudioCallbackHandler(BaseCallbackHandler):
79
+ """Label Studio callback handler.
80
+ Provides the ability to send predictions to Label Studio
81
+ for human evaluation, feedback and annotation.
82
+
83
+ Parameters:
84
+ api_key: Label Studio API key
85
+ url: Label Studio URL
86
+ project_id: Label Studio project ID
87
+ project_name: Label Studio project name
88
+ project_config: Label Studio project config (XML)
89
+ mode: Label Studio mode ("prompt" or "chat")
90
+
91
+ Examples:
92
+ >>> from langchain_community.llms import OpenAI
93
+ >>> from langchain_community.callbacks import LabelStudioCallbackHandler
94
+ >>> handler = LabelStudioCallbackHandler(
95
+ ... api_key='<your_key_here>',
96
+ ... url='http://localhost:8080',
97
+ ... project_name='LangChain-%Y-%m-%d',
98
+ ... mode='prompt'
99
+ ... )
100
+ >>> llm = OpenAI(callbacks=[handler])
101
+ >>> llm.invoke('Tell me a story about a dog.')
102
+ """
103
+
104
+ DEFAULT_PROJECT_NAME: str = "LangChain-%Y-%m-%d"
105
+
106
+ def __init__(
107
+ self,
108
+ api_key: Optional[str] = None,
109
+ url: Optional[str] = None,
110
+ project_id: Optional[int] = None,
111
+ project_name: str = DEFAULT_PROJECT_NAME,
112
+ project_config: Optional[str] = None,
113
+ mode: Union[str, LabelStudioMode] = LabelStudioMode.PROMPT,
114
+ ):
115
+ super().__init__()
116
+
117
+ # Import LabelStudio SDK
118
+ try:
119
+ import label_studio_sdk as ls
120
+ except ImportError:
121
+ raise ImportError(
122
+ f"You're using {self.__class__.__name__} in your code,"
123
+ f" but you don't have the LabelStudio SDK "
124
+ f"Python package installed or upgraded to the latest version. "
125
+ f"Please run `pip install -U label-studio-sdk`"
126
+ f" before using this callback."
127
+ )
128
+
129
+ # Check if Label Studio API key is provided
130
+ if not api_key:
131
+ if os.getenv("LABEL_STUDIO_API_KEY"):
132
+ api_key = str(os.getenv("LABEL_STUDIO_API_KEY"))
133
+ else:
134
+ raise ValueError(
135
+ f"You're using {self.__class__.__name__} in your code,"
136
+ f" Label Studio API key is not provided. "
137
+ f"Please provide Label Studio API key: "
138
+ f"go to the Label Studio instance, navigate to "
139
+ f"Account & Settings -> Access Token and copy the key. "
140
+ f"Use the key as a parameter for the callback: "
141
+ f"{self.__class__.__name__}"
142
+ f"(label_studio_api_key='<your_key_here>', ...) or "
143
+ f"set the environment variable LABEL_STUDIO_API_KEY=<your_key_here>"
144
+ )
145
+ self.api_key = api_key
146
+
147
+ if not url:
148
+ if os.getenv("LABEL_STUDIO_URL"):
149
+ url = os.getenv("LABEL_STUDIO_URL")
150
+ else:
151
+ warnings.warn(
152
+ f"Label Studio URL is not provided, "
153
+ f"using default URL: {ls.LABEL_STUDIO_DEFAULT_URL}"
154
+ f"If you want to provide your own URL, use the parameter: "
155
+ f"{self.__class__.__name__}"
156
+ f"(label_studio_url='<your_url_here>', ...) "
157
+ f"or set the environment variable LABEL_STUDIO_URL=<your_url_here>"
158
+ )
159
+ url = ls.LABEL_STUDIO_DEFAULT_URL
160
+ self.url = url
161
+
162
+ # Maps run_id to prompts
163
+ self.payload: Dict[str, Dict] = {}
164
+
165
+ self.ls_client = ls.Client(url=self.url, api_key=self.api_key)
166
+ self.project_name = project_name
167
+ if project_config:
168
+ self.project_config = project_config
169
+ self.mode = None
170
+ else:
171
+ self.project_config, self.mode = get_default_label_configs(mode)
172
+
173
+ self.project_id = project_id or os.getenv("LABEL_STUDIO_PROJECT_ID")
174
+ if self.project_id is not None:
175
+ self.ls_project = self.ls_client.get_project(int(self.project_id))
176
+ else:
177
+ project_title = datetime.today().strftime(self.project_name)
178
+ existing_projects = self.ls_client.get_projects(title=project_title)
179
+ if existing_projects:
180
+ self.ls_project = existing_projects[0]
181
+ self.project_id = self.ls_project.id
182
+ else:
183
+ self.ls_project = self.ls_client.create_project(
184
+ title=project_title, label_config=self.project_config
185
+ )
186
+ self.project_id = self.ls_project.id
187
+ self.parsed_label_config = self.ls_project.parsed_label_config
188
+
189
+ # Find the first TextArea tag
190
+ # "from_name", "to_name", "value" will be used to create predictions
191
+ self.from_name, self.to_name, self.value, self.input_type = (
192
+ None,
193
+ None,
194
+ None,
195
+ None,
196
+ )
197
+ for tag_name, tag_info in self.parsed_label_config.items():
198
+ if tag_info["type"] == "TextArea":
199
+ self.from_name = tag_name
200
+ self.to_name = tag_info["to_name"][0]
201
+ self.value = tag_info["inputs"][0]["value"]
202
+ self.input_type = tag_info["inputs"][0]["type"]
203
+ break
204
+ if not self.from_name:
205
+ error_message = (
206
+ f'Label Studio project "{self.project_name}" '
207
+ f"does not have a TextArea tag. "
208
+ f"Please add a TextArea tag to the project."
209
+ )
210
+ if self.mode == LabelStudioMode.PROMPT:
211
+ error_message += (
212
+ "\nHINT: go to project Settings -> "
213
+ "Labeling Interface -> Browse Templates"
214
+ ' and select "Generative AI -> '
215
+ 'Supervised Language Model Fine-tuning" template.'
216
+ )
217
+ else:
218
+ error_message += (
219
+ "\nHINT: go to project Settings -> "
220
+ "Labeling Interface -> Browse Templates"
221
+ " and check available templates under "
222
+ '"Generative AI" section.'
223
+ )
224
+ raise ValueError(error_message)
225
+
226
+ def add_prompts_generations(
227
+ self, run_id: str, generations: List[List[Generation]]
228
+ ) -> None:
229
+ # Create tasks in Label Studio
230
+ tasks = []
231
+ prompts = self.payload[run_id]["prompts"]
232
+ model_version = (
233
+ self.payload[run_id]["kwargs"]
234
+ .get("invocation_params", {})
235
+ .get("model_name")
236
+ )
237
+ for prompt, generation in zip(prompts, generations):
238
+ tasks.append(
239
+ {
240
+ "data": {
241
+ self.value: prompt,
242
+ "run_id": run_id,
243
+ },
244
+ "predictions": [
245
+ {
246
+ "result": [
247
+ {
248
+ "from_name": self.from_name,
249
+ "to_name": self.to_name,
250
+ "type": "textarea",
251
+ "value": {"text": [g.text for g in generation]},
252
+ }
253
+ ],
254
+ "model_version": model_version,
255
+ }
256
+ ],
257
+ }
258
+ )
259
+ self.ls_project.import_tasks(tasks)
260
+
261
+ def on_llm_start(
262
+ self,
263
+ serialized: Dict[str, Any],
264
+ prompts: List[str],
265
+ **kwargs: Any,
266
+ ) -> None:
267
+ """Save the prompts in memory when an LLM starts."""
268
+ if self.input_type != "Text":
269
+ raise ValueError(
270
+ f'\nLabel Studio project "{self.project_name}" '
271
+ f"has an input type <{self.input_type}>. "
272
+ f'To make it work with the mode="chat", '
273
+ f"the input type should be <Text>.\n"
274
+ f"Read more here https://labelstud.io/tags/text"
275
+ )
276
+ run_id = str(kwargs["run_id"])
277
+ self.payload[run_id] = {"prompts": prompts, "kwargs": kwargs}
278
+
279
+ def _get_message_role(self, message: BaseMessage) -> str:
280
+ """Get the role of the message."""
281
+ if isinstance(message, ChatMessage):
282
+ return message.role
283
+ else:
284
+ return message.__class__.__name__
285
+
286
+ def on_chat_model_start(
287
+ self,
288
+ serialized: Dict[str, Any],
289
+ messages: List[List[BaseMessage]],
290
+ *,
291
+ run_id: UUID,
292
+ parent_run_id: Optional[UUID] = None,
293
+ tags: Optional[List[str]] = None,
294
+ metadata: Optional[Dict[str, Any]] = None,
295
+ **kwargs: Any,
296
+ ) -> Any:
297
+ """Save the prompts in memory when an LLM starts."""
298
+ if self.input_type != "Paragraphs":
299
+ raise ValueError(
300
+ f'\nLabel Studio project "{self.project_name}" '
301
+ f"has an input type <{self.input_type}>. "
302
+ f'To make it work with the mode="chat", '
303
+ f"the input type should be <Paragraphs>.\n"
304
+ f"Read more here https://labelstud.io/tags/paragraphs"
305
+ )
306
+
307
+ prompts = []
308
+ for message_list in messages:
309
+ dialog = []
310
+ for message in message_list:
311
+ dialog.append(
312
+ {
313
+ "role": self._get_message_role(message),
314
+ "content": message.content,
315
+ }
316
+ )
317
+ prompts.append(dialog)
318
+ self.payload[str(run_id)] = {
319
+ "prompts": prompts,
320
+ "tags": tags,
321
+ "metadata": metadata,
322
+ "run_id": run_id,
323
+ "parent_run_id": parent_run_id,
324
+ "kwargs": kwargs,
325
+ }
326
+
327
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
328
+ """Do nothing when a new token is generated."""
329
+ pass
330
+
331
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
332
+ """Create a new Label Studio task for each prompt and generation."""
333
+ run_id = str(kwargs["run_id"])
334
+
335
+ # Submit results to Label Studio
336
+ self.add_prompts_generations(run_id, response.generations)
337
+
338
+ # Pop current run from `self.runs`
339
+ self.payload.pop(run_id)
340
+
341
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
342
+ """Do nothing when LLM outputs an error."""
343
+ pass
344
+
345
+ def on_chain_start(
346
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
347
+ ) -> None:
348
+ pass
349
+
350
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
351
+ pass
352
+
353
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
354
+ """Do nothing when LLM chain outputs an error."""
355
+ pass
356
+
357
+ def on_tool_start(
358
+ self,
359
+ serialized: Dict[str, Any],
360
+ input_str: str,
361
+ **kwargs: Any,
362
+ ) -> None:
363
+ """Do nothing when tool starts."""
364
+ pass
365
+
366
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
367
+ """Do nothing when agent takes a specific action."""
368
+ pass
369
+
370
+ def on_tool_end(
371
+ self,
372
+ output: str,
373
+ observation_prefix: Optional[str] = None,
374
+ llm_prefix: Optional[str] = None,
375
+ **kwargs: Any,
376
+ ) -> None:
377
+ """Do nothing when tool ends."""
378
+ pass
379
+
380
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
381
+ """Do nothing when tool outputs an error."""
382
+ pass
383
+
384
+ def on_text(self, text: str, **kwargs: Any) -> None:
385
+ """Do nothing"""
386
+ pass
387
+
388
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
389
+ """Do nothing"""
390
+ pass
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/llmonitor_callback.py ADDED
@@ -0,0 +1,681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ import logging
3
+ import os
4
+ import traceback
5
+ import warnings
6
+ from contextvars import ContextVar
7
+ from typing import Any, Dict, List, Union, cast
8
+ from uuid import UUID
9
+
10
+ import requests
11
+ from langchain_core.agents import AgentAction, AgentFinish
12
+ from langchain_core.callbacks import BaseCallbackHandler
13
+ from langchain_core.messages import BaseMessage
14
+ from langchain_core.outputs import LLMResult
15
+ from packaging.version import parse
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ DEFAULT_API_URL = "https://app.llmonitor.com"
20
+
21
+ user_ctx = ContextVar[Union[str, None]]("user_ctx", default=None)
22
+ user_props_ctx = ContextVar[Union[str, None]]("user_props_ctx", default=None)
23
+
24
+ PARAMS_TO_CAPTURE = [
25
+ "temperature",
26
+ "top_p",
27
+ "top_k",
28
+ "stop",
29
+ "presence_penalty",
30
+ "frequence_penalty",
31
+ "seed",
32
+ "function_call",
33
+ "functions",
34
+ "tools",
35
+ "tool_choice",
36
+ "response_format",
37
+ "max_tokens",
38
+ "logit_bias",
39
+ ]
40
+
41
+
42
+ class UserContextManager:
43
+ """Context manager for LLMonitor user context."""
44
+
45
+ def __init__(self, user_id: str, user_props: Any = None) -> None:
46
+ user_ctx.set(user_id)
47
+ user_props_ctx.set(user_props)
48
+
49
+ def __enter__(self) -> Any:
50
+ pass
51
+
52
+ def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> Any:
53
+ user_ctx.set(None)
54
+ user_props_ctx.set(None)
55
+
56
+
57
+ def identify(user_id: str, user_props: Any = None) -> UserContextManager:
58
+ """Builds an LLMonitor UserContextManager
59
+
60
+ Parameters:
61
+ - `user_id`: The user id.
62
+ - `user_props`: The user properties.
63
+
64
+ Returns:
65
+ A context manager that sets the user context.
66
+ """
67
+ return UserContextManager(user_id, user_props)
68
+
69
+
70
+ def _serialize(obj: Any) -> Union[Dict[str, Any], List[Any], Any]:
71
+ if hasattr(obj, "to_json"):
72
+ return obj.to_json()
73
+
74
+ if isinstance(obj, dict):
75
+ return {key: _serialize(value) for key, value in obj.items()}
76
+
77
+ if isinstance(obj, list):
78
+ return [_serialize(element) for element in obj]
79
+
80
+ return obj
81
+
82
+
83
+ def _parse_input(raw_input: Any) -> Any:
84
+ if not raw_input:
85
+ return None
86
+
87
+ # if it's an array of 1, just parse the first element
88
+ if isinstance(raw_input, list) and len(raw_input) == 1:
89
+ return _parse_input(raw_input[0])
90
+
91
+ if not isinstance(raw_input, dict):
92
+ return _serialize(raw_input)
93
+
94
+ input_value = raw_input.get("input")
95
+ inputs_value = raw_input.get("inputs")
96
+ question_value = raw_input.get("question")
97
+ query_value = raw_input.get("query")
98
+
99
+ if input_value:
100
+ return input_value
101
+ if inputs_value:
102
+ return inputs_value
103
+ if question_value:
104
+ return question_value
105
+ if query_value:
106
+ return query_value
107
+
108
+ return _serialize(raw_input)
109
+
110
+
111
+ def _parse_output(raw_output: dict) -> Any:
112
+ if not raw_output:
113
+ return None
114
+
115
+ if not isinstance(raw_output, dict):
116
+ return _serialize(raw_output)
117
+
118
+ text_value = raw_output.get("text")
119
+ output_value = raw_output.get("output")
120
+ output_text_value = raw_output.get("output_text")
121
+ answer_value = raw_output.get("answer")
122
+ result_value = raw_output.get("result")
123
+
124
+ if text_value:
125
+ return text_value
126
+ if answer_value:
127
+ return answer_value
128
+ if output_value:
129
+ return output_value
130
+ if output_text_value:
131
+ return output_text_value
132
+ if result_value:
133
+ return result_value
134
+
135
+ return _serialize(raw_output)
136
+
137
+
138
+ def _parse_lc_role(
139
+ role: str,
140
+ ) -> str:
141
+ if role == "human":
142
+ return "user"
143
+ else:
144
+ return role
145
+
146
+
147
+ def _get_user_id(metadata: Any) -> Any:
148
+ if user_ctx.get() is not None:
149
+ return user_ctx.get()
150
+
151
+ metadata = metadata or {}
152
+ user_id = metadata.get("user_id")
153
+ if user_id is None:
154
+ user_id = metadata.get("userId") # legacy, to delete in the future
155
+ return user_id
156
+
157
+
158
+ def _get_user_props(metadata: Any) -> Any:
159
+ if user_props_ctx.get() is not None:
160
+ return user_props_ctx.get()
161
+
162
+ metadata = metadata or {}
163
+ return metadata.get("user_props", None)
164
+
165
+
166
+ def _parse_lc_message(message: BaseMessage) -> Dict[str, Any]:
167
+ keys = ["function_call", "tool_calls", "tool_call_id", "name"]
168
+ parsed = {"text": message.content, "role": _parse_lc_role(message.type)}
169
+ parsed.update(
170
+ {
171
+ key: cast(Any, message.additional_kwargs.get(key))
172
+ for key in keys
173
+ if message.additional_kwargs.get(key) is not None
174
+ }
175
+ )
176
+ return parsed
177
+
178
+
179
+ def _parse_lc_messages(messages: Union[List[BaseMessage], Any]) -> List[Dict[str, Any]]:
180
+ return [_parse_lc_message(message) for message in messages]
181
+
182
+
183
+ class LLMonitorCallbackHandler(BaseCallbackHandler):
184
+ """Callback Handler for LLMonitor`.
185
+
186
+ #### Parameters:
187
+ - `app_id`: The app id of the app you want to report to. Defaults to
188
+ `None`, which means that `LLMONITOR_APP_ID` will be used.
189
+ - `api_url`: The url of the LLMonitor API. Defaults to `None`,
190
+ which means that either `LLMONITOR_API_URL` environment variable
191
+ or `https://app.llmonitor.com` will be used.
192
+
193
+ #### Raises:
194
+ - `ValueError`: if `app_id` is not provided either as an
195
+ argument or as an environment variable.
196
+ - `ConnectionError`: if the connection to the API fails.
197
+
198
+
199
+ #### Example:
200
+ ```python
201
+ from langchain_community.llms import OpenAI
202
+ from langchain_community.callbacks import LLMonitorCallbackHandler
203
+
204
+ llmonitor_callback = LLMonitorCallbackHandler()
205
+ llm = OpenAI(callbacks=[llmonitor_callback],
206
+ metadata={"userId": "user-123"})
207
+ llm.invoke("Hello, how are you?")
208
+ ```
209
+ """
210
+
211
+ __api_url: str
212
+ __app_id: str
213
+ __verbose: bool
214
+ __llmonitor_version: str
215
+ __has_valid_config: bool
216
+
217
+ def __init__(
218
+ self,
219
+ app_id: Union[str, None] = None,
220
+ api_url: Union[str, None] = None,
221
+ verbose: bool = False,
222
+ ) -> None:
223
+ super().__init__()
224
+
225
+ self.__has_valid_config = True
226
+
227
+ try:
228
+ import llmonitor
229
+
230
+ self.__llmonitor_version = importlib.metadata.version("llmonitor")
231
+ self.__track_event = llmonitor.track_event
232
+
233
+ except ImportError:
234
+ logger.warning(
235
+ """[LLMonitor] To use the LLMonitor callback handler you need to
236
+ have the `llmonitor` Python package installed. Please install it
237
+ with `pip install llmonitor`"""
238
+ )
239
+ self.__has_valid_config = False
240
+ return
241
+
242
+ if parse(self.__llmonitor_version) < parse("0.0.32"):
243
+ logger.warning(
244
+ f"""[LLMonitor] The installed `llmonitor` version is
245
+ {self.__llmonitor_version}
246
+ but `LLMonitorCallbackHandler` requires at least version 0.0.32
247
+ upgrade `llmonitor` with `pip install --upgrade llmonitor`"""
248
+ )
249
+ self.__has_valid_config = False
250
+
251
+ self.__has_valid_config = True
252
+
253
+ self.__api_url = api_url or os.getenv("LLMONITOR_API_URL") or DEFAULT_API_URL
254
+ self.__verbose = verbose or bool(os.getenv("LLMONITOR_VERBOSE"))
255
+
256
+ _app_id = app_id or os.getenv("LLMONITOR_APP_ID")
257
+ if _app_id is None:
258
+ logger.warning(
259
+ """[LLMonitor] app_id must be provided either as an argument or
260
+ as an environment variable"""
261
+ )
262
+ self.__has_valid_config = False
263
+ else:
264
+ self.__app_id = _app_id
265
+
266
+ if self.__has_valid_config is False:
267
+ return None
268
+
269
+ try:
270
+ res = requests.get(f"{self.__api_url}/api/app/{self.__app_id}")
271
+ if not res.ok:
272
+ raise ConnectionError()
273
+ except Exception:
274
+ logger.warning(
275
+ f"""[LLMonitor] Could not connect to the LLMonitor API at
276
+ {self.__api_url}"""
277
+ )
278
+
279
+ def on_llm_start(
280
+ self,
281
+ serialized: Dict[str, Any],
282
+ prompts: List[str],
283
+ *,
284
+ run_id: UUID,
285
+ parent_run_id: Union[UUID, None] = None,
286
+ tags: Union[List[str], None] = None,
287
+ metadata: Union[Dict[str, Any], None] = None,
288
+ **kwargs: Any,
289
+ ) -> None:
290
+ if self.__has_valid_config is False:
291
+ return
292
+ try:
293
+ user_id = _get_user_id(metadata)
294
+ user_props = _get_user_props(metadata)
295
+
296
+ params = kwargs.get("invocation_params", {})
297
+ params.update(
298
+ serialized.get("kwargs", {})
299
+ ) # Sometimes, for example with ChatAnthropic, `invocation_params` is empty
300
+
301
+ name = (
302
+ params.get("model")
303
+ or params.get("model_name")
304
+ or params.get("model_id")
305
+ )
306
+
307
+ if not name and "anthropic" in params.get("_type"):
308
+ name = "claude-2"
309
+
310
+ extra = {
311
+ param: params.get(param)
312
+ for param in PARAMS_TO_CAPTURE
313
+ if params.get(param) is not None
314
+ }
315
+
316
+ input = _parse_input(prompts)
317
+
318
+ self.__track_event(
319
+ "llm",
320
+ "start",
321
+ user_id=user_id,
322
+ run_id=str(run_id),
323
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
324
+ name=name,
325
+ input=input,
326
+ tags=tags,
327
+ extra=extra,
328
+ metadata=metadata,
329
+ user_props=user_props,
330
+ app_id=self.__app_id,
331
+ )
332
+ except Exception as e:
333
+ warnings.warn(f"[LLMonitor] An error occurred in on_llm_start: {e}")
334
+
335
+ def on_chat_model_start(
336
+ self,
337
+ serialized: Dict[str, Any],
338
+ messages: List[List[BaseMessage]],
339
+ *,
340
+ run_id: UUID,
341
+ parent_run_id: Union[UUID, None] = None,
342
+ tags: Union[List[str], None] = None,
343
+ metadata: Union[Dict[str, Any], None] = None,
344
+ **kwargs: Any,
345
+ ) -> Any:
346
+ if self.__has_valid_config is False:
347
+ return
348
+
349
+ try:
350
+ user_id = _get_user_id(metadata)
351
+ user_props = _get_user_props(metadata)
352
+
353
+ params = kwargs.get("invocation_params", {})
354
+ params.update(
355
+ serialized.get("kwargs", {})
356
+ ) # Sometimes, for example with ChatAnthropic, `invocation_params` is empty
357
+
358
+ name = (
359
+ params.get("model")
360
+ or params.get("model_name")
361
+ or params.get("model_id")
362
+ )
363
+
364
+ if not name and "anthropic" in params.get("_type"):
365
+ name = "claude-2"
366
+
367
+ extra = {
368
+ param: params.get(param)
369
+ for param in PARAMS_TO_CAPTURE
370
+ if params.get(param) is not None
371
+ }
372
+
373
+ input = _parse_lc_messages(messages[0])
374
+
375
+ self.__track_event(
376
+ "llm",
377
+ "start",
378
+ user_id=user_id,
379
+ run_id=str(run_id),
380
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
381
+ name=name,
382
+ input=input,
383
+ tags=tags,
384
+ extra=extra,
385
+ metadata=metadata,
386
+ user_props=user_props,
387
+ app_id=self.__app_id,
388
+ )
389
+ except Exception as e:
390
+ logger.error(f"[LLMonitor] An error occurred in on_chat_model_start: {e}")
391
+
392
+ def on_llm_end(
393
+ self,
394
+ response: LLMResult,
395
+ *,
396
+ run_id: UUID,
397
+ parent_run_id: Union[UUID, None] = None,
398
+ **kwargs: Any,
399
+ ) -> None:
400
+ if self.__has_valid_config is False:
401
+ return
402
+
403
+ try:
404
+ token_usage = (response.llm_output or {}).get("token_usage", {})
405
+
406
+ parsed_output: Any = [
407
+ _parse_lc_message(generation.message)
408
+ if hasattr(generation, "message")
409
+ else generation.text
410
+ for generation in response.generations[0]
411
+ ]
412
+
413
+ # if it's an array of 1, just parse the first element
414
+ if len(parsed_output) == 1:
415
+ parsed_output = parsed_output[0]
416
+
417
+ self.__track_event(
418
+ "llm",
419
+ "end",
420
+ run_id=str(run_id),
421
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
422
+ output=parsed_output,
423
+ token_usage={
424
+ "prompt": token_usage.get("prompt_tokens"),
425
+ "completion": token_usage.get("completion_tokens"),
426
+ },
427
+ app_id=self.__app_id,
428
+ )
429
+ except Exception as e:
430
+ logger.error(f"[LLMonitor] An error occurred in on_llm_end: {e}")
431
+
432
+ def on_tool_start(
433
+ self,
434
+ serialized: Dict[str, Any],
435
+ input_str: str,
436
+ *,
437
+ run_id: UUID,
438
+ parent_run_id: Union[UUID, None] = None,
439
+ tags: Union[List[str], None] = None,
440
+ metadata: Union[Dict[str, Any], None] = None,
441
+ **kwargs: Any,
442
+ ) -> None:
443
+ if self.__has_valid_config is False:
444
+ return
445
+ try:
446
+ user_id = _get_user_id(metadata)
447
+ user_props = _get_user_props(metadata)
448
+ name = serialized.get("name")
449
+
450
+ self.__track_event(
451
+ "tool",
452
+ "start",
453
+ user_id=user_id,
454
+ run_id=str(run_id),
455
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
456
+ name=name,
457
+ input=input_str,
458
+ tags=tags,
459
+ metadata=metadata,
460
+ user_props=user_props,
461
+ app_id=self.__app_id,
462
+ )
463
+ except Exception as e:
464
+ logger.error(f"[LLMonitor] An error occurred in on_tool_start: {e}")
465
+
466
+ def on_tool_end(
467
+ self,
468
+ output: Any,
469
+ *,
470
+ run_id: UUID,
471
+ parent_run_id: Union[UUID, None] = None,
472
+ tags: Union[List[str], None] = None,
473
+ **kwargs: Any,
474
+ ) -> None:
475
+ output = str(output)
476
+ if self.__has_valid_config is False:
477
+ return
478
+ try:
479
+ self.__track_event(
480
+ "tool",
481
+ "end",
482
+ run_id=str(run_id),
483
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
484
+ output=output,
485
+ app_id=self.__app_id,
486
+ )
487
+ except Exception as e:
488
+ logger.error(f"[LLMonitor] An error occurred in on_tool_end: {e}")
489
+
490
+ def on_chain_start(
491
+ self,
492
+ serialized: Dict[str, Any],
493
+ inputs: Dict[str, Any],
494
+ *,
495
+ run_id: UUID,
496
+ parent_run_id: Union[UUID, None] = None,
497
+ tags: Union[List[str], None] = None,
498
+ metadata: Union[Dict[str, Any], None] = None,
499
+ **kwargs: Any,
500
+ ) -> Any:
501
+ if self.__has_valid_config is False:
502
+ return
503
+ try:
504
+ name = serialized.get("id", [None, None, None, None])[3]
505
+ type = "chain"
506
+ metadata = metadata or {}
507
+
508
+ agentName = metadata.get("agent_name")
509
+ if agentName is None:
510
+ agentName = metadata.get("agentName")
511
+
512
+ if name == "AgentExecutor" or name == "PlanAndExecute":
513
+ type = "agent"
514
+ if agentName is not None:
515
+ type = "agent"
516
+ name = agentName
517
+ if parent_run_id is not None:
518
+ type = "chain"
519
+
520
+ user_id = _get_user_id(metadata)
521
+ user_props = _get_user_props(metadata)
522
+ input = _parse_input(inputs)
523
+
524
+ self.__track_event(
525
+ type,
526
+ "start",
527
+ user_id=user_id,
528
+ run_id=str(run_id),
529
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
530
+ name=name,
531
+ input=input,
532
+ tags=tags,
533
+ metadata=metadata,
534
+ user_props=user_props,
535
+ app_id=self.__app_id,
536
+ )
537
+ except Exception as e:
538
+ logger.error(f"[LLMonitor] An error occurred in on_chain_start: {e}")
539
+
540
+ def on_chain_end(
541
+ self,
542
+ outputs: Dict[str, Any],
543
+ *,
544
+ run_id: UUID,
545
+ parent_run_id: Union[UUID, None] = None,
546
+ **kwargs: Any,
547
+ ) -> Any:
548
+ if self.__has_valid_config is False:
549
+ return
550
+ try:
551
+ output = _parse_output(outputs)
552
+
553
+ self.__track_event(
554
+ "chain",
555
+ "end",
556
+ run_id=str(run_id),
557
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
558
+ output=output,
559
+ app_id=self.__app_id,
560
+ )
561
+ except Exception as e:
562
+ logger.error(f"[LLMonitor] An error occurred in on_chain_end: {e}")
563
+
564
+ def on_agent_action(
565
+ self,
566
+ action: AgentAction,
567
+ *,
568
+ run_id: UUID,
569
+ parent_run_id: Union[UUID, None] = None,
570
+ **kwargs: Any,
571
+ ) -> Any:
572
+ if self.__has_valid_config is False:
573
+ return
574
+ try:
575
+ name = action.tool
576
+ input = _parse_input(action.tool_input)
577
+
578
+ self.__track_event(
579
+ "tool",
580
+ "start",
581
+ run_id=str(run_id),
582
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
583
+ name=name,
584
+ input=input,
585
+ app_id=self.__app_id,
586
+ )
587
+ except Exception as e:
588
+ logger.error(f"[LLMonitor] An error occurred in on_agent_action: {e}")
589
+
590
+ def on_agent_finish(
591
+ self,
592
+ finish: AgentFinish,
593
+ *,
594
+ run_id: UUID,
595
+ parent_run_id: Union[UUID, None] = None,
596
+ **kwargs: Any,
597
+ ) -> Any:
598
+ if self.__has_valid_config is False:
599
+ return
600
+ try:
601
+ output = _parse_output(finish.return_values)
602
+
603
+ self.__track_event(
604
+ "agent",
605
+ "end",
606
+ run_id=str(run_id),
607
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
608
+ output=output,
609
+ app_id=self.__app_id,
610
+ )
611
+ except Exception as e:
612
+ logger.error(f"[LLMonitor] An error occurred in on_agent_finish: {e}")
613
+
614
+ def on_chain_error(
615
+ self,
616
+ error: BaseException,
617
+ *,
618
+ run_id: UUID,
619
+ parent_run_id: Union[UUID, None] = None,
620
+ **kwargs: Any,
621
+ ) -> Any:
622
+ if self.__has_valid_config is False:
623
+ return
624
+ try:
625
+ self.__track_event(
626
+ "chain",
627
+ "error",
628
+ run_id=str(run_id),
629
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
630
+ error={"message": str(error), "stack": traceback.format_exc()},
631
+ app_id=self.__app_id,
632
+ )
633
+ except Exception as e:
634
+ logger.error(f"[LLMonitor] An error occurred in on_chain_error: {e}")
635
+
636
+ def on_tool_error(
637
+ self,
638
+ error: BaseException,
639
+ *,
640
+ run_id: UUID,
641
+ parent_run_id: Union[UUID, None] = None,
642
+ **kwargs: Any,
643
+ ) -> Any:
644
+ if self.__has_valid_config is False:
645
+ return
646
+ try:
647
+ self.__track_event(
648
+ "tool",
649
+ "error",
650
+ run_id=str(run_id),
651
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
652
+ error={"message": str(error), "stack": traceback.format_exc()},
653
+ app_id=self.__app_id,
654
+ )
655
+ except Exception as e:
656
+ logger.error(f"[LLMonitor] An error occurred in on_tool_error: {e}")
657
+
658
+ def on_llm_error(
659
+ self,
660
+ error: BaseException,
661
+ *,
662
+ run_id: UUID,
663
+ parent_run_id: Union[UUID, None] = None,
664
+ **kwargs: Any,
665
+ ) -> Any:
666
+ if self.__has_valid_config is False:
667
+ return
668
+ try:
669
+ self.__track_event(
670
+ "llm",
671
+ "error",
672
+ run_id=str(run_id),
673
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
674
+ error={"message": str(error), "stack": traceback.format_exc()},
675
+ app_id=self.__app_id,
676
+ )
677
+ except Exception as e:
678
+ logger.error(f"[LLMonitor] An error occurred in on_llm_error: {e}")
679
+
680
+
681
+ __all__ = ["LLMonitorCallbackHandler", "identify"]
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/manager.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from contextlib import contextmanager
5
+ from contextvars import ContextVar
6
+ from typing import (
7
+ Generator,
8
+ Optional,
9
+ )
10
+
11
+ from langchain_core.tracers.context import register_configure_hook
12
+
13
+ from langchain_community.callbacks.bedrock_anthropic_callback import (
14
+ BedrockAnthropicTokenUsageCallbackHandler,
15
+ )
16
+ from langchain_community.callbacks.openai_info import OpenAICallbackHandler
17
+ from langchain_community.callbacks.tracers.comet import CometTracer
18
+ from langchain_community.callbacks.tracers.wandb import WandbTracer
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ openai_callback_var: ContextVar[Optional[OpenAICallbackHandler]] = ContextVar(
23
+ "openai_callback", default=None
24
+ )
25
+ bedrock_anthropic_callback_var: (ContextVar)[
26
+ Optional[BedrockAnthropicTokenUsageCallbackHandler]
27
+ ] = ContextVar("bedrock_anthropic_callback", default=None)
28
+ wandb_tracing_callback_var: ContextVar[Optional[WandbTracer]] = ContextVar(
29
+ "tracing_wandb_callback", default=None
30
+ )
31
+ comet_tracing_callback_var: ContextVar[Optional[CometTracer]] = ContextVar(
32
+ "tracing_comet_callback", default=None
33
+ )
34
+
35
+ register_configure_hook(openai_callback_var, True)
36
+ register_configure_hook(bedrock_anthropic_callback_var, True)
37
+ register_configure_hook(
38
+ wandb_tracing_callback_var, True, WandbTracer, "LANGCHAIN_WANDB_TRACING"
39
+ )
40
+ register_configure_hook(
41
+ comet_tracing_callback_var, True, CometTracer, "LANGCHAIN_COMET_TRACING"
42
+ )
43
+
44
+
45
+ @contextmanager
46
+ def get_openai_callback() -> Generator[OpenAICallbackHandler, None, None]:
47
+ """Get the OpenAI callback handler in a context manager.
48
+ which conveniently exposes token and cost information.
49
+
50
+ Returns:
51
+ OpenAICallbackHandler: The OpenAI callback handler.
52
+
53
+ Example:
54
+ >>> with get_openai_callback() as cb:
55
+ ... # Use the OpenAI callback handler
56
+ """
57
+ cb = OpenAICallbackHandler()
58
+ openai_callback_var.set(cb)
59
+ yield cb
60
+ openai_callback_var.set(None)
61
+
62
+
63
+ @contextmanager
64
+ def get_bedrock_anthropic_callback() -> Generator[
65
+ BedrockAnthropicTokenUsageCallbackHandler, None, None
66
+ ]:
67
+ """Get the Bedrock anthropic callback handler in a context manager.
68
+ which conveniently exposes token and cost information.
69
+
70
+ Returns:
71
+ BedrockAnthropicTokenUsageCallbackHandler:
72
+ The Bedrock anthropic callback handler.
73
+
74
+ Example:
75
+ >>> with get_bedrock_anthropic_callback() as cb:
76
+ ... # Use the Bedrock anthropic callback handler
77
+ """
78
+ cb = BedrockAnthropicTokenUsageCallbackHandler()
79
+ bedrock_anthropic_callback_var.set(cb)
80
+ yield cb
81
+ bedrock_anthropic_callback_var.set(None)
82
+
83
+
84
+ @contextmanager
85
+ def wandb_tracing_enabled(
86
+ session_name: str = "default",
87
+ ) -> Generator[None, None, None]:
88
+ """Get the WandbTracer in a context manager.
89
+
90
+ Args:
91
+ session_name (str, optional): The name of the session.
92
+ Defaults to "default".
93
+
94
+ Returns:
95
+ None
96
+
97
+ Example:
98
+ >>> with wandb_tracing_enabled() as session:
99
+ ... # Use the WandbTracer session
100
+ """
101
+ cb = WandbTracer()
102
+ wandb_tracing_callback_var.set(cb)
103
+ yield None
104
+ wandb_tracing_callback_var.set(None)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/mlflow_callback.py ADDED
@@ -0,0 +1,769 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import random
4
+ import string
5
+ import tempfile
6
+ import traceback
7
+ from copy import deepcopy
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional, Sequence, Union
10
+
11
+ from langchain_core.agents import AgentAction, AgentFinish
12
+ from langchain_core.callbacks import BaseCallbackHandler
13
+ from langchain_core.documents import Document
14
+ from langchain_core.outputs import LLMResult
15
+ from langchain_core.utils import get_from_dict_or_env, guard_import
16
+
17
+ from langchain_community.callbacks.utils import (
18
+ BaseMetadataCallbackHandler,
19
+ flatten_dict,
20
+ hash_string,
21
+ import_pandas,
22
+ import_spacy,
23
+ import_textstat,
24
+ )
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def import_mlflow() -> Any:
30
+ """Import the mlflow python package and raise an error if it is not installed."""
31
+ return guard_import("mlflow")
32
+
33
+
34
+ def mlflow_callback_metrics() -> List[str]:
35
+ """Get the metrics to log to MLFlow."""
36
+ return [
37
+ "step",
38
+ "starts",
39
+ "ends",
40
+ "errors",
41
+ "text_ctr",
42
+ "chain_starts",
43
+ "chain_ends",
44
+ "llm_starts",
45
+ "llm_ends",
46
+ "llm_streams",
47
+ "tool_starts",
48
+ "tool_ends",
49
+ "agent_ends",
50
+ "retriever_starts",
51
+ "retriever_ends",
52
+ ]
53
+
54
+
55
+ def get_text_complexity_metrics() -> List[str]:
56
+ """Get the text complexity metrics from textstat."""
57
+ return [
58
+ "flesch_reading_ease",
59
+ "flesch_kincaid_grade",
60
+ "smog_index",
61
+ "coleman_liau_index",
62
+ "automated_readability_index",
63
+ "dale_chall_readability_score",
64
+ "difficult_words",
65
+ "linsear_write_formula",
66
+ "gunning_fog",
67
+ # "text_standard"
68
+ "fernandez_huerta",
69
+ "szigriszt_pazos",
70
+ "gutierrez_polini",
71
+ "crawford",
72
+ "gulpease_index",
73
+ "osman",
74
+ ]
75
+
76
+
77
+ def analyze_text(
78
+ text: str,
79
+ nlp: Any = None,
80
+ textstat: Any = None,
81
+ ) -> dict:
82
+ """Analyze text using textstat and spacy.
83
+
84
+ Parameters:
85
+ text (str): The text to analyze.
86
+ nlp (spacy.lang): The spacy language model to use for visualization.
87
+ textstat: The textstat library to use for complexity metrics calculation.
88
+
89
+ Returns:
90
+ `dict` containing the complexity metrics and visualization
91
+ files serialized to HTML string.
92
+ """
93
+ resp: Dict[str, Any] = {}
94
+ if textstat is not None:
95
+ text_complexity_metrics = {
96
+ key: getattr(textstat, key)(text) for key in get_text_complexity_metrics()
97
+ }
98
+ resp.update({"text_complexity_metrics": text_complexity_metrics})
99
+ resp.update(text_complexity_metrics)
100
+
101
+ if nlp is not None:
102
+ spacy = import_spacy()
103
+ doc = nlp(text)
104
+
105
+ dep_out = spacy.displacy.render(doc, style="dep", jupyter=False, page=True)
106
+
107
+ ent_out = spacy.displacy.render(doc, style="ent", jupyter=False, page=True)
108
+
109
+ text_visualizations = {
110
+ "dependency_tree": dep_out,
111
+ "entities": ent_out,
112
+ }
113
+
114
+ resp.update(text_visualizations)
115
+
116
+ return resp
117
+
118
+
119
+ def construct_html_from_prompt_and_generation(prompt: str, generation: str) -> Any:
120
+ """Construct an html element from a prompt and a generation.
121
+
122
+ Parameters:
123
+ prompt (str): The prompt.
124
+ generation (str): The generation.
125
+
126
+ Returns:
127
+ (str): The html string."""
128
+ formatted_prompt = prompt.replace("\n", "<br>")
129
+ formatted_generation = generation.replace("\n", "<br>")
130
+
131
+ return f"""
132
+ <p style="color:black;">{formatted_prompt}:</p>
133
+ <blockquote>
134
+ <p style="color:green;">
135
+ {formatted_generation}
136
+ </p>
137
+ </blockquote>
138
+ """
139
+
140
+
141
+ class MlflowLogger:
142
+ """Callback Handler that logs metrics and artifacts to mlflow server.
143
+
144
+ Parameters:
145
+ name (str): Name of the run.
146
+ experiment (str): Name of the experiment.
147
+ tags (dict): Tags to be attached for the run.
148
+ tracking_uri (str): MLflow tracking server uri.
149
+
150
+ This handler implements the helper functions to initialize,
151
+ log metrics and artifacts to the mlflow server.
152
+ """
153
+
154
+ def __init__(self, **kwargs: Any):
155
+ self.mlflow = import_mlflow()
156
+ if "DATABRICKS_RUNTIME_VERSION" in os.environ:
157
+ self.mlflow.set_tracking_uri("databricks")
158
+ self.mlf_expid = self.mlflow.tracking.fluent._get_experiment_id()
159
+ self.mlf_exp = self.mlflow.get_experiment(self.mlf_expid)
160
+ else:
161
+ tracking_uri = get_from_dict_or_env(
162
+ kwargs, "tracking_uri", "MLFLOW_TRACKING_URI", ""
163
+ )
164
+ self.mlflow.set_tracking_uri(tracking_uri)
165
+
166
+ if run_id := kwargs.get("run_id"):
167
+ self.mlf_expid = self.mlflow.get_run(run_id).info.experiment_id
168
+ else:
169
+ # User can set other env variables described here
170
+ # > https://www.mlflow.org/docs/latest/tracking.html#logging-to-a-tracking-server
171
+
172
+ experiment_name = get_from_dict_or_env(
173
+ kwargs, "experiment_name", "MLFLOW_EXPERIMENT_NAME"
174
+ )
175
+ self.mlf_exp = self.mlflow.get_experiment_by_name(experiment_name)
176
+ if self.mlf_exp is not None:
177
+ self.mlf_expid = self.mlf_exp.experiment_id
178
+ else:
179
+ self.mlf_expid = self.mlflow.create_experiment(experiment_name)
180
+
181
+ self.start_run(
182
+ kwargs["run_name"], kwargs["run_tags"], kwargs.get("run_id", None)
183
+ )
184
+ self.dir = kwargs.get("artifacts_dir", "")
185
+
186
+ def start_run(
187
+ self, name: str, tags: Dict[str, str], run_id: Optional[str] = None
188
+ ) -> None:
189
+ """
190
+ If run_id is provided, it will reuse the run with the given run_id.
191
+ Otherwise, it starts a new run, auto generates the random suffix for name.
192
+ """
193
+ if run_id is None:
194
+ if name.endswith("-%"):
195
+ rname = "".join(
196
+ random.choices(string.ascii_uppercase + string.digits, k=7)
197
+ )
198
+ name = name[:-1] + rname
199
+ run = self.mlflow.MlflowClient().create_run(
200
+ self.mlf_expid, run_name=name, tags=tags
201
+ )
202
+ run_id = run.info.run_id
203
+ self.run_id = run_id
204
+
205
+ def finish_run(self) -> None:
206
+ """To finish the run."""
207
+ self.mlflow.end_run()
208
+
209
+ def metric(self, key: str, value: float) -> None:
210
+ """To log metric to mlflow server."""
211
+ self.mlflow.log_metric(key, value, run_id=self.run_id)
212
+
213
+ def metrics(
214
+ self, data: Union[Dict[str, float], Dict[str, int]], step: Optional[int] = 0
215
+ ) -> None:
216
+ """To log all metrics in the input dict."""
217
+ self.mlflow.log_metrics(data, run_id=self.run_id)
218
+
219
+ def jsonf(self, data: Dict[str, Any], filename: str) -> None:
220
+ """To log the input data as json file artifact."""
221
+ self.mlflow.log_dict(
222
+ data, os.path.join(self.dir, f"{filename}.json"), run_id=self.run_id
223
+ )
224
+
225
+ def table(self, name: str, dataframe: Any) -> None:
226
+ """To log the input pandas dataframe as a html table"""
227
+ self.html(dataframe.to_html(), f"table_{name}")
228
+
229
+ def html(self, html: str, filename: str) -> None:
230
+ """To log the input html string as html file artifact."""
231
+ self.mlflow.log_text(
232
+ html, os.path.join(self.dir, f"{filename}.html"), run_id=self.run_id
233
+ )
234
+
235
+ def text(self, text: str, filename: str) -> None:
236
+ """To log the input text as text file artifact."""
237
+ self.mlflow.log_text(
238
+ text, os.path.join(self.dir, f"{filename}.txt"), run_id=self.run_id
239
+ )
240
+
241
+ def artifact(self, path: str) -> None:
242
+ """To upload the file from given path as artifact."""
243
+ self.mlflow.log_artifact(path, run_id=self.run_id)
244
+
245
+ def langchain_artifact(self, chain: Any) -> None:
246
+ self.mlflow.langchain.log_model(chain, "langchain-model", run_id=self.run_id)
247
+
248
+
249
+ class MlflowCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
250
+ """Callback Handler that logs metrics and artifacts to mlflow server.
251
+
252
+ Parameters:
253
+ name (str): Name of the run.
254
+ experiment (str): Name of the experiment.
255
+ tags (dict): Tags to be attached for the run.
256
+ tracking_uri (str): MLflow tracking server uri.
257
+
258
+ This handler will utilize the associated callback method called and formats
259
+ the input of each callback function with metadata regarding the state of LLM run,
260
+ and adds the response to the list of records for both the {method}_records and
261
+ action. It then logs the response to mlflow server.
262
+ """
263
+
264
+ def __init__(
265
+ self,
266
+ name: Optional[str] = "langchainrun-%",
267
+ experiment: Optional[str] = "langchain",
268
+ tags: Optional[Dict] = None,
269
+ tracking_uri: Optional[str] = None,
270
+ run_id: Optional[str] = None,
271
+ artifacts_dir: str = "",
272
+ ) -> None:
273
+ """Initialize callback handler."""
274
+ import_pandas()
275
+ import_mlflow()
276
+ super().__init__()
277
+
278
+ self.name = name
279
+ self.experiment = experiment
280
+ self.tags = tags or {}
281
+ self.tracking_uri = tracking_uri
282
+ self.run_id = run_id
283
+ self.artifacts_dir = artifacts_dir
284
+
285
+ self.temp_dir = tempfile.TemporaryDirectory()
286
+
287
+ self.mlflg = MlflowLogger(
288
+ tracking_uri=self.tracking_uri,
289
+ experiment_name=self.experiment,
290
+ run_name=self.name,
291
+ run_tags=self.tags,
292
+ run_id=self.run_id,
293
+ artifacts_dir=self.artifacts_dir,
294
+ )
295
+
296
+ self.action_records: list = []
297
+ self.nlp = None
298
+ try:
299
+ spacy = import_spacy()
300
+ except ImportError as e:
301
+ logger.warning(e.msg)
302
+ else:
303
+ try:
304
+ self.nlp = spacy.load("en_core_web_sm")
305
+ except OSError:
306
+ logger.warning(
307
+ "Run `python -m spacy download en_core_web_sm` "
308
+ "to download en_core_web_sm model for text visualization."
309
+ )
310
+
311
+ try:
312
+ self.textstat = import_textstat()
313
+ except ImportError as e:
314
+ logger.warning(e.msg)
315
+ self.textstat = None
316
+
317
+ self.metrics = {key: 0 for key in mlflow_callback_metrics()}
318
+
319
+ self.records: Dict[str, Any] = {
320
+ "on_llm_start_records": [],
321
+ "on_llm_token_records": [],
322
+ "on_llm_end_records": [],
323
+ "on_chain_start_records": [],
324
+ "on_chain_end_records": [],
325
+ "on_tool_start_records": [],
326
+ "on_tool_end_records": [],
327
+ "on_text_records": [],
328
+ "on_agent_finish_records": [],
329
+ "on_agent_action_records": [],
330
+ "on_retriever_start_records": [],
331
+ "on_retriever_end_records": [],
332
+ "action_records": [],
333
+ }
334
+
335
+ def _reset(self) -> None:
336
+ for k, v in self.metrics.items():
337
+ self.metrics[k] = 0
338
+ for k, v in self.records.items():
339
+ self.records[k] = []
340
+
341
+ def on_llm_start(
342
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
343
+ ) -> None:
344
+ """Run when LLM starts."""
345
+ self.metrics["step"] += 1
346
+ self.metrics["llm_starts"] += 1
347
+ self.metrics["starts"] += 1
348
+
349
+ llm_starts = self.metrics["llm_starts"]
350
+
351
+ resp: Dict[str, Any] = {}
352
+ resp.update({"action": "on_llm_start"})
353
+ resp.update(flatten_dict(serialized))
354
+ resp.update(self.metrics)
355
+
356
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
357
+
358
+ for idx, prompt in enumerate(prompts):
359
+ prompt_resp = deepcopy(resp)
360
+ prompt_resp["prompt"] = prompt
361
+ self.records["on_llm_start_records"].append(prompt_resp)
362
+ self.records["action_records"].append(prompt_resp)
363
+ self.mlflg.jsonf(prompt_resp, f"llm_start_{llm_starts}_prompt_{idx}")
364
+
365
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
366
+ """Run when LLM generates a new token."""
367
+ self.metrics["step"] += 1
368
+ self.metrics["llm_streams"] += 1
369
+
370
+ llm_streams = self.metrics["llm_streams"]
371
+
372
+ resp: Dict[str, Any] = {}
373
+ resp.update({"action": "on_llm_new_token", "token": token})
374
+ resp.update(self.metrics)
375
+
376
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
377
+
378
+ self.records["on_llm_token_records"].append(resp)
379
+ self.records["action_records"].append(resp)
380
+ self.mlflg.jsonf(resp, f"llm_new_tokens_{llm_streams}")
381
+
382
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
383
+ """Run when LLM ends running."""
384
+ self.metrics["step"] += 1
385
+ self.metrics["llm_ends"] += 1
386
+ self.metrics["ends"] += 1
387
+
388
+ llm_ends = self.metrics["llm_ends"]
389
+
390
+ resp: Dict[str, Any] = {}
391
+ resp.update({"action": "on_llm_end"})
392
+ resp.update(flatten_dict(response.llm_output or {}))
393
+ resp.update(self.metrics)
394
+
395
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
396
+
397
+ for generations in response.generations:
398
+ for idx, generation in enumerate(generations):
399
+ generation_resp = deepcopy(resp)
400
+ generation_resp.update(flatten_dict(generation.dict()))
401
+ generation_resp.update(
402
+ analyze_text(
403
+ generation.text,
404
+ nlp=self.nlp,
405
+ textstat=self.textstat,
406
+ )
407
+ )
408
+ if "text_complexity_metrics" in generation_resp:
409
+ complexity_metrics: Dict[str, float] = generation_resp.pop(
410
+ "text_complexity_metrics"
411
+ )
412
+ self.mlflg.metrics(
413
+ complexity_metrics,
414
+ step=self.metrics["step"],
415
+ )
416
+ self.records["on_llm_end_records"].append(generation_resp)
417
+ self.records["action_records"].append(generation_resp)
418
+ self.mlflg.jsonf(resp, f"llm_end_{llm_ends}_generation_{idx}")
419
+ if "dependency_tree" in generation_resp:
420
+ dependency_tree = generation_resp["dependency_tree"]
421
+ self.mlflg.html(
422
+ dependency_tree, "dep-" + hash_string(generation.text)
423
+ )
424
+ if "entities" in generation_resp:
425
+ entities = generation_resp["entities"]
426
+ self.mlflg.html(entities, "ent-" + hash_string(generation.text))
427
+
428
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
429
+ """Run when LLM errors."""
430
+ self.metrics["step"] += 1
431
+ self.metrics["errors"] += 1
432
+
433
+ def on_chain_start(
434
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
435
+ ) -> None:
436
+ """Run when chain starts running."""
437
+ self.metrics["step"] += 1
438
+ self.metrics["chain_starts"] += 1
439
+ self.metrics["starts"] += 1
440
+
441
+ chain_starts = self.metrics["chain_starts"]
442
+
443
+ resp: Dict[str, Any] = {}
444
+ resp.update({"action": "on_chain_start"})
445
+ resp.update(flatten_dict(serialized))
446
+ resp.update(self.metrics)
447
+
448
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
449
+
450
+ if isinstance(inputs, dict):
451
+ chain_input = ",".join([f"{k}={v}" for k, v in inputs.items()])
452
+ elif isinstance(inputs, list):
453
+ chain_input = ",".join([str(input) for input in inputs])
454
+ else:
455
+ chain_input = str(inputs)
456
+ input_resp = deepcopy(resp)
457
+ input_resp["inputs"] = chain_input
458
+ self.records["on_chain_start_records"].append(input_resp)
459
+ self.records["action_records"].append(input_resp)
460
+ self.mlflg.jsonf(input_resp, f"chain_start_{chain_starts}")
461
+
462
+ def on_chain_end(
463
+ self, outputs: Union[Dict[str, Any], str, List[str]], **kwargs: Any
464
+ ) -> None:
465
+ """Run when chain ends running."""
466
+ self.metrics["step"] += 1
467
+ self.metrics["chain_ends"] += 1
468
+ self.metrics["ends"] += 1
469
+
470
+ chain_ends = self.metrics["chain_ends"]
471
+
472
+ resp: Dict[str, Any] = {}
473
+ if isinstance(outputs, dict):
474
+ chain_output = ",".join([f"{k}={v}" for k, v in outputs.items()])
475
+ elif isinstance(outputs, list):
476
+ chain_output = ",".join(map(str, outputs))
477
+ else:
478
+ chain_output = str(outputs)
479
+ resp.update({"action": "on_chain_end", "outputs": chain_output})
480
+ resp.update(self.metrics)
481
+
482
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
483
+
484
+ self.records["on_chain_end_records"].append(resp)
485
+ self.records["action_records"].append(resp)
486
+ self.mlflg.jsonf(resp, f"chain_end_{chain_ends}")
487
+
488
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
489
+ """Run when chain errors."""
490
+ self.metrics["step"] += 1
491
+ self.metrics["errors"] += 1
492
+
493
+ def on_tool_start(
494
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
495
+ ) -> None:
496
+ """Run when tool starts running."""
497
+ self.metrics["step"] += 1
498
+ self.metrics["tool_starts"] += 1
499
+ self.metrics["starts"] += 1
500
+
501
+ tool_starts = self.metrics["tool_starts"]
502
+
503
+ resp: Dict[str, Any] = {}
504
+ resp.update({"action": "on_tool_start", "input_str": input_str})
505
+ resp.update(flatten_dict(serialized))
506
+ resp.update(self.metrics)
507
+
508
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
509
+
510
+ self.records["on_tool_start_records"].append(resp)
511
+ self.records["action_records"].append(resp)
512
+ self.mlflg.jsonf(resp, f"tool_start_{tool_starts}")
513
+
514
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
515
+ """Run when tool ends running."""
516
+ output = str(output)
517
+ self.metrics["step"] += 1
518
+ self.metrics["tool_ends"] += 1
519
+ self.metrics["ends"] += 1
520
+
521
+ tool_ends = self.metrics["tool_ends"]
522
+
523
+ resp: Dict[str, Any] = {}
524
+ resp.update({"action": "on_tool_end", "output": output})
525
+ resp.update(self.metrics)
526
+
527
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
528
+
529
+ self.records["on_tool_end_records"].append(resp)
530
+ self.records["action_records"].append(resp)
531
+ self.mlflg.jsonf(resp, f"tool_end_{tool_ends}")
532
+
533
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
534
+ """Run when tool errors."""
535
+ self.metrics["step"] += 1
536
+ self.metrics["errors"] += 1
537
+
538
+ def on_text(self, text: str, **kwargs: Any) -> None:
539
+ """
540
+ Run when text is received.
541
+ """
542
+ self.metrics["step"] += 1
543
+ self.metrics["text_ctr"] += 1
544
+
545
+ text_ctr = self.metrics["text_ctr"]
546
+
547
+ resp: Dict[str, Any] = {}
548
+ resp.update({"action": "on_text", "text": text})
549
+ resp.update(self.metrics)
550
+
551
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
552
+
553
+ self.records["on_text_records"].append(resp)
554
+ self.records["action_records"].append(resp)
555
+ self.mlflg.jsonf(resp, f"on_text_{text_ctr}")
556
+
557
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
558
+ """Run when agent ends running."""
559
+ self.metrics["step"] += 1
560
+ self.metrics["agent_ends"] += 1
561
+ self.metrics["ends"] += 1
562
+
563
+ agent_ends = self.metrics["agent_ends"]
564
+ resp: Dict[str, Any] = {}
565
+ resp.update(
566
+ {
567
+ "action": "on_agent_finish",
568
+ "output": finish.return_values["output"],
569
+ "log": finish.log,
570
+ }
571
+ )
572
+ resp.update(self.metrics)
573
+
574
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
575
+
576
+ self.records["on_agent_finish_records"].append(resp)
577
+ self.records["action_records"].append(resp)
578
+ self.mlflg.jsonf(resp, f"agent_finish_{agent_ends}")
579
+
580
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
581
+ """Run on agent action."""
582
+ self.metrics["step"] += 1
583
+ self.metrics["tool_starts"] += 1
584
+ self.metrics["starts"] += 1
585
+
586
+ tool_starts = self.metrics["tool_starts"]
587
+ resp: Dict[str, Any] = {}
588
+ resp.update(
589
+ {
590
+ "action": "on_agent_action",
591
+ "tool": action.tool,
592
+ "tool_input": action.tool_input,
593
+ "log": action.log,
594
+ }
595
+ )
596
+ resp.update(self.metrics)
597
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
598
+ self.records["on_agent_action_records"].append(resp)
599
+ self.records["action_records"].append(resp)
600
+ self.mlflg.jsonf(resp, f"agent_action_{tool_starts}")
601
+
602
+ def on_retriever_start(
603
+ self,
604
+ serialized: Dict[str, Any],
605
+ query: str,
606
+ **kwargs: Any,
607
+ ) -> Any:
608
+ """Run when Retriever starts running."""
609
+ self.metrics["step"] += 1
610
+ self.metrics["retriever_starts"] += 1
611
+ self.metrics["starts"] += 1
612
+
613
+ retriever_starts = self.metrics["retriever_starts"]
614
+
615
+ resp: Dict[str, Any] = {}
616
+ resp.update({"action": "on_retriever_start", "query": query})
617
+ resp.update(flatten_dict(serialized))
618
+ resp.update(self.metrics)
619
+
620
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
621
+
622
+ self.records["on_retriever_start_records"].append(resp)
623
+ self.records["action_records"].append(resp)
624
+ self.mlflg.jsonf(resp, f"retriever_start_{retriever_starts}")
625
+
626
+ def on_retriever_end(
627
+ self,
628
+ documents: Sequence[Document],
629
+ **kwargs: Any,
630
+ ) -> Any:
631
+ """Run when Retriever ends running."""
632
+ self.metrics["step"] += 1
633
+ self.metrics["retriever_ends"] += 1
634
+ self.metrics["ends"] += 1
635
+
636
+ retriever_ends = self.metrics["retriever_ends"]
637
+
638
+ resp: Dict[str, Any] = {}
639
+ retriever_documents = [
640
+ {
641
+ "page_content": doc.page_content,
642
+ "metadata": {
643
+ k: (
644
+ str(v)
645
+ if not isinstance(v, list)
646
+ else ",".join(str(x) for x in v)
647
+ )
648
+ for k, v in doc.metadata.items()
649
+ },
650
+ }
651
+ for doc in documents
652
+ ]
653
+ resp.update({"action": "on_retriever_end", "documents": retriever_documents})
654
+ resp.update(self.metrics)
655
+
656
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
657
+
658
+ self.records["on_retriever_end_records"].append(resp)
659
+ self.records["action_records"].append(resp)
660
+ self.mlflg.jsonf(resp, f"retriever_end_{retriever_ends}")
661
+
662
+ def on_retriever_error(self, error: BaseException, **kwargs: Any) -> Any:
663
+ """Run when Retriever errors."""
664
+ self.metrics["step"] += 1
665
+ self.metrics["errors"] += 1
666
+
667
+ def _create_session_analysis_df(self) -> Any:
668
+ """Create a dataframe with all the information from the session."""
669
+ pd = import_pandas()
670
+ on_llm_start_records_df = pd.DataFrame(self.records["on_llm_start_records"])
671
+ on_llm_end_records_df = pd.DataFrame(self.records["on_llm_end_records"])
672
+
673
+ llm_input_columns = ["step", "prompt"]
674
+ if "name" in on_llm_start_records_df.columns:
675
+ llm_input_columns.append("name")
676
+ elif "id" in on_llm_start_records_df.columns:
677
+ # id is llm class's full import path. For example:
678
+ # ["langchain", "llms", "openai", "AzureOpenAI"]
679
+ on_llm_start_records_df["name"] = on_llm_start_records_df["id"].apply(
680
+ lambda id_: id_[-1]
681
+ )
682
+ llm_input_columns.append("name")
683
+ llm_input_prompts_df = (
684
+ on_llm_start_records_df[llm_input_columns]
685
+ .dropna(axis=1)
686
+ .rename({"step": "prompt_step"}, axis=1)
687
+ )
688
+ complexity_metrics_columns = (
689
+ get_text_complexity_metrics() if self.textstat is not None else []
690
+ )
691
+ visualizations_columns = (
692
+ ["dependency_tree", "entities"] if self.nlp is not None else []
693
+ )
694
+
695
+ token_usage_columns = [
696
+ "token_usage_total_tokens",
697
+ "token_usage_prompt_tokens",
698
+ "token_usage_completion_tokens",
699
+ ]
700
+ token_usage_columns = [
701
+ x for x in token_usage_columns if x in on_llm_end_records_df.columns
702
+ ]
703
+
704
+ llm_outputs_df = (
705
+ on_llm_end_records_df[
706
+ [
707
+ "step",
708
+ "text",
709
+ ]
710
+ + token_usage_columns
711
+ + complexity_metrics_columns
712
+ + visualizations_columns
713
+ ]
714
+ .dropna(axis=1)
715
+ .rename({"step": "output_step", "text": "output"}, axis=1)
716
+ )
717
+ session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1)
718
+ session_analysis_df["chat_html"] = session_analysis_df[
719
+ ["prompt", "output"]
720
+ ].apply(
721
+ lambda row: construct_html_from_prompt_and_generation(
722
+ row["prompt"], row["output"]
723
+ ),
724
+ axis=1,
725
+ )
726
+ return session_analysis_df
727
+
728
+ def _contain_llm_records(self) -> bool:
729
+ return bool(self.records["on_llm_start_records"])
730
+
731
+ def flush_tracker(self, langchain_asset: Any = None, finish: bool = False) -> None:
732
+ pd = import_pandas()
733
+ self.mlflg.table("action_records", pd.DataFrame(self.records["action_records"]))
734
+ if self._contain_llm_records():
735
+ session_analysis_df = self._create_session_analysis_df()
736
+ chat_html = session_analysis_df.pop("chat_html")
737
+ chat_html = chat_html.replace("\n", "", regex=True)
738
+ self.mlflg.table("session_analysis", pd.DataFrame(session_analysis_df))
739
+ self.mlflg.html("".join(chat_html.tolist()), "chat_html")
740
+
741
+ if langchain_asset:
742
+ # To avoid circular import error
743
+ # mlflow only supports LLMChain asset
744
+ if "langchain.chains.llm.LLMChain" in str(type(langchain_asset)):
745
+ self.mlflg.langchain_artifact(langchain_asset)
746
+ else:
747
+ langchain_asset_path = str(Path(self.temp_dir.name, "model.json"))
748
+ try:
749
+ langchain_asset.save(langchain_asset_path)
750
+ self.mlflg.artifact(langchain_asset_path)
751
+ except ValueError:
752
+ try:
753
+ langchain_asset.save_agent(langchain_asset_path)
754
+ self.mlflg.artifact(langchain_asset_path)
755
+ except AttributeError:
756
+ print("Could not save model.") # noqa: T201
757
+ traceback.print_exc()
758
+ pass
759
+ except NotImplementedError:
760
+ print("Could not save model.") # noqa: T201
761
+ traceback.print_exc()
762
+ pass
763
+ except NotImplementedError:
764
+ print("Could not save model.") # noqa: T201
765
+ traceback.print_exc()
766
+ pass
767
+ if finish:
768
+ self.mlflg.finish_run()
769
+ self._reset()
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/openai_info.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Callback Handler that prints to std out."""
2
+
3
+ import threading
4
+ from enum import Enum, auto
5
+ from typing import Any, Dict, List
6
+
7
+ from langchain_core._api import warn_deprecated
8
+ from langchain_core.callbacks import BaseCallbackHandler
9
+ from langchain_core.messages import AIMessage
10
+ from langchain_core.outputs import ChatGeneration, LLMResult
11
+
12
+ MODEL_COST_PER_1K_TOKENS = {
13
+ # GPT-5 input
14
+ "gpt-5": 0.00125,
15
+ "gpt-5-cached": 0.000125,
16
+ "gpt-5-2025-08-07": 0.00125,
17
+ "gpt-5-2025-08-07-cached": 0.000125,
18
+ # GPT-5 output
19
+ "gpt-5-completion": 0.01,
20
+ "gpt-5-2025-08-07-completion": 0.01,
21
+ # GPT-5-mini input
22
+ "gpt-5-mini": 0.00025,
23
+ "gpt-5-mini-cached": 0.000025,
24
+ "gpt-5-mini-2025-08-07": 0.00025,
25
+ "gpt-5-mini-2025-08-07-cached": 0.000025,
26
+ # GPT-5-mini output
27
+ "gpt-5-mini-completion": 0.002,
28
+ "gpt-5-mini-2025-08-07-completion": 0.002,
29
+ # GPT-5-nano input
30
+ "gpt-5-nano": 0.00005,
31
+ "gpt-5-nano-cached": 0.000005,
32
+ "gpt-5-nano-2025-08-07": 0.00005,
33
+ "gpt-5-nano-2025-08-07-cached": 0.000005,
34
+ # GPT-5-nano output
35
+ "gpt-5-nano-completion": 0.0004,
36
+ "gpt-5-nano-2025-08-07-completion": 0.0004,
37
+ # GPT-5-chat-latest input
38
+ "gpt-5-chat-latest": 0.00125,
39
+ "gpt-5-chat-latest-cached": 0.000125,
40
+ "gpt-5-chat-latest-2025-08-07": 0.00125,
41
+ "gpt-5-chat-latest-2025-08-07-cached": 0.000125,
42
+ # GPT-5-chat-latest output
43
+ "gpt-5-chat-latest-completion": 0.01,
44
+ "gpt-5-chat-latest-2025-08-07-completion": 0.01,
45
+ # GPT-4.1 input
46
+ "gpt-4.1": 0.002,
47
+ "gpt-4.1-2025-04-14": 0.002,
48
+ "gpt-4.1-cached": 0.0005,
49
+ "gpt-4.1-2025-04-14-cached": 0.0005,
50
+ # GPT-4.1 output
51
+ "gpt-4.1-completion": 0.008,
52
+ "gpt-4.1-2025-04-14-completion": 0.008,
53
+ # GPT-4.1-mini input
54
+ "gpt-4.1-mini": 0.0004,
55
+ "gpt-4.1-mini-2025-04-14": 0.0004,
56
+ "gpt-4.1-mini-cached": 0.0001,
57
+ "gpt-4.1-mini-2025-04-14-cached": 0.0001,
58
+ # GPT-4.1-mini output
59
+ "gpt-4.1-mini-completion": 0.0016,
60
+ "gpt-4.1-mini-2025-04-14-completion": 0.0016,
61
+ # GPT-4.1-nano input
62
+ "gpt-4.1-nano": 0.0001,
63
+ "gpt-4.1-nano-2025-04-14": 0.0001,
64
+ "gpt-4.1-nano-cached": 0.000025,
65
+ "gpt-4.1-nano-2025-04-14-cached": 0.000025,
66
+ # GPT-4.1-nano output
67
+ "gpt-4.1-nano-completion": 0.0004,
68
+ "gpt-4.1-nano-2025-04-14-completion": 0.0004,
69
+ # GPT-4.5-preview input
70
+ "gpt-4.5-preview": 0.075,
71
+ "gpt-4.5-preview-2025-02-27": 0.075,
72
+ "gpt-4.5-preview-cached": 0.0375,
73
+ "gpt-4.5-preview-2025-02-27-cached": 0.0375,
74
+ # GPT-4.5-preview output
75
+ "gpt-4.5-preview-completion": 0.15,
76
+ "gpt-4.5-preview-2025-02-27-completion": 0.15,
77
+ # OpenAI o1 input
78
+ "o1": 0.015,
79
+ "o1-2024-12-17": 0.015,
80
+ "o1-cached": 0.0075,
81
+ "o1-2024-12-17-cached": 0.0075,
82
+ # OpenAI o1 output
83
+ "o1-completion": 0.06,
84
+ "o1-2024-12-17-completion": 0.06,
85
+ # OpenAI o1-pro input
86
+ "o1-pro": 0.15,
87
+ "o1-pro-2025-03-19": 0.15,
88
+ # OpenAI o1-pro output
89
+ "o1-pro-completion": 0.6,
90
+ "o1-pro-2025-03-19-completion": 0.6,
91
+ # OpenAI o3 input
92
+ "o3": 0.002,
93
+ "o3-2025-04-16": 0.002,
94
+ "o3-cached": 0.0005,
95
+ "o3-2025-04-16-cached": 0.0005,
96
+ # OpenAI o3 output
97
+ "o3-completion": 0.008,
98
+ "o3-2025-04-16-completion": 0.008,
99
+ # OpenAI o4-mini input
100
+ "o4-mini": 0.0011,
101
+ "o4-mini-2025-04-16": 0.0011,
102
+ "o4-mini-cached": 0.000275,
103
+ "o4-mini-2025-04-16-cached": 0.000275,
104
+ # OpenAI o4-mini output
105
+ "o4-mini-completion": 0.0044,
106
+ "o4-mini-2025-04-16-completion": 0.0044,
107
+ # OpenAI o3-mini input
108
+ "o3-mini": 0.0011,
109
+ "o3-mini-2025-01-31": 0.0011,
110
+ "o3-mini-cached": 0.00055,
111
+ "o3-mini-2025-01-31-cached": 0.00055,
112
+ # OpenAI o3-mini output
113
+ "o3-mini-completion": 0.0044,
114
+ "o3-mini-2025-01-31-completion": 0.0044,
115
+ # OpenAI o1-mini input (updated pricing)
116
+ "o1-mini": 0.0011,
117
+ "o1-mini-cached": 0.00055,
118
+ "o1-mini-2024-09-12": 0.0011,
119
+ "o1-mini-2024-09-12-cached": 0.00055,
120
+ # OpenAI o1-mini output (updated pricing)
121
+ "o1-mini-completion": 0.0044,
122
+ "o1-mini-2024-09-12-completion": 0.0044,
123
+ # OpenAI o1-preview input
124
+ "o1-preview": 0.015,
125
+ "o1-preview-cached": 0.0075,
126
+ "o1-preview-2024-09-12": 0.015,
127
+ "o1-preview-2024-09-12-cached": 0.0075,
128
+ # OpenAI o1-preview output
129
+ "o1-preview-completion": 0.06,
130
+ "o1-preview-2024-09-12-completion": 0.06,
131
+ # GPT-4o input
132
+ "gpt-4o": 0.0025,
133
+ "gpt-4o-cached": 0.00125,
134
+ "gpt-4o-2024-05-13": 0.005,
135
+ "gpt-4o-2024-08-06": 0.0025,
136
+ "gpt-4o-2024-08-06-cached": 0.00125,
137
+ "gpt-4o-2024-11-20": 0.0025,
138
+ "gpt-4o-2024-11-20-cached": 0.00125,
139
+ # GPT-4o output
140
+ "gpt-4o-completion": 0.01,
141
+ "gpt-4o-2024-05-13-completion": 0.015,
142
+ "gpt-4o-2024-08-06-completion": 0.01,
143
+ "gpt-4o-2024-11-20-completion": 0.01,
144
+ # GPT-4o-audio-preview input
145
+ "gpt-4o-audio-preview": 0.0025,
146
+ "gpt-4o-audio-preview-2024-12-17": 0.0025,
147
+ "gpt-4o-audio-preview-2024-10-01": 0.0025,
148
+ # GPT-4o-audio-preview output
149
+ "gpt-4o-audio-preview-completion": 0.01,
150
+ "gpt-4o-audio-preview-2024-12-17-completion": 0.01,
151
+ "gpt-4o-audio-preview-2024-10-01-completion": 0.01,
152
+ # GPT-4o-realtime-preview input
153
+ "gpt-4o-realtime-preview": 0.005,
154
+ "gpt-4o-realtime-preview-2024-12-17": 0.005,
155
+ "gpt-4o-realtime-preview-2024-10-01": 0.005,
156
+ "gpt-4o-realtime-preview-cached": 0.0025,
157
+ "gpt-4o-realtime-preview-2024-12-17-cached": 0.0025,
158
+ "gpt-4o-realtime-preview-2024-10-01-cached": 0.0025,
159
+ # GPT-4o-realtime-preview output
160
+ "gpt-4o-realtime-preview-completion": 0.02,
161
+ "gpt-4o-realtime-preview-2024-12-17-completion": 0.02,
162
+ "gpt-4o-realtime-preview-2024-10-01-completion": 0.02,
163
+ # GPT-4o-mini input
164
+ "gpt-4o-mini": 0.00015,
165
+ "gpt-4o-mini-cached": 0.000075,
166
+ "gpt-4o-mini-2024-07-18": 0.00015,
167
+ "gpt-4o-mini-2024-07-18-cached": 0.000075,
168
+ # GPT-4o-mini output
169
+ "gpt-4o-mini-completion": 0.0006,
170
+ "gpt-4o-mini-2024-07-18-completion": 0.0006,
171
+ # GPT-4o-mini-audio-preview input
172
+ "gpt-4o-mini-audio-preview": 0.00015,
173
+ "gpt-4o-mini-audio-preview-2024-12-17": 0.00015,
174
+ # GPT-4o-mini-audio-preview output
175
+ "gpt-4o-mini-audio-preview-completion": 0.0006,
176
+ "gpt-4o-mini-audio-preview-2024-12-17-completion": 0.0006,
177
+ # GPT-4o-mini-realtime-preview input
178
+ "gpt-4o-mini-realtime-preview": 0.0006,
179
+ "gpt-4o-mini-realtime-preview-2024-12-17": 0.0006,
180
+ "gpt-4o-mini-realtime-preview-cached": 0.0003,
181
+ "gpt-4o-mini-realtime-preview-2024-12-17-cached": 0.0003,
182
+ # GPT-4o-mini-realtime-preview output
183
+ "gpt-4o-mini-realtime-preview-completion": 0.0024,
184
+ "gpt-4o-mini-realtime-preview-2024-12-17-completion": 0.0024,
185
+ # GPT-4o-mini-search-preview input
186
+ "gpt-4o-mini-search-preview": 0.00015,
187
+ "gpt-4o-mini-search-preview-2025-03-11": 0.00015,
188
+ # GPT-4o-mini-search-preview output
189
+ "gpt-4o-mini-search-preview-completion": 0.0006,
190
+ "gpt-4o-mini-search-preview-2025-03-11-completion": 0.0006,
191
+ # GPT-4o-search-preview input
192
+ "gpt-4o-search-preview": 0.0025,
193
+ "gpt-4o-search-preview-2025-03-11": 0.0025,
194
+ # GPT-4o-search-preview output
195
+ "gpt-4o-search-preview-completion": 0.01,
196
+ "gpt-4o-search-preview-2025-03-11-completion": 0.01,
197
+ # Computer-use-preview input
198
+ "computer-use-preview": 0.003,
199
+ "computer-use-preview-2025-03-11": 0.003,
200
+ # Computer-use-preview output
201
+ "computer-use-preview-completion": 0.012,
202
+ "computer-use-preview-2025-03-11-completion": 0.012,
203
+ # GPT-4 input
204
+ "gpt-4": 0.03,
205
+ "gpt-4-0314": 0.03,
206
+ "gpt-4-0613": 0.03,
207
+ "gpt-4-32k": 0.06,
208
+ "gpt-4-32k-0314": 0.06,
209
+ "gpt-4-32k-0613": 0.06,
210
+ "gpt-4-vision-preview": 0.01,
211
+ "gpt-4-1106-preview": 0.01,
212
+ "gpt-4-0125-preview": 0.01,
213
+ "gpt-4-turbo-preview": 0.01,
214
+ "gpt-4-turbo": 0.01,
215
+ "gpt-4-turbo-2024-04-09": 0.01,
216
+ # GPT-4 output
217
+ "gpt-4-completion": 0.06,
218
+ "gpt-4-0314-completion": 0.06,
219
+ "gpt-4-0613-completion": 0.06,
220
+ "gpt-4-32k-completion": 0.12,
221
+ "gpt-4-32k-0314-completion": 0.12,
222
+ "gpt-4-32k-0613-completion": 0.12,
223
+ "gpt-4-vision-preview-completion": 0.03,
224
+ "gpt-4-1106-preview-completion": 0.03,
225
+ "gpt-4-0125-preview-completion": 0.03,
226
+ "gpt-4-turbo-preview-completion": 0.03,
227
+ "gpt-4-turbo-completion": 0.03,
228
+ "gpt-4-turbo-2024-04-09-completion": 0.03,
229
+ # GPT-3.5 input
230
+ # gpt-3.5-turbo points at gpt-3.5-turbo-0613 until Feb 16, 2024.
231
+ # Switches to gpt-3.5-turbo-0125 after.
232
+ "gpt-3.5-turbo": 0.0015,
233
+ "gpt-3.5-turbo-0125": 0.0005,
234
+ "gpt-3.5-turbo-0301": 0.0015,
235
+ "gpt-3.5-turbo-0613": 0.0015,
236
+ "gpt-3.5-turbo-1106": 0.001,
237
+ "gpt-3.5-turbo-instruct": 0.0015,
238
+ "gpt-3.5-turbo-16k": 0.003,
239
+ "gpt-3.5-turbo-16k-0613": 0.003,
240
+ # GPT-3.5 output
241
+ # gpt-3.5-turbo points at gpt-3.5-turbo-0613 until Feb 16, 2024.
242
+ # Switches to gpt-3.5-turbo-0125 after.
243
+ "gpt-3.5-turbo-completion": 0.002,
244
+ "gpt-3.5-turbo-0125-completion": 0.0015,
245
+ "gpt-3.5-turbo-0301-completion": 0.002,
246
+ "gpt-3.5-turbo-0613-completion": 0.002,
247
+ "gpt-3.5-turbo-1106-completion": 0.002,
248
+ "gpt-3.5-turbo-instruct-completion": 0.002,
249
+ "gpt-3.5-turbo-16k-completion": 0.004,
250
+ "gpt-3.5-turbo-16k-0613-completion": 0.004,
251
+ # Azure GPT-35 input
252
+ "gpt-35-turbo": 0.0015, # Azure OpenAI version of ChatGPT
253
+ "gpt-35-turbo-0125": 0.0005,
254
+ "gpt-35-turbo-0301": 0.002, # Azure OpenAI version of ChatGPT
255
+ "gpt-35-turbo-0613": 0.0015,
256
+ "gpt-35-turbo-instruct": 0.0015,
257
+ "gpt-35-turbo-16k": 0.003,
258
+ "gpt-35-turbo-16k-0613": 0.003,
259
+ # Azure GPT-35 output
260
+ "gpt-35-turbo-completion": 0.002, # Azure OpenAI version of ChatGPT
261
+ "gpt-35-turbo-0125-completion": 0.0015,
262
+ "gpt-35-turbo-0301-completion": 0.002, # Azure OpenAI version of ChatGPT
263
+ "gpt-35-turbo-0613-completion": 0.002,
264
+ "gpt-35-turbo-instruct-completion": 0.002,
265
+ "gpt-35-turbo-16k-completion": 0.004,
266
+ "gpt-35-turbo-16k-0613-completion": 0.004,
267
+ # Others
268
+ "text-ada-001": 0.0004,
269
+ "ada": 0.0004,
270
+ "text-babbage-001": 0.0005,
271
+ "babbage": 0.0005,
272
+ "text-curie-001": 0.002,
273
+ "curie": 0.002,
274
+ "text-davinci-003": 0.02,
275
+ "text-davinci-002": 0.02,
276
+ "code-davinci-002": 0.02,
277
+ # Fine Tuned input
278
+ "babbage-002-finetuned": 0.0016,
279
+ "davinci-002-finetuned": 0.012,
280
+ "gpt-3.5-turbo-0613-finetuned": 0.003,
281
+ "gpt-3.5-turbo-1106-finetuned": 0.003,
282
+ "gpt-3.5-turbo-0125-finetuned": 0.003,
283
+ "gpt-4o-mini-2024-07-18-finetuned": 0.0003,
284
+ "gpt-4o-mini-2024-07-18-finetuned-cached": 0.00015,
285
+ # Fine Tuned output
286
+ "babbage-002-finetuned-completion": 0.0016,
287
+ "davinci-002-finetuned-completion": 0.012,
288
+ "gpt-3.5-turbo-0613-finetuned-completion": 0.006,
289
+ "gpt-3.5-turbo-1106-finetuned-completion": 0.006,
290
+ "gpt-3.5-turbo-0125-finetuned-completion": 0.006,
291
+ "gpt-4o-mini-2024-07-18-finetuned-completion": 0.0012,
292
+ # Azure Fine Tuned input
293
+ "babbage-002-azure-finetuned": 0.0004,
294
+ "davinci-002-azure-finetuned": 0.002,
295
+ "gpt-35-turbo-0613-azure-finetuned": 0.0015,
296
+ # Azure Fine Tuned output
297
+ "babbage-002-azure-finetuned-completion": 0.0004,
298
+ "davinci-002-azure-finetuned-completion": 0.002,
299
+ "gpt-35-turbo-0613-azure-finetuned-completion": 0.002,
300
+ # Legacy fine-tuned models
301
+ "ada-finetuned-legacy": 0.0016,
302
+ "babbage-finetuned-legacy": 0.0024,
303
+ "curie-finetuned-legacy": 0.012,
304
+ "davinci-finetuned-legacy": 0.12,
305
+ }
306
+
307
+
308
+ class TokenType(Enum):
309
+ """Token type enum."""
310
+
311
+ PROMPT = auto()
312
+ PROMPT_CACHED = auto()
313
+ COMPLETION = auto()
314
+
315
+
316
+ def standardize_model_name(
317
+ model_name: str,
318
+ is_completion: bool = False,
319
+ *,
320
+ token_type: TokenType = TokenType.PROMPT,
321
+ ) -> str:
322
+ """
323
+ Standardize the model name to a format that can be used in the OpenAI API.
324
+
325
+ Args:
326
+ model_name: Model name to standardize.
327
+ is_completion: Whether the model is used for completion or not.
328
+ Defaults to False. Deprecated in favor of ``token_type``.
329
+ token_type: Token type. Defaults to ``TokenType.PROMPT``.
330
+
331
+ Returns:
332
+ Standardized model name.
333
+
334
+ """
335
+ if is_completion:
336
+ warn_deprecated(
337
+ since="0.3.13",
338
+ message=(
339
+ "is_completion is deprecated. Use token_type instead. Example:\n\n"
340
+ "from langchain_community.callbacks.openai_info import TokenType\n\n"
341
+ "standardize_model_name('gpt-4o', token_type=TokenType.COMPLETION)\n"
342
+ ),
343
+ removal="1.0",
344
+ )
345
+ token_type = TokenType.COMPLETION
346
+ model_name = model_name.lower()
347
+ if ".ft-" in model_name:
348
+ model_name = model_name.split(".ft-")[0] + "-azure-finetuned"
349
+ if ":ft-" in model_name:
350
+ model_name = model_name.split(":")[0] + "-finetuned-legacy"
351
+ if "ft:" in model_name:
352
+ model_name = model_name.split(":")[1] + "-finetuned"
353
+ if token_type == TokenType.COMPLETION and (
354
+ model_name.startswith("gpt-5")
355
+ or model_name.startswith("gpt-4")
356
+ or model_name.startswith("gpt-3.5")
357
+ or model_name.startswith("gpt-35")
358
+ or model_name.startswith("o1-")
359
+ or model_name.startswith("o3-")
360
+ or model_name.startswith("o4-")
361
+ or ("finetuned" in model_name and "legacy" not in model_name)
362
+ ):
363
+ return model_name + "-completion"
364
+ if (
365
+ token_type == TokenType.PROMPT_CACHED
366
+ and (
367
+ model_name.startswith("gpt-5")
368
+ or model_name.startswith("gpt-4o")
369
+ or model_name.startswith("gpt-4.1")
370
+ or model_name.startswith("o1")
371
+ or model_name.startswith("o3")
372
+ or model_name.startswith("o4")
373
+ )
374
+ and not (model_name.startswith("gpt-4o-2024-05-13"))
375
+ ):
376
+ return model_name + "-cached"
377
+ else:
378
+ return model_name
379
+
380
+
381
+ def get_openai_token_cost_for_model(
382
+ model_name: str,
383
+ num_tokens: int,
384
+ is_completion: bool = False,
385
+ *,
386
+ token_type: TokenType = TokenType.PROMPT,
387
+ ) -> float:
388
+ """
389
+ Get the cost in USD for a given model and number of tokens.
390
+
391
+ Args:
392
+ model_name: Name of the model
393
+ num_tokens: Number of tokens.
394
+ is_completion: Whether the model is used for completion or not.
395
+ Defaults to False. Deprecated in favor of ``token_type``.
396
+ token_type: Token type. Defaults to ``TokenType.PROMPT``.
397
+
398
+ Returns:
399
+ Cost in USD.
400
+ """
401
+ if is_completion:
402
+ warn_deprecated(
403
+ since="0.3.13",
404
+ message=(
405
+ "is_completion is deprecated. Use token_type instead. Example:\n\n"
406
+ "from langchain_community.callbacks.openai_info import TokenType\n\n"
407
+ "get_openai_token_cost_for_model('gpt-4o', 10, token_type=TokenType.COMPLETION)\n" # noqa: E501
408
+ ),
409
+ removal="1.0",
410
+ )
411
+ token_type = TokenType.COMPLETION
412
+ model_name = standardize_model_name(model_name, token_type=token_type)
413
+ if model_name not in MODEL_COST_PER_1K_TOKENS:
414
+ raise ValueError(
415
+ f"Unknown model: {model_name}. Please provide a valid OpenAI model name."
416
+ "Known models are: " + ", ".join(MODEL_COST_PER_1K_TOKENS.keys())
417
+ )
418
+ return MODEL_COST_PER_1K_TOKENS[model_name] * (num_tokens / 1000)
419
+
420
+
421
+ class OpenAICallbackHandler(BaseCallbackHandler):
422
+ """Callback Handler that tracks OpenAI info."""
423
+
424
+ total_tokens: int = 0
425
+ prompt_tokens: int = 0
426
+ prompt_tokens_cached: int = 0
427
+ completion_tokens: int = 0
428
+ reasoning_tokens: int = 0
429
+ successful_requests: int = 0
430
+ total_cost: float = 0.0
431
+
432
+ def __init__(self) -> None:
433
+ super().__init__()
434
+ self._lock = threading.Lock()
435
+
436
+ def __repr__(self) -> str:
437
+ return (
438
+ f"Tokens Used: {self.total_tokens}\n"
439
+ f"\tPrompt Tokens: {self.prompt_tokens}\n"
440
+ f"\t\tPrompt Tokens Cached: {self.prompt_tokens_cached}\n"
441
+ f"\tCompletion Tokens: {self.completion_tokens}\n"
442
+ f"\t\tReasoning Tokens: {self.reasoning_tokens}\n"
443
+ f"Successful Requests: {self.successful_requests}\n"
444
+ f"Total Cost (USD): ${self.total_cost}"
445
+ )
446
+
447
+ @property
448
+ def always_verbose(self) -> bool:
449
+ """Whether to call verbose callbacks even if verbose is False."""
450
+ return True
451
+
452
+ def on_llm_start(
453
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
454
+ ) -> None:
455
+ """Print out the prompts."""
456
+ pass
457
+
458
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
459
+ """Print out the token."""
460
+ pass
461
+
462
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
463
+ """Collect token usage."""
464
+ # Check for usage_metadata (langchain-core >= 0.2.2)
465
+ try:
466
+ generation = response.generations[0][0]
467
+ except IndexError:
468
+ generation = None
469
+ if isinstance(generation, ChatGeneration):
470
+ try:
471
+ message = generation.message
472
+ if isinstance(message, AIMessage):
473
+ usage_metadata = message.usage_metadata
474
+ response_metadata = message.response_metadata
475
+ else:
476
+ usage_metadata = None
477
+ response_metadata = None
478
+ except AttributeError:
479
+ usage_metadata = None
480
+ response_metadata = None
481
+ else:
482
+ usage_metadata = None
483
+ response_metadata = None
484
+
485
+ prompt_tokens_cached = 0
486
+ reasoning_tokens = 0
487
+
488
+ if usage_metadata:
489
+ token_usage = {"total_tokens": usage_metadata["total_tokens"]}
490
+ completion_tokens = usage_metadata["output_tokens"]
491
+ prompt_tokens = usage_metadata["input_tokens"]
492
+ if response_model_name := (response_metadata or {}).get("model_name"):
493
+ model_name = standardize_model_name(response_model_name)
494
+ elif response.llm_output is None:
495
+ model_name = ""
496
+ else:
497
+ model_name = standardize_model_name(
498
+ response.llm_output.get("model_name", "")
499
+ )
500
+ if "cache_read" in usage_metadata.get("input_token_details", {}):
501
+ prompt_tokens_cached = usage_metadata["input_token_details"][
502
+ "cache_read"
503
+ ]
504
+ if "reasoning" in usage_metadata.get("output_token_details", {}):
505
+ reasoning_tokens = usage_metadata["output_token_details"]["reasoning"]
506
+ else:
507
+ if response.llm_output is None:
508
+ return None
509
+
510
+ if "token_usage" not in response.llm_output:
511
+ with self._lock:
512
+ self.successful_requests += 1
513
+ return None
514
+
515
+ # compute tokens and cost for this request
516
+ token_usage = response.llm_output["token_usage"]
517
+ completion_tokens = token_usage.get("completion_tokens", 0)
518
+ prompt_tokens = token_usage.get("prompt_tokens", 0)
519
+ model_name = standardize_model_name(
520
+ response.llm_output.get("model_name", "")
521
+ )
522
+
523
+ if model_name in MODEL_COST_PER_1K_TOKENS:
524
+ uncached_prompt_tokens = prompt_tokens - prompt_tokens_cached
525
+ uncached_prompt_cost = get_openai_token_cost_for_model(
526
+ model_name, uncached_prompt_tokens, token_type=TokenType.PROMPT
527
+ )
528
+ cached_prompt_cost = get_openai_token_cost_for_model(
529
+ model_name, prompt_tokens_cached, token_type=TokenType.PROMPT_CACHED
530
+ )
531
+ prompt_cost = uncached_prompt_cost + cached_prompt_cost
532
+ completion_cost = get_openai_token_cost_for_model(
533
+ model_name, completion_tokens, token_type=TokenType.COMPLETION
534
+ )
535
+ else:
536
+ completion_cost = 0
537
+ prompt_cost = 0
538
+
539
+ # update shared state behind lock
540
+ with self._lock:
541
+ self.total_cost += prompt_cost + completion_cost
542
+ self.total_tokens += token_usage.get("total_tokens", 0)
543
+ self.prompt_tokens += prompt_tokens
544
+ self.prompt_tokens_cached += prompt_tokens_cached
545
+ self.completion_tokens += completion_tokens
546
+ self.reasoning_tokens += reasoning_tokens
547
+ self.successful_requests += 1
548
+
549
+ def __copy__(self) -> "OpenAICallbackHandler":
550
+ """Return a copy of the callback handler."""
551
+ return self
552
+
553
+ def __deepcopy__(self, memo: Any) -> "OpenAICallbackHandler":
554
+ """Return a deep copy of the callback handler."""
555
+ return self
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/promptlayer_callback.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Callback handler for promptlayer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple
7
+ from uuid import UUID
8
+
9
+ from langchain_core.callbacks import BaseCallbackHandler
10
+ from langchain_core.messages import (
11
+ AIMessage,
12
+ BaseMessage,
13
+ ChatMessage,
14
+ HumanMessage,
15
+ SystemMessage,
16
+ )
17
+ from langchain_core.outputs import (
18
+ ChatGeneration,
19
+ LLMResult,
20
+ )
21
+
22
+ if TYPE_CHECKING:
23
+ import promptlayer
24
+
25
+
26
+ def _lazy_import_promptlayer() -> promptlayer:
27
+ """Lazy import promptlayer to avoid circular imports."""
28
+ try:
29
+ import promptlayer
30
+ except ImportError:
31
+ raise ImportError(
32
+ "The PromptLayerCallbackHandler requires the promptlayer package. "
33
+ " Please install it with `pip install promptlayer`."
34
+ )
35
+ return promptlayer
36
+
37
+
38
+ class PromptLayerCallbackHandler(BaseCallbackHandler):
39
+ """Callback handler for promptlayer."""
40
+
41
+ def __init__(
42
+ self,
43
+ pl_id_callback: Optional[Callable[..., Any]] = None,
44
+ pl_tags: Optional[List[str]] = None,
45
+ ) -> None:
46
+ """Initialize the PromptLayerCallbackHandler."""
47
+ _lazy_import_promptlayer()
48
+ self.pl_id_callback = pl_id_callback
49
+ self.pl_tags = pl_tags or []
50
+ self.runs: Dict[UUID, Dict[str, Any]] = {}
51
+
52
+ def on_chat_model_start(
53
+ self,
54
+ serialized: Dict[str, Any],
55
+ messages: List[List[BaseMessage]],
56
+ *,
57
+ run_id: UUID,
58
+ parent_run_id: Optional[UUID] = None,
59
+ tags: Optional[List[str]] = None,
60
+ **kwargs: Any,
61
+ ) -> Any:
62
+ self.runs[run_id] = {
63
+ "messages": [self._create_message_dicts(m)[0] for m in messages],
64
+ "invocation_params": kwargs.get("invocation_params", {}),
65
+ "name": ".".join(serialized["id"]),
66
+ "request_start_time": datetime.datetime.now().timestamp(),
67
+ "tags": tags,
68
+ }
69
+
70
+ def on_llm_start(
71
+ self,
72
+ serialized: Dict[str, Any],
73
+ prompts: List[str],
74
+ *,
75
+ run_id: UUID,
76
+ parent_run_id: Optional[UUID] = None,
77
+ tags: Optional[List[str]] = None,
78
+ **kwargs: Any,
79
+ ) -> Any:
80
+ self.runs[run_id] = {
81
+ "prompts": prompts,
82
+ "invocation_params": kwargs.get("invocation_params", {}),
83
+ "name": ".".join(serialized["id"]),
84
+ "request_start_time": datetime.datetime.now().timestamp(),
85
+ "tags": tags,
86
+ }
87
+
88
+ def on_llm_end(
89
+ self,
90
+ response: LLMResult,
91
+ *,
92
+ run_id: UUID,
93
+ parent_run_id: Optional[UUID] = None,
94
+ **kwargs: Any,
95
+ ) -> None:
96
+ from promptlayer.utils import get_api_key, promptlayer_api_request
97
+
98
+ run_info = self.runs.get(run_id, {})
99
+ if not run_info:
100
+ return
101
+ run_info["request_end_time"] = datetime.datetime.now().timestamp()
102
+ for i in range(len(response.generations)):
103
+ generation = response.generations[i][0]
104
+
105
+ resp = {
106
+ "text": generation.text,
107
+ "llm_output": response.llm_output,
108
+ }
109
+ model_params = run_info.get("invocation_params", {})
110
+ is_chat_model = run_info.get("messages", None) is not None
111
+ model_input = (
112
+ run_info.get("messages", [])[i]
113
+ if is_chat_model
114
+ else [run_info.get("prompts", [])[i]]
115
+ )
116
+ model_response = (
117
+ [self._convert_message_to_dict(generation.message)]
118
+ if is_chat_model and isinstance(generation, ChatGeneration)
119
+ else resp
120
+ )
121
+
122
+ pl_request_id = promptlayer_api_request(
123
+ run_info.get("name"),
124
+ "langchain",
125
+ model_input,
126
+ model_params,
127
+ self.pl_tags,
128
+ model_response,
129
+ run_info.get("request_start_time"),
130
+ run_info.get("request_end_time"),
131
+ get_api_key(),
132
+ return_pl_id=bool(self.pl_id_callback is not None),
133
+ metadata={
134
+ "_langchain_run_id": str(run_id),
135
+ "_langchain_parent_run_id": str(parent_run_id),
136
+ "_langchain_tags": str(run_info.get("tags", [])),
137
+ },
138
+ )
139
+
140
+ if self.pl_id_callback:
141
+ self.pl_id_callback(pl_request_id)
142
+
143
+ def _convert_message_to_dict(self, message: BaseMessage) -> Dict[str, Any]:
144
+ if isinstance(message, HumanMessage):
145
+ message_dict = {"role": "user", "content": message.content}
146
+ elif isinstance(message, AIMessage):
147
+ message_dict = {"role": "assistant", "content": message.content}
148
+ elif isinstance(message, SystemMessage):
149
+ message_dict = {"role": "system", "content": message.content}
150
+ elif isinstance(message, ChatMessage):
151
+ message_dict = {"role": message.role, "content": message.content}
152
+ else:
153
+ raise ValueError(f"Got unknown type {message}")
154
+ if "name" in message.additional_kwargs:
155
+ message_dict["name"] = message.additional_kwargs["name"]
156
+ return message_dict
157
+
158
+ def _create_message_dicts(
159
+ self, messages: List[BaseMessage]
160
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
161
+ params: Dict[str, Any] = {}
162
+ message_dicts = [self._convert_message_to_dict(m) for m in messages]
163
+ return message_dicts, params
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/sagemaker_callback.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import shutil
4
+ import tempfile
5
+ from copy import deepcopy
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from langchain_core.agents import AgentAction, AgentFinish
9
+ from langchain_core.callbacks import BaseCallbackHandler
10
+ from langchain_core.outputs import LLMResult
11
+
12
+ from langchain_community.callbacks.utils import (
13
+ flatten_dict,
14
+ )
15
+
16
+
17
+ def save_json(data: dict, file_path: str) -> None:
18
+ """Save dict to local file path.
19
+
20
+ Parameters:
21
+ data (dict): The dictionary to be saved.
22
+ file_path (str): Local file path.
23
+ """
24
+ with open(file_path, "w") as outfile:
25
+ json.dump(data, outfile)
26
+
27
+
28
+ class SageMakerCallbackHandler(BaseCallbackHandler):
29
+ """Callback Handler that logs prompt artifacts and metrics to SageMaker Experiments.
30
+
31
+ Parameters:
32
+ run (sagemaker.experiments.run.Run): Run object where the experiment is logged.
33
+ """
34
+
35
+ def __init__(self, run: Any) -> None:
36
+ """Initialize callback handler."""
37
+ super().__init__()
38
+
39
+ self.run = run
40
+
41
+ self.metrics = {
42
+ "step": 0,
43
+ "starts": 0,
44
+ "ends": 0,
45
+ "errors": 0,
46
+ "text_ctr": 0,
47
+ "chain_starts": 0,
48
+ "chain_ends": 0,
49
+ "llm_starts": 0,
50
+ "llm_ends": 0,
51
+ "llm_streams": 0,
52
+ "tool_starts": 0,
53
+ "tool_ends": 0,
54
+ "agent_ends": 0,
55
+ }
56
+
57
+ # Create a temporary directory
58
+ self.temp_dir = tempfile.mkdtemp()
59
+
60
+ def _reset(self) -> None:
61
+ for k, v in self.metrics.items():
62
+ self.metrics[k] = 0
63
+
64
+ def on_llm_start(
65
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
66
+ ) -> None:
67
+ """Run when LLM starts."""
68
+ self.metrics["step"] += 1
69
+ self.metrics["llm_starts"] += 1
70
+ self.metrics["starts"] += 1
71
+
72
+ llm_starts = self.metrics["llm_starts"]
73
+
74
+ resp: Dict[str, Any] = {}
75
+ resp.update({"action": "on_llm_start"})
76
+ resp.update(flatten_dict(serialized))
77
+ resp.update(self.metrics)
78
+
79
+ for idx, prompt in enumerate(prompts):
80
+ prompt_resp = deepcopy(resp)
81
+ prompt_resp["prompt"] = prompt
82
+ self.jsonf(
83
+ prompt_resp,
84
+ self.temp_dir,
85
+ f"llm_start_{llm_starts}_prompt_{idx}",
86
+ )
87
+
88
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
89
+ """Run when LLM generates a new token."""
90
+ self.metrics["step"] += 1
91
+ self.metrics["llm_streams"] += 1
92
+
93
+ llm_streams = self.metrics["llm_streams"]
94
+
95
+ resp: Dict[str, Any] = {}
96
+ resp.update({"action": "on_llm_new_token", "token": token})
97
+ resp.update(self.metrics)
98
+
99
+ self.jsonf(resp, self.temp_dir, f"llm_new_tokens_{llm_streams}")
100
+
101
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
102
+ """Run when LLM ends running."""
103
+ self.metrics["step"] += 1
104
+ self.metrics["llm_ends"] += 1
105
+ self.metrics["ends"] += 1
106
+
107
+ llm_ends = self.metrics["llm_ends"]
108
+
109
+ resp: Dict[str, Any] = {}
110
+ resp.update({"action": "on_llm_end"})
111
+ resp.update(flatten_dict(response.llm_output or {}))
112
+
113
+ resp.update(self.metrics)
114
+
115
+ for generations in response.generations:
116
+ for idx, generation in enumerate(generations):
117
+ generation_resp = deepcopy(resp)
118
+ generation_resp.update(flatten_dict(generation.dict()))
119
+
120
+ self.jsonf(
121
+ resp,
122
+ self.temp_dir,
123
+ f"llm_end_{llm_ends}_generation_{idx}",
124
+ )
125
+
126
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
127
+ """Run when LLM errors."""
128
+ self.metrics["step"] += 1
129
+ self.metrics["errors"] += 1
130
+
131
+ def on_chain_start(
132
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
133
+ ) -> None:
134
+ """Run when chain starts running."""
135
+ self.metrics["step"] += 1
136
+ self.metrics["chain_starts"] += 1
137
+ self.metrics["starts"] += 1
138
+
139
+ chain_starts = self.metrics["chain_starts"]
140
+
141
+ resp: Dict[str, Any] = {}
142
+ resp.update({"action": "on_chain_start"})
143
+ resp.update(flatten_dict(serialized))
144
+ resp.update(self.metrics)
145
+
146
+ chain_input = ",".join([f"{k}={v}" for k, v in inputs.items()])
147
+ input_resp = deepcopy(resp)
148
+ input_resp["inputs"] = chain_input
149
+
150
+ self.jsonf(input_resp, self.temp_dir, f"chain_start_{chain_starts}")
151
+
152
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
153
+ """Run when chain ends running."""
154
+ self.metrics["step"] += 1
155
+ self.metrics["chain_ends"] += 1
156
+ self.metrics["ends"] += 1
157
+
158
+ chain_ends = self.metrics["chain_ends"]
159
+
160
+ resp: Dict[str, Any] = {}
161
+ chain_output = ",".join([f"{k}={v}" for k, v in outputs.items()])
162
+ resp.update({"action": "on_chain_end", "outputs": chain_output})
163
+ resp.update(self.metrics)
164
+
165
+ self.jsonf(resp, self.temp_dir, f"chain_end_{chain_ends}")
166
+
167
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
168
+ """Run when chain errors."""
169
+ self.metrics["step"] += 1
170
+ self.metrics["errors"] += 1
171
+
172
+ def on_tool_start(
173
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
174
+ ) -> None:
175
+ """Run when tool starts running."""
176
+ self.metrics["step"] += 1
177
+ self.metrics["tool_starts"] += 1
178
+ self.metrics["starts"] += 1
179
+
180
+ tool_starts = self.metrics["tool_starts"]
181
+
182
+ resp: Dict[str, Any] = {}
183
+ resp.update({"action": "on_tool_start", "input_str": input_str})
184
+ resp.update(flatten_dict(serialized))
185
+ resp.update(self.metrics)
186
+
187
+ self.jsonf(resp, self.temp_dir, f"tool_start_{tool_starts}")
188
+
189
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
190
+ """Run when tool ends running."""
191
+ output = str(output)
192
+ self.metrics["step"] += 1
193
+ self.metrics["tool_ends"] += 1
194
+ self.metrics["ends"] += 1
195
+
196
+ tool_ends = self.metrics["tool_ends"]
197
+
198
+ resp: Dict[str, Any] = {}
199
+ resp.update({"action": "on_tool_end", "output": output})
200
+ resp.update(self.metrics)
201
+
202
+ self.jsonf(resp, self.temp_dir, f"tool_end_{tool_ends}")
203
+
204
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
205
+ """Run when tool errors."""
206
+ self.metrics["step"] += 1
207
+ self.metrics["errors"] += 1
208
+
209
+ def on_text(self, text: str, **kwargs: Any) -> None:
210
+ """
211
+ Run when agent is ending.
212
+ """
213
+ self.metrics["step"] += 1
214
+ self.metrics["text_ctr"] += 1
215
+
216
+ text_ctr = self.metrics["text_ctr"]
217
+
218
+ resp: Dict[str, Any] = {}
219
+ resp.update({"action": "on_text", "text": text})
220
+ resp.update(self.metrics)
221
+
222
+ self.jsonf(resp, self.temp_dir, f"on_text_{text_ctr}")
223
+
224
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
225
+ """Run when agent ends running."""
226
+ self.metrics["step"] += 1
227
+ self.metrics["agent_ends"] += 1
228
+ self.metrics["ends"] += 1
229
+
230
+ agent_ends = self.metrics["agent_ends"]
231
+ resp: Dict[str, Any] = {}
232
+ resp.update(
233
+ {
234
+ "action": "on_agent_finish",
235
+ "output": finish.return_values["output"],
236
+ "log": finish.log,
237
+ }
238
+ )
239
+ resp.update(self.metrics)
240
+
241
+ self.jsonf(resp, self.temp_dir, f"agent_finish_{agent_ends}")
242
+
243
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
244
+ """Run on agent action."""
245
+ self.metrics["step"] += 1
246
+ self.metrics["tool_starts"] += 1
247
+ self.metrics["starts"] += 1
248
+
249
+ tool_starts = self.metrics["tool_starts"]
250
+ resp: Dict[str, Any] = {}
251
+ resp.update(
252
+ {
253
+ "action": "on_agent_action",
254
+ "tool": action.tool,
255
+ "tool_input": action.tool_input,
256
+ "log": action.log,
257
+ }
258
+ )
259
+ resp.update(self.metrics)
260
+ self.jsonf(resp, self.temp_dir, f"agent_action_{tool_starts}")
261
+
262
+ def jsonf(
263
+ self,
264
+ data: Dict[str, Any],
265
+ data_dir: str,
266
+ filename: str,
267
+ is_output: Optional[bool] = True,
268
+ ) -> None:
269
+ """To log the input data as json file artifact."""
270
+ file_path = os.path.join(data_dir, f"{filename}.json")
271
+ save_json(data, file_path)
272
+ self.run.log_file(file_path, name=filename, is_output=is_output)
273
+
274
+ def flush_tracker(self) -> None:
275
+ """Reset the steps and delete the temporary local directory."""
276
+ self._reset()
277
+ shutil.rmtree(self.temp_dir)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/trubrics_callback.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Any, Dict, List, Optional
3
+ from uuid import UUID
4
+
5
+ from langchain_core.callbacks import BaseCallbackHandler
6
+ from langchain_core.messages import (
7
+ AIMessage,
8
+ BaseMessage,
9
+ ChatMessage,
10
+ FunctionMessage,
11
+ HumanMessage,
12
+ SystemMessage,
13
+ )
14
+ from langchain_core.outputs import LLMResult
15
+
16
+
17
+ def _convert_message_to_dict(message: BaseMessage) -> dict:
18
+ message_dict: Dict[str, Any]
19
+ if isinstance(message, ChatMessage):
20
+ message_dict = {"role": message.role, "content": message.content}
21
+ elif isinstance(message, HumanMessage):
22
+ message_dict = {"role": "user", "content": message.content}
23
+ elif isinstance(message, AIMessage):
24
+ message_dict = {"role": "assistant", "content": message.content}
25
+ if "function_call" in message.additional_kwargs:
26
+ message_dict["function_call"] = message.additional_kwargs["function_call"]
27
+ # If function call only, content is None not empty string
28
+ if message_dict["content"] == "":
29
+ message_dict["content"] = None
30
+ elif isinstance(message, SystemMessage):
31
+ message_dict = {"role": "system", "content": message.content}
32
+ elif isinstance(message, FunctionMessage):
33
+ message_dict = {
34
+ "role": "function",
35
+ "content": message.content,
36
+ "name": message.name,
37
+ }
38
+ else:
39
+ raise TypeError(f"Got unknown type {message}")
40
+ if "name" in message.additional_kwargs:
41
+ message_dict["name"] = message.additional_kwargs["name"]
42
+ return message_dict
43
+
44
+
45
+ class TrubricsCallbackHandler(BaseCallbackHandler):
46
+ """
47
+ Callback handler for Trubrics.
48
+
49
+ Args:
50
+ project: a trubrics project, default project is "default"
51
+ email: a trubrics account email, can equally be set in env variables
52
+ password: a trubrics account password, can equally be set in env variables
53
+ **kwargs: all other kwargs are parsed and set to trubrics prompt variables,
54
+ or added to the `metadata` dict
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ project: str = "default",
60
+ email: Optional[str] = None,
61
+ password: Optional[str] = None,
62
+ **kwargs: Any,
63
+ ) -> None:
64
+ super().__init__()
65
+ try:
66
+ from trubrics import Trubrics
67
+ except ImportError:
68
+ raise ImportError(
69
+ "The TrubricsCallbackHandler requires installation of "
70
+ "the trubrics package. "
71
+ "Please install it with `pip install trubrics`."
72
+ )
73
+
74
+ self.trubrics = Trubrics(
75
+ project=project,
76
+ email=email or os.environ["TRUBRICS_EMAIL"],
77
+ password=password or os.environ["TRUBRICS_PASSWORD"],
78
+ )
79
+ self.config_model: dict = {}
80
+ self.prompt: Optional[str] = None
81
+ self.messages: Optional[list] = None
82
+ self.trubrics_kwargs: Optional[dict] = kwargs if kwargs else None
83
+
84
+ def on_llm_start(
85
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
86
+ ) -> None:
87
+ self.prompt = prompts[0]
88
+
89
+ def on_chat_model_start(
90
+ self,
91
+ serialized: Dict[str, Any],
92
+ messages: List[List[BaseMessage]],
93
+ **kwargs: Any,
94
+ ) -> None:
95
+ self.messages = [_convert_message_to_dict(message) for message in messages[0]]
96
+ self.prompt = self.messages[-1]["content"]
97
+
98
+ def on_llm_end(self, response: LLMResult, run_id: UUID, **kwargs: Any) -> None:
99
+ tags = ["langchain"]
100
+ user_id = None
101
+ session_id = None
102
+ metadata: dict = {"langchain_run_id": run_id}
103
+ if self.messages:
104
+ metadata["messages"] = self.messages
105
+ if self.trubrics_kwargs:
106
+ if self.trubrics_kwargs.get("tags"):
107
+ tags.append(*self.trubrics_kwargs.pop("tags"))
108
+ user_id = self.trubrics_kwargs.pop("user_id", None)
109
+ session_id = self.trubrics_kwargs.pop("session_id", None)
110
+ metadata.update(self.trubrics_kwargs)
111
+
112
+ for generation in response.generations:
113
+ self.trubrics.log_prompt(
114
+ config_model={
115
+ "model": response.llm_output.get("model_name")
116
+ if response.llm_output
117
+ else "NA"
118
+ },
119
+ prompt=self.prompt,
120
+ generation=generation[0].text,
121
+ user_id=user_id,
122
+ session_id=session_id,
123
+ tags=tags,
124
+ metadata=metadata,
125
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/upstash_ratelimit_callback.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ratelimiting Handler to limit requests or tokens"""
2
+
3
+ import logging
4
+ from typing import Any, Dict, List, Literal, Optional
5
+
6
+ from langchain_core.callbacks import BaseCallbackHandler
7
+ from langchain_core.outputs import LLMResult
8
+
9
+ logger = logging.getLogger(__name__)
10
+ try:
11
+ from upstash_ratelimit import Ratelimit
12
+ except ImportError:
13
+ Ratelimit = None
14
+
15
+
16
+ class UpstashRatelimitError(Exception):
17
+ """
18
+ Upstash Ratelimit Error
19
+
20
+ Raised when the rate limit is reached in `UpstashRatelimitHandler`
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ message: str,
26
+ type: Literal["token", "request"],
27
+ limit: Optional[int] = None,
28
+ reset: Optional[float] = None,
29
+ ):
30
+ """
31
+ Args:
32
+ message (str): error message
33
+ type (str): The kind of the limit which was reached. One of
34
+ "token" or "request"
35
+ limit (Optional[int]): The limit which was reached. Passed when type
36
+ is request
37
+ reset (Optional[int]): unix timestamp in milliseconds when the limits
38
+ are reset. Passed when type is request
39
+ """
40
+ # Call the base class constructor with the parameters it needs
41
+ super().__init__(message)
42
+ self.type = type
43
+ self.limit = limit
44
+ self.reset = reset
45
+
46
+
47
+ class UpstashRatelimitHandler(BaseCallbackHandler):
48
+ """
49
+ Callback to handle rate limiting based on the number of requests
50
+ or the number of tokens in the input.
51
+
52
+ It uses Upstash Ratelimit to track the ratelimit which utilizes
53
+ Upstash Redis to track the state.
54
+
55
+ Should not be passed to the chain when initialising the chain.
56
+ This is because the handler has a state which should be fresh
57
+ every time invoke is called. Instead, initialise and pass a handler
58
+ every time you invoke.
59
+ """
60
+
61
+ raise_error: bool = True
62
+ _checked: bool = False
63
+
64
+ def __init__(
65
+ self,
66
+ identifier: str,
67
+ *,
68
+ token_ratelimit: Optional[Ratelimit] = None,
69
+ request_ratelimit: Optional[Ratelimit] = None,
70
+ include_output_tokens: bool = False,
71
+ ):
72
+ """
73
+ Creates UpstashRatelimitHandler. Must be passed an identifier to
74
+ ratelimit like a user id or an ip address.
75
+
76
+ Additionally, it must be passed at least one of token_ratelimit
77
+ or request_ratelimit parameters.
78
+
79
+ Args:
80
+ identifier Union[int, str]: the identifier
81
+ token_ratelimit Optional[Ratelimit]: Ratelimit to limit the
82
+ number of tokens. Only works with OpenAI models since only
83
+ these models provide the number of tokens as information
84
+ in their output.
85
+ request_ratelimit Optional[Ratelimit]: Ratelimit to limit the
86
+ number of requests
87
+ include_output_tokens bool: Whether to count output tokens when
88
+ rate limiting based on number of tokens. Only used when
89
+ `token_ratelimit` is passed. False by default.
90
+
91
+ Example:
92
+ .. code-block:: python
93
+
94
+ from upstash_redis import Redis
95
+ from upstash_ratelimit import Ratelimit, FixedWindow
96
+
97
+ redis = Redis.from_env()
98
+ ratelimit = Ratelimit(
99
+ redis=redis,
100
+ # fixed window to allow 10 requests every 10 seconds:
101
+ limiter=FixedWindow(max_requests=10, window=10),
102
+ )
103
+
104
+ user_id = "foo"
105
+ handler = UpstashRatelimitHandler(
106
+ identifier=user_id,
107
+ request_ratelimit=ratelimit
108
+ )
109
+
110
+ # Initialize a simple runnable to test
111
+ chain = RunnableLambda(str)
112
+
113
+ # pass handler as callback:
114
+ output = chain.invoke(
115
+ "input",
116
+ config={
117
+ "callbacks": [handler]
118
+ }
119
+ )
120
+
121
+ """
122
+ if not any([token_ratelimit, request_ratelimit]):
123
+ raise ValueError(
124
+ "You must pass at least one of input_token_ratelimit or"
125
+ " request_ratelimit parameters for handler to work."
126
+ )
127
+
128
+ self.identifier = identifier
129
+ self.token_ratelimit = token_ratelimit
130
+ self.request_ratelimit = request_ratelimit
131
+ self.include_output_tokens = include_output_tokens
132
+
133
+ def on_chain_start(
134
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
135
+ ) -> Any:
136
+ """
137
+ Run when chain starts running.
138
+
139
+ on_chain_start runs multiple times during a chain execution. To make
140
+ sure that it's only called once, we keep a bool state `_checked`. If
141
+ not `self._checked`, we call limit with `request_ratelimit` and raise
142
+ `UpstashRatelimitError` if the identifier is rate limited.
143
+ """
144
+ if self.request_ratelimit and not self._checked:
145
+ response = self.request_ratelimit.limit(self.identifier)
146
+ if not response.allowed:
147
+ raise UpstashRatelimitError(
148
+ "Request limit reached!", "request", response.limit, response.reset
149
+ )
150
+ self._checked = True
151
+
152
+ def on_llm_start(
153
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
154
+ ) -> None:
155
+ """
156
+ Run when LLM starts running
157
+ """
158
+ if self.token_ratelimit:
159
+ remaining = self.token_ratelimit.get_remaining(self.identifier)
160
+ if remaining <= 0:
161
+ raise UpstashRatelimitError("Token limit reached!", "token")
162
+
163
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
164
+ """
165
+ Run when LLM ends running
166
+
167
+ If the `include_output_tokens` is set to True, number of tokens
168
+ in LLM completion are counted for rate limiting
169
+ """
170
+ if self.token_ratelimit:
171
+ try:
172
+ llm_output = response.llm_output or {}
173
+ token_usage = llm_output["token_usage"]
174
+ token_count = (
175
+ token_usage["total_tokens"]
176
+ if self.include_output_tokens
177
+ else token_usage["prompt_tokens"]
178
+ )
179
+ except KeyError:
180
+ raise ValueError(
181
+ "LLM response doesn't include"
182
+ " `token_usage: {total_tokens: int, prompt_tokens: int}`"
183
+ " field. To use UpstashRatelimitHandler with token_ratelimit,"
184
+ " either use a model which returns token_usage (like "
185
+ " OpenAI models) or rate limit only with request_ratelimit."
186
+ )
187
+
188
+ # call limit to add the completion tokens to rate limit
189
+ # but don't raise exception since we already generated
190
+ # the tokens and would rather continue execution.
191
+ self.token_ratelimit.limit(self.identifier, rate=token_count)
192
+
193
+ def reset(self, identifier: Optional[str] = None) -> "UpstashRatelimitHandler":
194
+ """
195
+ Creates a new UpstashRatelimitHandler object with the same
196
+ ratelimit configurations but with a new identifier if it's
197
+ provided.
198
+
199
+ Also resets the state of the handler.
200
+ """
201
+ return UpstashRatelimitHandler(
202
+ identifier=identifier or self.identifier,
203
+ token_ratelimit=self.token_ratelimit,
204
+ request_ratelimit=self.request_ratelimit,
205
+ include_output_tokens=self.include_output_tokens,
206
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/uptrain_callback.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ UpTrain Callback Handler
3
+
4
+ UpTrain is an open-source platform to evaluate and improve LLM applications. It provides
5
+ grades for 20+ preconfigured checks (covering language, code, embedding use cases),
6
+ performs root cause analyses on instances of failure cases and provides guidance for
7
+ resolving them.
8
+
9
+ This module contains a callback handler for integrating UpTrain seamlessly into your
10
+ pipeline and facilitating diverse evaluations. The callback handler automates various
11
+ evaluations to assess the performance and effectiveness of the components within the
12
+ pipeline.
13
+
14
+ The evaluations conducted include:
15
+
16
+ 1. RAG:
17
+ - Context Relevance: Determines the relevance of the context extracted from the query
18
+ to the response.
19
+ - Factual Accuracy: Assesses if the Language Model (LLM) is providing accurate
20
+ information or hallucinating.
21
+ - Response Completeness: Checks if the response contains all the information
22
+ requested by the query.
23
+
24
+ 2. Multi Query Generation:
25
+ MultiQueryRetriever generates multiple variants of a question with similar meanings
26
+ to the original question. This evaluation includes previous assessments and adds:
27
+ - Multi Query Accuracy: Ensures that the multi-queries generated convey the same
28
+ meaning as the original query.
29
+
30
+ 3. Context Compression and Reranking:
31
+ Re-ranking involves reordering nodes based on relevance to the query and selecting
32
+ top n nodes.
33
+ Due to the potential reduction in the number of nodes after re-ranking, the following
34
+ evaluations
35
+ are performed in addition to the RAG evaluations:
36
+ - Context Reranking: Determines if the order of re-ranked nodes is more relevant to
37
+ the query than the original order.
38
+ - Context Conciseness: Examines whether the reduced number of nodes still provides
39
+ all the required information.
40
+
41
+ These evaluations collectively ensure the robustness and effectiveness of the RAG query
42
+ engine, MultiQueryRetriever, and the re-ranking process within the pipeline.
43
+
44
+ Useful links:
45
+ Github: https://github.com/uptrain-ai/uptrain
46
+ Website: https://uptrain.ai/
47
+ Docs: https://docs.uptrain.ai/getting-started/introduction
48
+
49
+ """
50
+
51
+ import logging
52
+ import sys
53
+ from collections import defaultdict
54
+ from typing import (
55
+ Any,
56
+ DefaultDict,
57
+ Dict,
58
+ List,
59
+ Optional,
60
+ Sequence,
61
+ Set,
62
+ )
63
+ from uuid import UUID
64
+
65
+ from langchain_core.callbacks.base import BaseCallbackHandler
66
+ from langchain_core.documents import Document
67
+ from langchain_core.outputs import LLMResult
68
+ from langchain_core.utils import guard_import
69
+
70
+ logger = logging.getLogger(__name__)
71
+ handler = logging.StreamHandler(sys.stdout)
72
+ formatter = logging.Formatter("%(message)s")
73
+ handler.setFormatter(formatter)
74
+ logger.addHandler(handler)
75
+
76
+
77
+ def import_uptrain() -> Any:
78
+ """Import the `uptrain` package."""
79
+ return guard_import("uptrain")
80
+
81
+
82
+ class UpTrainDataSchema:
83
+ """The UpTrain data schema for tracking evaluation results.
84
+
85
+ Args:
86
+ project_name (str): The project name to be shown in UpTrain dashboard.
87
+
88
+ Attributes:
89
+ project_name (str): The project name to be shown in UpTrain dashboard.
90
+ uptrain_results (DefaultDict[str, Any]): Dictionary to store evaluation results.
91
+ eval_types (Set[str]): Set to store the types of evaluations.
92
+ query (str): Query for the RAG evaluation.
93
+ context (str): Context for the RAG evaluation.
94
+ response (str): Response for the RAG evaluation.
95
+ old_context (List[str]): Old context nodes for Context Conciseness evaluation.
96
+ new_context (List[str]): New context nodes for Context Conciseness evaluation.
97
+ context_conciseness_run_id (str): Run ID for Context Conciseness evaluation.
98
+ multi_queries (List[str]): List of multi queries for Multi Query evaluation.
99
+ multi_query_run_id (str): Run ID for Multi Query evaluation.
100
+ multi_query_daugher_run_id (str): Run ID for Multi Query daughter evaluation.
101
+
102
+ """
103
+
104
+ def __init__(self, project_name: str) -> None:
105
+ """Initialize the UpTrain data schema."""
106
+ # For tracking project name and results
107
+ self.project_name: str = project_name
108
+ self.uptrain_results: DefaultDict[str, Any] = defaultdict(list)
109
+
110
+ # For tracking event types
111
+ self.eval_types: Set[str] = set()
112
+
113
+ ## RAG
114
+ self.query: str = ""
115
+ self.context: str = ""
116
+ self.response: str = ""
117
+
118
+ ## CONTEXT CONCISENESS
119
+ self.old_context: List[str] = []
120
+ self.new_context: List[str] = []
121
+ self.context_conciseness_run_id: UUID = UUID(int=0)
122
+
123
+ # MULTI QUERY
124
+ self.multi_queries: List[str] = []
125
+ self.multi_query_run_id: UUID = UUID(int=0)
126
+ self.multi_query_daugher_run_id: UUID = UUID(int=0)
127
+
128
+
129
+ class UpTrainCallbackHandler(BaseCallbackHandler):
130
+ """Callback Handler that logs evaluation results to uptrain and the console.
131
+
132
+ Args:
133
+ project_name (str): The project name to be shown in UpTrain dashboard.
134
+ key_type (str): Type of key to use. Must be 'uptrain' or 'openai'.
135
+ api_key (str): API key for the UpTrain or OpenAI API.
136
+ (This key is required to perform evaluations using GPT.)
137
+
138
+ Raises:
139
+ ValueError: If the key type is invalid.
140
+ ImportError: If the `uptrain` package is not installed.
141
+
142
+ """
143
+
144
+ def __init__(
145
+ self,
146
+ *,
147
+ project_name: str = "langchain",
148
+ key_type: str = "openai",
149
+ api_key: str = "sk-****************", # The API key to use for evaluation
150
+ model: str = "gpt-3.5-turbo", # The model to use for evaluation
151
+ log_results: bool = True,
152
+ ) -> None:
153
+ """Initializes the `UpTrainCallbackHandler`."""
154
+ super().__init__()
155
+
156
+ uptrain = import_uptrain()
157
+
158
+ self.log_results = log_results
159
+
160
+ # Set uptrain variables
161
+ self.schema = UpTrainDataSchema(project_name=project_name)
162
+ self.first_score_printed_flag = False
163
+
164
+ if key_type == "uptrain":
165
+ settings = uptrain.Settings(uptrain_access_token=api_key, model=model)
166
+ self.uptrain_client = uptrain.APIClient(settings=settings)
167
+ elif key_type == "openai":
168
+ settings = uptrain.Settings(
169
+ openai_api_key=api_key, evaluate_locally=True, model=model
170
+ )
171
+ self.uptrain_client = uptrain.EvalLLM(settings=settings)
172
+ else:
173
+ raise ValueError("Invalid key type: Must be 'uptrain' or 'openai'")
174
+
175
+ def uptrain_evaluate(
176
+ self,
177
+ evaluation_name: str,
178
+ data: List[Dict[str, Any]],
179
+ checks: List[str],
180
+ ) -> None:
181
+ """Run an evaluation on the UpTrain server using UpTrain client."""
182
+ if self.uptrain_client.__class__.__name__ == "APIClient":
183
+ uptrain_result = self.uptrain_client.log_and_evaluate(
184
+ project_name=self.schema.project_name,
185
+ evaluation_name=evaluation_name,
186
+ data=data,
187
+ checks=checks,
188
+ )
189
+ else:
190
+ uptrain_result = self.uptrain_client.evaluate(
191
+ project_name=self.schema.project_name,
192
+ evaluation_name=evaluation_name,
193
+ data=data,
194
+ checks=checks,
195
+ )
196
+ self.schema.uptrain_results[self.schema.project_name].append(uptrain_result)
197
+
198
+ score_name_map = {
199
+ "score_context_relevance": "Context Relevance Score",
200
+ "score_factual_accuracy": "Factual Accuracy Score",
201
+ "score_response_completeness": "Response Completeness Score",
202
+ "score_sub_query_completeness": "Sub Query Completeness Score",
203
+ "score_context_reranking": "Context Reranking Score",
204
+ "score_context_conciseness": "Context Conciseness Score",
205
+ "score_multi_query_accuracy": "Multi Query Accuracy Score",
206
+ }
207
+
208
+ if self.log_results:
209
+ # Set logger level to INFO to print the evaluation results
210
+ logger.setLevel(logging.INFO)
211
+
212
+ for row in uptrain_result:
213
+ columns = list(row.keys())
214
+ for column in columns:
215
+ if column == "question":
216
+ logger.info(f"\nQuestion: {row[column]}")
217
+ self.first_score_printed_flag = False
218
+ elif column == "response":
219
+ logger.info(f"Response: {row[column]}")
220
+ self.first_score_printed_flag = False
221
+ elif column == "variants":
222
+ logger.info("Multi Queries:")
223
+ for variant in row[column]:
224
+ logger.info(f" - {variant}")
225
+ self.first_score_printed_flag = False
226
+ elif column.startswith("score"):
227
+ if not self.first_score_printed_flag:
228
+ logger.info("")
229
+ self.first_score_printed_flag = True
230
+ if column in score_name_map:
231
+ logger.info(f"{score_name_map[column]}: {row[column]}")
232
+ else:
233
+ logger.info(f"{column}: {row[column]}")
234
+
235
+ if self.log_results:
236
+ # Set logger level back to WARNING
237
+ # (We are doing this to avoid printing the logs from HTTP requests)
238
+ logger.setLevel(logging.WARNING)
239
+
240
+ def on_llm_end(
241
+ self,
242
+ response: LLMResult,
243
+ *,
244
+ run_id: UUID,
245
+ parent_run_id: Optional[UUID] = None,
246
+ **kwargs: Any,
247
+ ) -> None:
248
+ """Log records to uptrain when an LLM ends."""
249
+ uptrain = import_uptrain()
250
+ self.schema.response = response.generations[0][0].text
251
+ if (
252
+ "qa_rag" in self.schema.eval_types
253
+ and parent_run_id != self.schema.multi_query_daugher_run_id
254
+ ):
255
+ data = [
256
+ {
257
+ "question": self.schema.query,
258
+ "context": self.schema.context,
259
+ "response": self.schema.response,
260
+ }
261
+ ]
262
+
263
+ self.uptrain_evaluate(
264
+ evaluation_name="rag",
265
+ data=data,
266
+ checks=[
267
+ uptrain.Evals.CONTEXT_RELEVANCE,
268
+ uptrain.Evals.FACTUAL_ACCURACY,
269
+ uptrain.Evals.RESPONSE_COMPLETENESS,
270
+ ],
271
+ )
272
+
273
+ def on_chain_start(
274
+ self,
275
+ serialized: Dict[str, Any],
276
+ inputs: Dict[str, Any],
277
+ *,
278
+ run_id: UUID,
279
+ tags: Optional[List[str]] = None,
280
+ parent_run_id: Optional[UUID] = None,
281
+ metadata: Optional[Dict[str, Any]] = None,
282
+ run_type: Optional[str] = None,
283
+ name: Optional[str] = None,
284
+ **kwargs: Any,
285
+ ) -> None:
286
+ """Do nothing when chain starts"""
287
+ if parent_run_id == self.schema.multi_query_run_id:
288
+ self.schema.multi_query_daugher_run_id = run_id
289
+ if isinstance(inputs, dict) and set(inputs.keys()) == {"context", "question"}:
290
+ self.schema.eval_types.add("qa_rag")
291
+
292
+ context = ""
293
+ if isinstance(inputs["context"], Document):
294
+ context = inputs["context"].page_content
295
+ elif isinstance(inputs["context"], list):
296
+ for doc in inputs["context"]:
297
+ context += doc.page_content + "\n"
298
+ elif isinstance(inputs["context"], str):
299
+ context = inputs["context"]
300
+ self.schema.context = context
301
+ self.schema.query = inputs["question"]
302
+ pass
303
+
304
+ def on_retriever_start(
305
+ self,
306
+ serialized: Dict[str, Any],
307
+ query: str,
308
+ *,
309
+ run_id: UUID,
310
+ parent_run_id: Optional[UUID] = None,
311
+ tags: Optional[List[str]] = None,
312
+ metadata: Optional[Dict[str, Any]] = None,
313
+ **kwargs: Any,
314
+ ) -> None:
315
+ if "contextual_compression" in serialized["id"]:
316
+ self.schema.eval_types.add("contextual_compression")
317
+ self.schema.query = query
318
+ self.schema.context_conciseness_run_id = run_id
319
+
320
+ if "multi_query" in serialized["id"]:
321
+ self.schema.eval_types.add("multi_query")
322
+ self.schema.multi_query_run_id = run_id
323
+ self.schema.query = query
324
+ elif "multi_query" in self.schema.eval_types:
325
+ self.schema.multi_queries.append(query)
326
+
327
+ def on_retriever_end(
328
+ self,
329
+ documents: Sequence[Document],
330
+ *,
331
+ run_id: UUID,
332
+ parent_run_id: Optional[UUID] = None,
333
+ **kwargs: Any,
334
+ ) -> Any:
335
+ """Run when Retriever ends running."""
336
+ uptrain = import_uptrain()
337
+ if run_id == self.schema.multi_query_run_id:
338
+ data = [
339
+ {
340
+ "question": self.schema.query,
341
+ "variants": self.schema.multi_queries,
342
+ }
343
+ ]
344
+
345
+ self.uptrain_evaluate(
346
+ evaluation_name="multi_query",
347
+ data=data,
348
+ checks=[uptrain.Evals.MULTI_QUERY_ACCURACY],
349
+ )
350
+ if "contextual_compression" in self.schema.eval_types:
351
+ if parent_run_id == self.schema.context_conciseness_run_id:
352
+ for doc in documents:
353
+ self.schema.old_context.append(doc.page_content)
354
+ elif run_id == self.schema.context_conciseness_run_id:
355
+ for doc in documents:
356
+ self.schema.new_context.append(doc.page_content)
357
+ context = "\n".join(
358
+ [
359
+ f"{index}. {string}"
360
+ for index, string in enumerate(self.schema.old_context, start=1)
361
+ ]
362
+ )
363
+ reranked_context = "\n".join(
364
+ [
365
+ f"{index}. {string}"
366
+ for index, string in enumerate(self.schema.new_context, start=1)
367
+ ]
368
+ )
369
+ data = [
370
+ {
371
+ "question": self.schema.query,
372
+ "context": context,
373
+ "concise_context": reranked_context,
374
+ "reranked_context": reranked_context,
375
+ }
376
+ ]
377
+ self.uptrain_evaluate(
378
+ evaluation_name="context_reranking",
379
+ data=data,
380
+ checks=[
381
+ uptrain.Evals.CONTEXT_CONCISENESS,
382
+ uptrain.Evals.CONTEXT_RERANKING,
383
+ ],
384
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/utils.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ from pathlib import Path
3
+ from typing import Any, Dict, Iterable, Tuple, Union
4
+
5
+ from langchain_core.utils import guard_import
6
+
7
+
8
+ def import_spacy() -> Any:
9
+ """Import the spacy python package and raise an error if it is not installed."""
10
+ return guard_import("spacy")
11
+
12
+
13
+ def import_pandas() -> Any:
14
+ """Import the pandas python package and raise an error if it is not installed."""
15
+ return guard_import("pandas")
16
+
17
+
18
+ def import_textstat() -> Any:
19
+ """Import the textstat python package and raise an error if it is not installed."""
20
+ return guard_import("textstat")
21
+
22
+
23
+ def _flatten_dict(
24
+ nested_dict: Dict[str, Any], parent_key: str = "", sep: str = "_"
25
+ ) -> Iterable[Tuple[str, Any]]:
26
+ """
27
+ Generator that yields flattened items from a nested dictionary for a flat dict.
28
+
29
+ Parameters:
30
+ nested_dict (dict): The nested dictionary to flatten.
31
+ parent_key (str): The prefix to prepend to the keys of the flattened dict.
32
+ sep (str): The separator to use between the parent key and the key of the
33
+ flattened dictionary.
34
+
35
+ Yields:
36
+ (str, any): A key-value pair from the flattened dictionary.
37
+ """
38
+ for key, value in nested_dict.items():
39
+ new_key = parent_key + sep + key if parent_key else key
40
+ if isinstance(value, dict):
41
+ yield from _flatten_dict(value, new_key, sep)
42
+ else:
43
+ yield new_key, value
44
+
45
+
46
+ def flatten_dict(
47
+ nested_dict: Dict[str, Any], parent_key: str = "", sep: str = "_"
48
+ ) -> Dict[str, Any]:
49
+ """Flatten a nested dictionary into a flat dictionary.
50
+
51
+ Parameters:
52
+ nested_dict (dict): The nested dictionary to flatten.
53
+ parent_key (str): The prefix to prepend to the keys of the flattened dict.
54
+ sep (str): The separator to use between the parent key and the key of the
55
+ flattened dictionary.
56
+
57
+ Returns:
58
+ (dict): A flat dictionary.
59
+
60
+ """
61
+ flat_dict = {k: v for k, v in _flatten_dict(nested_dict, parent_key, sep)}
62
+ return flat_dict
63
+
64
+
65
+ def hash_string(s: str) -> str:
66
+ """Hash a string using sha1.
67
+
68
+ Parameters:
69
+ s (str): The string to hash.
70
+
71
+ Returns:
72
+ (str): The hashed string.
73
+ """
74
+ return hashlib.sha1(s.encode("utf-8")).hexdigest()
75
+
76
+
77
+ def load_json(json_path: Union[str, Path]) -> str:
78
+ """Load json file to a string.
79
+
80
+ Parameters:
81
+ json_path (str): The path to the json file.
82
+
83
+ Returns:
84
+ (str): The string representation of the json file.
85
+ """
86
+ with open(json_path, "r") as f:
87
+ data = f.read()
88
+ return data
89
+
90
+
91
+ class BaseMetadataCallbackHandler:
92
+ """Handle the metadata and associated function states for callbacks.
93
+
94
+ Attributes:
95
+ step (int): The current step.
96
+ starts (int): The number of times the start method has been called.
97
+ ends (int): The number of times the end method has been called.
98
+ errors (int): The number of times the error method has been called.
99
+ text_ctr (int): The number of times the text method has been called.
100
+ ignore_llm_ (bool): Whether to ignore llm callbacks.
101
+ ignore_chain_ (bool): Whether to ignore chain callbacks.
102
+ ignore_agent_ (bool): Whether to ignore agent callbacks.
103
+ ignore_retriever_ (bool): Whether to ignore retriever callbacks.
104
+ always_verbose_ (bool): Whether to always be verbose.
105
+ chain_starts (int): The number of times the chain start method has been called.
106
+ chain_ends (int): The number of times the chain end method has been called.
107
+ llm_starts (int): The number of times the llm start method has been called.
108
+ llm_ends (int): The number of times the llm end method has been called.
109
+ llm_streams (int): The number of times the text method has been called.
110
+ tool_starts (int): The number of times the tool start method has been called.
111
+ tool_ends (int): The number of times the tool end method has been called.
112
+ agent_ends (int): The number of times the agent end method has been called.
113
+ on_llm_start_records (list): A list of records of the on_llm_start method.
114
+ on_llm_token_records (list): A list of records of the on_llm_token method.
115
+ on_llm_end_records (list): A list of records of the on_llm_end method.
116
+ on_chain_start_records (list): A list of records of the on_chain_start method.
117
+ on_chain_end_records (list): A list of records of the on_chain_end method.
118
+ on_tool_start_records (list): A list of records of the on_tool_start method.
119
+ on_tool_end_records (list): A list of records of the on_tool_end method.
120
+ on_agent_finish_records (list): A list of records of the on_agent_end method.
121
+ """
122
+
123
+ def __init__(self) -> None:
124
+ self.step = 0
125
+
126
+ self.starts = 0
127
+ self.ends = 0
128
+ self.errors = 0
129
+ self.text_ctr = 0
130
+
131
+ self.ignore_llm_ = False
132
+ self.ignore_chain_ = False
133
+ self.ignore_agent_ = False
134
+ self.ignore_retriever_ = False
135
+ self.always_verbose_ = False
136
+
137
+ self.chain_starts = 0
138
+ self.chain_ends = 0
139
+
140
+ self.llm_starts = 0
141
+ self.llm_ends = 0
142
+ self.llm_streams = 0
143
+
144
+ self.tool_starts = 0
145
+ self.tool_ends = 0
146
+
147
+ self.agent_ends = 0
148
+
149
+ self.on_llm_start_records: list = []
150
+ self.on_llm_token_records: list = []
151
+ self.on_llm_end_records: list = []
152
+
153
+ self.on_chain_start_records: list = []
154
+ self.on_chain_end_records: list = []
155
+
156
+ self.on_tool_start_records: list = []
157
+ self.on_tool_end_records: list = []
158
+
159
+ self.on_text_records: list = []
160
+ self.on_agent_finish_records: list = []
161
+ self.on_agent_action_records: list = []
162
+
163
+ @property
164
+ def always_verbose(self) -> bool:
165
+ """Whether to call verbose callbacks even if verbose is False."""
166
+ return self.always_verbose_
167
+
168
+ @property
169
+ def ignore_llm(self) -> bool:
170
+ """Whether to ignore LLM callbacks."""
171
+ return self.ignore_llm_
172
+
173
+ @property
174
+ def ignore_chain(self) -> bool:
175
+ """Whether to ignore chain callbacks."""
176
+ return self.ignore_chain_
177
+
178
+ @property
179
+ def ignore_agent(self) -> bool:
180
+ """Whether to ignore agent callbacks."""
181
+ return self.ignore_agent_
182
+
183
+ def get_custom_callback_meta(self) -> Dict[str, Any]:
184
+ return {
185
+ "step": self.step,
186
+ "starts": self.starts,
187
+ "ends": self.ends,
188
+ "errors": self.errors,
189
+ "text_ctr": self.text_ctr,
190
+ "chain_starts": self.chain_starts,
191
+ "chain_ends": self.chain_ends,
192
+ "llm_starts": self.llm_starts,
193
+ "llm_ends": self.llm_ends,
194
+ "llm_streams": self.llm_streams,
195
+ "tool_starts": self.tool_starts,
196
+ "tool_ends": self.tool_ends,
197
+ "agent_ends": self.agent_ends,
198
+ }
199
+
200
+ def reset_callback_meta(self) -> None:
201
+ """Reset the callback metadata."""
202
+ self.step = 0
203
+
204
+ self.starts = 0
205
+ self.ends = 0
206
+ self.errors = 0
207
+ self.text_ctr = 0
208
+
209
+ self.ignore_llm_ = False
210
+ self.ignore_chain_ = False
211
+ self.ignore_agent_ = False
212
+ self.always_verbose_ = False
213
+
214
+ self.chain_starts = 0
215
+ self.chain_ends = 0
216
+
217
+ self.llm_starts = 0
218
+ self.llm_ends = 0
219
+ self.llm_streams = 0
220
+
221
+ self.tool_starts = 0
222
+ self.tool_ends = 0
223
+
224
+ self.agent_ends = 0
225
+
226
+ self.on_llm_start_records = []
227
+ self.on_llm_token_records = []
228
+ self.on_llm_end_records = []
229
+
230
+ self.on_chain_start_records = []
231
+ self.on_chain_end_records = []
232
+
233
+ self.on_tool_start_records = []
234
+ self.on_tool_end_records = []
235
+
236
+ self.on_text_records = []
237
+ self.on_agent_finish_records = []
238
+ self.on_agent_action_records = []
239
+ return None
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/wandb_callback.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import tempfile
3
+ from copy import deepcopy
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List, Optional, Sequence, Union
6
+
7
+ from langchain_core._api import warn_deprecated
8
+ from langchain_core.agents import AgentAction, AgentFinish
9
+ from langchain_core.callbacks import BaseCallbackHandler
10
+ from langchain_core.outputs import LLMResult
11
+ from langchain_core.utils import guard_import
12
+
13
+ from langchain_community.callbacks.utils import (
14
+ BaseMetadataCallbackHandler,
15
+ flatten_dict,
16
+ hash_string,
17
+ import_pandas,
18
+ import_spacy,
19
+ import_textstat,
20
+ )
21
+
22
+
23
+ def import_wandb() -> Any:
24
+ """Import the wandb python package and raise an error if it is not installed."""
25
+ return guard_import("wandb")
26
+
27
+
28
+ def load_json_to_dict(json_path: Union[str, Path]) -> dict:
29
+ """Load json file to a dictionary.
30
+
31
+ Parameters:
32
+ json_path (str): The path to the json file.
33
+
34
+ Returns:
35
+ (dict): The dictionary representation of the json file.
36
+ """
37
+ with open(json_path, "r") as f:
38
+ data = json.load(f)
39
+ return data
40
+
41
+
42
+ def analyze_text(
43
+ text: str,
44
+ complexity_metrics: bool = True,
45
+ visualize: bool = True,
46
+ nlp: Any = None,
47
+ output_dir: Optional[Union[str, Path]] = None,
48
+ ) -> dict:
49
+ """Analyze text using textstat and spacy.
50
+
51
+ Parameters:
52
+ text (str): The text to analyze.
53
+ complexity_metrics (bool): Whether to compute complexity metrics.
54
+ visualize (bool): Whether to visualize the text.
55
+ nlp (spacy.lang): The spacy language model to use for visualization.
56
+ output_dir (str): The directory to save the visualization files to.
57
+
58
+ Returns:
59
+ `dict` containing the complexity metrics and visualization
60
+ files serialized in a wandb.Html element.
61
+ """
62
+ resp = {}
63
+ textstat = import_textstat()
64
+ wandb = import_wandb()
65
+ spacy = import_spacy()
66
+ if complexity_metrics:
67
+ text_complexity_metrics = {
68
+ "flesch_reading_ease": textstat.flesch_reading_ease(text),
69
+ "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
70
+ "smog_index": textstat.smog_index(text),
71
+ "coleman_liau_index": textstat.coleman_liau_index(text),
72
+ "automated_readability_index": textstat.automated_readability_index(text),
73
+ "dale_chall_readability_score": textstat.dale_chall_readability_score(text),
74
+ "difficult_words": textstat.difficult_words(text),
75
+ "linsear_write_formula": textstat.linsear_write_formula(text),
76
+ "gunning_fog": textstat.gunning_fog(text),
77
+ "text_standard": textstat.text_standard(text),
78
+ "fernandez_huerta": textstat.fernandez_huerta(text),
79
+ "szigriszt_pazos": textstat.szigriszt_pazos(text),
80
+ "gutierrez_polini": textstat.gutierrez_polini(text),
81
+ "crawford": textstat.crawford(text),
82
+ "gulpease_index": textstat.gulpease_index(text),
83
+ "osman": textstat.osman(text),
84
+ }
85
+ resp.update(text_complexity_metrics)
86
+
87
+ if visualize and nlp and output_dir is not None:
88
+ doc = nlp(text)
89
+
90
+ dep_out = spacy.displacy.render(doc, style="dep", jupyter=False, page=True)
91
+ dep_output_path = Path(output_dir, hash_string(f"dep-{text}") + ".html")
92
+ dep_output_path.open("w", encoding="utf-8").write(dep_out)
93
+
94
+ ent_out = spacy.displacy.render(doc, style="ent", jupyter=False, page=True)
95
+ ent_output_path = Path(output_dir, hash_string(f"ent-{text}") + ".html")
96
+ ent_output_path.open("w", encoding="utf-8").write(ent_out)
97
+
98
+ text_visualizations = {
99
+ "dependency_tree": wandb.Html(str(dep_output_path)),
100
+ "entities": wandb.Html(str(ent_output_path)),
101
+ }
102
+ resp.update(text_visualizations)
103
+
104
+ return resp
105
+
106
+
107
+ def construct_html_from_prompt_and_generation(prompt: str, generation: str) -> Any:
108
+ """Construct an html element from a prompt and a generation.
109
+
110
+ Parameters:
111
+ prompt (str): The prompt.
112
+ generation (str): The generation.
113
+
114
+ Returns:
115
+ (wandb.Html): The html element."""
116
+ wandb = import_wandb()
117
+ formatted_prompt = prompt.replace("\n", "<br>")
118
+ formatted_generation = generation.replace("\n", "<br>")
119
+
120
+ return wandb.Html(
121
+ f"""
122
+ <p style="color:black;">{formatted_prompt}:</p>
123
+ <blockquote>
124
+ <p style="color:green;">
125
+ {formatted_generation}
126
+ </p>
127
+ </blockquote>
128
+ """,
129
+ inject=False,
130
+ )
131
+
132
+
133
+ class WandbCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
134
+ """Callback Handler that logs to Weights and Biases.
135
+
136
+ Parameters:
137
+ job_type (str): The type of job.
138
+ project (str): The project to log to.
139
+ entity (str): The entity to log to.
140
+ tags (list): The tags to log.
141
+ group (str): The group to log to.
142
+ name (str): The name of the run.
143
+ notes (str): The notes to log.
144
+ visualize (bool): Whether to visualize the run.
145
+ complexity_metrics (bool): Whether to log complexity metrics.
146
+ stream_logs (bool): Whether to stream callback actions to W&B
147
+
148
+ This handler will utilize the associated callback method called and formats
149
+ the input of each callback function with metadata regarding the state of LLM run,
150
+ and adds the response to the list of records for both the {method}_records and
151
+ action. It then logs the response using the run.log() method to Weights and Biases.
152
+ """
153
+
154
+ def __init__(
155
+ self,
156
+ job_type: Optional[str] = None,
157
+ project: Optional[str] = "langchain_callback_demo",
158
+ entity: Optional[str] = None,
159
+ tags: Optional[Sequence] = None,
160
+ group: Optional[str] = None,
161
+ name: Optional[str] = None,
162
+ notes: Optional[str] = None,
163
+ visualize: bool = False,
164
+ complexity_metrics: bool = False,
165
+ stream_logs: bool = False,
166
+ ) -> None:
167
+ """Initialize callback handler."""
168
+
169
+ wandb = import_wandb()
170
+ import_pandas()
171
+ import_textstat()
172
+ spacy = import_spacy()
173
+ super().__init__()
174
+
175
+ self.job_type = job_type
176
+ self.project = project
177
+ self.entity = entity
178
+ self.tags = tags
179
+ self.group = group
180
+ self.name = name
181
+ self.notes = notes
182
+ self.visualize = visualize
183
+ self.complexity_metrics = complexity_metrics
184
+ self.stream_logs = stream_logs
185
+
186
+ self.temp_dir = tempfile.TemporaryDirectory()
187
+ self.run = wandb.init(
188
+ job_type=self.job_type,
189
+ project=self.project,
190
+ entity=self.entity,
191
+ tags=self.tags,
192
+ group=self.group,
193
+ name=self.name,
194
+ notes=self.notes,
195
+ )
196
+ warning = (
197
+ "DEPRECATION: The `WandbCallbackHandler` will soon be deprecated in favor "
198
+ "of the `WandbTracer`. Please update your code to use the `WandbTracer` "
199
+ "instead."
200
+ )
201
+ wandb.termwarn(
202
+ warning,
203
+ repeat=False,
204
+ )
205
+ self.callback_columns: list = []
206
+ self.action_records: list = []
207
+ self.complexity_metrics = complexity_metrics
208
+ self.visualize = visualize
209
+ self.nlp = spacy.load("en_core_web_sm")
210
+ warn_deprecated(
211
+ "0.3.8",
212
+ pending=False,
213
+ message=(
214
+ "Please use the WeaveTracer instead of the WandbCallbackHandler. "
215
+ "The WeaveTracer is a more flexible and powerful tool for logging "
216
+ "and tracing your LangChain callables."
217
+ "Find more information at https://weave-docs.wandb.ai/guides/integrations/langchain"
218
+ ),
219
+ alternative=(
220
+ "Please instantiate the WeaveTracer from "
221
+ "weave.integrations.langchain import WeaveTracer ."
222
+ "For autologging simply use weave.init() and log all traces "
223
+ "from your LangChain callables."
224
+ ),
225
+ )
226
+
227
+ def _init_resp(self) -> Dict:
228
+ return {k: None for k in self.callback_columns}
229
+
230
+ def on_llm_start(
231
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
232
+ ) -> None:
233
+ """Run when LLM starts."""
234
+ self.step += 1
235
+ self.llm_starts += 1
236
+ self.starts += 1
237
+
238
+ resp = self._init_resp()
239
+ resp.update({"action": "on_llm_start"})
240
+ resp.update(flatten_dict(serialized))
241
+ resp.update(self.get_custom_callback_meta())
242
+
243
+ for prompt in prompts:
244
+ prompt_resp = deepcopy(resp)
245
+ prompt_resp["prompts"] = prompt
246
+ self.on_llm_start_records.append(prompt_resp)
247
+ self.action_records.append(prompt_resp)
248
+ if self.stream_logs:
249
+ self.run.log(prompt_resp)
250
+
251
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
252
+ """Run when LLM generates a new token."""
253
+ self.step += 1
254
+ self.llm_streams += 1
255
+
256
+ resp = self._init_resp()
257
+ resp.update({"action": "on_llm_new_token", "token": token})
258
+ resp.update(self.get_custom_callback_meta())
259
+
260
+ self.on_llm_token_records.append(resp)
261
+ self.action_records.append(resp)
262
+ if self.stream_logs:
263
+ self.run.log(resp)
264
+
265
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
266
+ """Run when LLM ends running."""
267
+ self.step += 1
268
+ self.llm_ends += 1
269
+ self.ends += 1
270
+
271
+ resp = self._init_resp()
272
+ resp.update({"action": "on_llm_end"})
273
+ resp.update(flatten_dict(response.llm_output or {}))
274
+ resp.update(self.get_custom_callback_meta())
275
+
276
+ for generations in response.generations:
277
+ for generation in generations:
278
+ generation_resp = deepcopy(resp)
279
+ generation_resp.update(flatten_dict(generation.dict()))
280
+ generation_resp.update(
281
+ analyze_text(
282
+ generation.text,
283
+ complexity_metrics=self.complexity_metrics,
284
+ visualize=self.visualize,
285
+ nlp=self.nlp,
286
+ output_dir=self.temp_dir.name,
287
+ )
288
+ )
289
+ self.on_llm_end_records.append(generation_resp)
290
+ self.action_records.append(generation_resp)
291
+ if self.stream_logs:
292
+ self.run.log(generation_resp)
293
+
294
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
295
+ """Run when LLM errors."""
296
+ self.step += 1
297
+ self.errors += 1
298
+
299
+ def on_chain_start(
300
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
301
+ ) -> None:
302
+ """Run when chain starts running."""
303
+ self.step += 1
304
+ self.chain_starts += 1
305
+ self.starts += 1
306
+
307
+ resp = self._init_resp()
308
+ resp.update({"action": "on_chain_start"})
309
+ resp.update(flatten_dict(serialized))
310
+ resp.update(self.get_custom_callback_meta())
311
+
312
+ chain_input = inputs["input"]
313
+
314
+ if isinstance(chain_input, str):
315
+ input_resp = deepcopy(resp)
316
+ input_resp["input"] = chain_input
317
+ self.on_chain_start_records.append(input_resp)
318
+ self.action_records.append(input_resp)
319
+ if self.stream_logs:
320
+ self.run.log(input_resp)
321
+ elif isinstance(chain_input, list):
322
+ for inp in chain_input:
323
+ input_resp = deepcopy(resp)
324
+ input_resp.update(inp)
325
+ self.on_chain_start_records.append(input_resp)
326
+ self.action_records.append(input_resp)
327
+ if self.stream_logs:
328
+ self.run.log(input_resp)
329
+ else:
330
+ raise ValueError("Unexpected data format provided!")
331
+
332
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
333
+ """Run when chain ends running."""
334
+ self.step += 1
335
+ self.chain_ends += 1
336
+ self.ends += 1
337
+
338
+ resp = self._init_resp()
339
+ resp.update({"action": "on_chain_end", "outputs": outputs["output"]})
340
+ resp.update(self.get_custom_callback_meta())
341
+
342
+ self.on_chain_end_records.append(resp)
343
+ self.action_records.append(resp)
344
+ if self.stream_logs:
345
+ self.run.log(resp)
346
+
347
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
348
+ """Run when chain errors."""
349
+ self.step += 1
350
+ self.errors += 1
351
+
352
+ def on_tool_start(
353
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
354
+ ) -> None:
355
+ """Run when tool starts running."""
356
+ self.step += 1
357
+ self.tool_starts += 1
358
+ self.starts += 1
359
+
360
+ resp = self._init_resp()
361
+ resp.update({"action": "on_tool_start", "input_str": input_str})
362
+ resp.update(flatten_dict(serialized))
363
+ resp.update(self.get_custom_callback_meta())
364
+
365
+ self.on_tool_start_records.append(resp)
366
+ self.action_records.append(resp)
367
+ if self.stream_logs:
368
+ self.run.log(resp)
369
+
370
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
371
+ """Run when tool ends running."""
372
+ output = str(output)
373
+ self.step += 1
374
+ self.tool_ends += 1
375
+ self.ends += 1
376
+
377
+ resp = self._init_resp()
378
+ resp.update({"action": "on_tool_end", "output": output})
379
+ resp.update(self.get_custom_callback_meta())
380
+
381
+ self.on_tool_end_records.append(resp)
382
+ self.action_records.append(resp)
383
+ if self.stream_logs:
384
+ self.run.log(resp)
385
+
386
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
387
+ """Run when tool errors."""
388
+ self.step += 1
389
+ self.errors += 1
390
+
391
+ def on_text(self, text: str, **kwargs: Any) -> None:
392
+ """
393
+ Run when agent is ending.
394
+ """
395
+ self.step += 1
396
+ self.text_ctr += 1
397
+
398
+ resp = self._init_resp()
399
+ resp.update({"action": "on_text", "text": text})
400
+ resp.update(self.get_custom_callback_meta())
401
+
402
+ self.on_text_records.append(resp)
403
+ self.action_records.append(resp)
404
+ if self.stream_logs:
405
+ self.run.log(resp)
406
+
407
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
408
+ """Run when agent ends running."""
409
+ self.step += 1
410
+ self.agent_ends += 1
411
+ self.ends += 1
412
+
413
+ resp = self._init_resp()
414
+ resp.update(
415
+ {
416
+ "action": "on_agent_finish",
417
+ "output": finish.return_values["output"],
418
+ "log": finish.log,
419
+ }
420
+ )
421
+ resp.update(self.get_custom_callback_meta())
422
+
423
+ self.on_agent_finish_records.append(resp)
424
+ self.action_records.append(resp)
425
+ if self.stream_logs:
426
+ self.run.log(resp)
427
+
428
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
429
+ """Run on agent action."""
430
+ self.step += 1
431
+ self.tool_starts += 1
432
+ self.starts += 1
433
+
434
+ resp = self._init_resp()
435
+ resp.update(
436
+ {
437
+ "action": "on_agent_action",
438
+ "tool": action.tool,
439
+ "tool_input": action.tool_input,
440
+ "log": action.log,
441
+ }
442
+ )
443
+ resp.update(self.get_custom_callback_meta())
444
+ self.on_agent_action_records.append(resp)
445
+ self.action_records.append(resp)
446
+ if self.stream_logs:
447
+ self.run.log(resp)
448
+
449
+ def _create_session_analysis_df(self) -> Any:
450
+ """Create a dataframe with all the information from the session."""
451
+ pd = import_pandas()
452
+ on_llm_start_records_df = pd.DataFrame(self.on_llm_start_records)
453
+ on_llm_end_records_df = pd.DataFrame(self.on_llm_end_records)
454
+
455
+ llm_input_prompts_df = (
456
+ on_llm_start_records_df[["step", "prompts", "name"]]
457
+ .dropna(axis=1)
458
+ .rename({"step": "prompt_step"}, axis=1)
459
+ )
460
+ complexity_metrics_columns = []
461
+ visualizations_columns = []
462
+
463
+ if self.complexity_metrics:
464
+ complexity_metrics_columns = [
465
+ "flesch_reading_ease",
466
+ "flesch_kincaid_grade",
467
+ "smog_index",
468
+ "coleman_liau_index",
469
+ "automated_readability_index",
470
+ "dale_chall_readability_score",
471
+ "difficult_words",
472
+ "linsear_write_formula",
473
+ "gunning_fog",
474
+ "text_standard",
475
+ "fernandez_huerta",
476
+ "szigriszt_pazos",
477
+ "gutierrez_polini",
478
+ "crawford",
479
+ "gulpease_index",
480
+ "osman",
481
+ ]
482
+
483
+ if self.visualize:
484
+ visualizations_columns = ["dependency_tree", "entities"]
485
+
486
+ llm_outputs_df = (
487
+ on_llm_end_records_df[
488
+ [
489
+ "step",
490
+ "text",
491
+ "token_usage_total_tokens",
492
+ "token_usage_prompt_tokens",
493
+ "token_usage_completion_tokens",
494
+ ]
495
+ + complexity_metrics_columns
496
+ + visualizations_columns
497
+ ]
498
+ .dropna(axis=1)
499
+ .rename({"step": "output_step", "text": "output"}, axis=1)
500
+ )
501
+ session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1)
502
+ session_analysis_df["chat_html"] = session_analysis_df[
503
+ ["prompts", "output"]
504
+ ].apply(
505
+ lambda row: construct_html_from_prompt_and_generation(
506
+ row["prompts"], row["output"]
507
+ ),
508
+ axis=1,
509
+ )
510
+ return session_analysis_df
511
+
512
+ def flush_tracker(
513
+ self,
514
+ langchain_asset: Any = None,
515
+ reset: bool = True,
516
+ finish: bool = False,
517
+ job_type: Optional[str] = None,
518
+ project: Optional[str] = None,
519
+ entity: Optional[str] = None,
520
+ tags: Optional[Sequence] = None,
521
+ group: Optional[str] = None,
522
+ name: Optional[str] = None,
523
+ notes: Optional[str] = None,
524
+ visualize: Optional[bool] = None,
525
+ complexity_metrics: Optional[bool] = None,
526
+ ) -> None:
527
+ """Flush the tracker and reset the session.
528
+
529
+ Args:
530
+ langchain_asset: The langchain asset to save.
531
+ reset: Whether to reset the session.
532
+ finish: Whether to finish the run.
533
+ job_type: The job type.
534
+ project: The project.
535
+ entity: The entity.
536
+ tags: The tags.
537
+ group: The group.
538
+ name: The name.
539
+ notes: The notes.
540
+ visualize: Whether to visualize.
541
+ complexity_metrics: Whether to compute complexity metrics.
542
+
543
+ Returns:
544
+ None
545
+ """
546
+ pd = import_pandas()
547
+ wandb = import_wandb()
548
+ action_records_table = wandb.Table(dataframe=pd.DataFrame(self.action_records))
549
+ session_analysis_table = wandb.Table(
550
+ dataframe=self._create_session_analysis_df()
551
+ )
552
+ self.run.log(
553
+ {
554
+ "action_records": action_records_table,
555
+ "session_analysis": session_analysis_table,
556
+ }
557
+ )
558
+
559
+ if langchain_asset:
560
+ langchain_asset_path = Path(self.temp_dir.name, "model.json")
561
+ model_artifact = wandb.Artifact(name="model", type="model")
562
+ model_artifact.add(action_records_table, name="action_records")
563
+ model_artifact.add(session_analysis_table, name="session_analysis")
564
+ try:
565
+ langchain_asset.save(langchain_asset_path)
566
+ model_artifact.add_file(str(langchain_asset_path))
567
+ model_artifact.metadata = load_json_to_dict(langchain_asset_path)
568
+ except ValueError:
569
+ langchain_asset.save_agent(langchain_asset_path)
570
+ model_artifact.add_file(str(langchain_asset_path))
571
+ model_artifact.metadata = load_json_to_dict(langchain_asset_path)
572
+ except NotImplementedError as e:
573
+ print("Could not save model.") # noqa: T201
574
+ print(repr(e)) # noqa: T201
575
+ pass
576
+ self.run.log_artifact(model_artifact)
577
+
578
+ if finish or reset:
579
+ self.run.finish()
580
+ self.temp_dir.cleanup()
581
+ self.reset_callback_meta()
582
+ if reset:
583
+ self.__init__( # type: ignore[misc]
584
+ job_type=job_type if job_type else self.job_type,
585
+ project=project if project else self.project,
586
+ entity=entity if entity else self.entity,
587
+ tags=tags if tags else self.tags,
588
+ group=group if group else self.group,
589
+ name=name if name else self.name,
590
+ notes=notes if notes else self.notes,
591
+ visualize=visualize if visualize else self.visualize,
592
+ complexity_metrics=(
593
+ complexity_metrics
594
+ if complexity_metrics
595
+ else self.complexity_metrics
596
+ ),
597
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/whylabs_callback.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import TYPE_CHECKING, Any, Optional
5
+
6
+ from langchain_core.callbacks import BaseCallbackHandler
7
+ from langchain_core.utils import get_from_env, guard_import
8
+
9
+ if TYPE_CHECKING:
10
+ from whylogs.api.logger.logger import Logger
11
+
12
+ diagnostic_logger = logging.getLogger(__name__)
13
+
14
+
15
+ def import_langkit(
16
+ sentiment: bool = False,
17
+ toxicity: bool = False,
18
+ themes: bool = False,
19
+ ) -> Any:
20
+ """Import the langkit python package and raise an error if it is not installed.
21
+
22
+ Args:
23
+ sentiment: Whether to import the langkit.sentiment module. Defaults to False.
24
+ toxicity: Whether to import the langkit.toxicity module. Defaults to False.
25
+ themes: Whether to import the langkit.themes module. Defaults to False.
26
+
27
+ Returns:
28
+ The imported langkit module.
29
+ """
30
+ langkit = guard_import("langkit")
31
+ guard_import("langkit.regexes")
32
+ guard_import("langkit.textstat")
33
+ if sentiment:
34
+ guard_import("langkit.sentiment")
35
+ if toxicity:
36
+ guard_import("langkit.toxicity")
37
+ if themes:
38
+ guard_import("langkit.themes")
39
+ return langkit
40
+
41
+
42
+ class WhyLabsCallbackHandler(BaseCallbackHandler):
43
+ """
44
+ Callback Handler for logging to WhyLabs. This callback handler utilizes
45
+ `langkit` to extract features from the prompts & responses when interacting with
46
+ an LLM. These features can be used to guardrail, evaluate, and observe interactions
47
+ over time to detect issues relating to hallucinations, prompt engineering,
48
+ or output validation. LangKit is an LLM monitoring toolkit developed by WhyLabs.
49
+
50
+ Here are some examples of what can be monitored with LangKit:
51
+ * Text Quality
52
+ - readability score
53
+ - complexity and grade scores
54
+ * Text Relevance
55
+ - Similarity scores between prompt/responses
56
+ - Similarity scores against user-defined themes
57
+ - Topic classification
58
+ * Security and Privacy
59
+ - patterns - count of strings matching a user-defined regex pattern group
60
+ - jailbreaks - similarity scores with respect to known jailbreak attempts
61
+ - prompt injection - similarity scores with respect to known prompt attacks
62
+ - refusals - similarity scores with respect to known LLM refusal responses
63
+ * Sentiment and Toxicity
64
+ - sentiment analysis
65
+ - toxicity analysis
66
+
67
+ For more information, see https://docs.whylabs.ai/docs/language-model-monitoring
68
+ or check out the LangKit repo here: https://github.com/whylabs/langkit
69
+
70
+ ---
71
+ Args:
72
+ api_key (Optional[str]): WhyLabs API key. Optional because the preferred
73
+ way to specify the API key is with environment variable
74
+ WHYLABS_API_KEY.
75
+ org_id (Optional[str]): WhyLabs organization id to write profiles to.
76
+ Optional because the preferred way to specify the organization id is
77
+ with environment variable WHYLABS_DEFAULT_ORG_ID.
78
+ dataset_id (Optional[str]): WhyLabs dataset id to write profiles to.
79
+ Optional because the preferred way to specify the dataset id is
80
+ with environment variable WHYLABS_DEFAULT_DATASET_ID.
81
+ sentiment (bool): Whether to enable sentiment analysis. Defaults to False.
82
+ toxicity (bool): Whether to enable toxicity analysis. Defaults to False.
83
+ themes (bool): Whether to enable theme analysis. Defaults to False.
84
+ """
85
+
86
+ def __init__(self, logger: Logger, handler: Any):
87
+ """Initiate the rolling logger."""
88
+ super().__init__()
89
+ if hasattr(handler, "init"):
90
+ handler.init(self)
91
+ if hasattr(handler, "_get_callbacks"):
92
+ self._callbacks = handler._get_callbacks()
93
+ else:
94
+ self._callbacks = dict()
95
+ diagnostic_logger.warning("initialized handler without callbacks.")
96
+ self._logger = logger
97
+
98
+ def flush(self) -> None:
99
+ """Explicitly write current profile if using a rolling logger."""
100
+ if self._logger and hasattr(self._logger, "_do_rollover"):
101
+ self._logger._do_rollover()
102
+ diagnostic_logger.info("Flushing WhyLabs logger, writing profile...")
103
+
104
+ def close(self) -> None:
105
+ """Close any loggers to allow writing out of any profiles before exiting."""
106
+ if self._logger and hasattr(self._logger, "close"):
107
+ self._logger.close()
108
+ diagnostic_logger.info("Closing WhyLabs logger, see you next time!")
109
+
110
+ def __enter__(self) -> WhyLabsCallbackHandler:
111
+ return self
112
+
113
+ def __exit__(
114
+ self, exception_type: Any, exception_value: Any, traceback: Any
115
+ ) -> None:
116
+ self.close()
117
+
118
+ @classmethod
119
+ def from_params(
120
+ cls,
121
+ *,
122
+ api_key: Optional[str] = None,
123
+ org_id: Optional[str] = None,
124
+ dataset_id: Optional[str] = None,
125
+ sentiment: bool = False,
126
+ toxicity: bool = False,
127
+ themes: bool = False,
128
+ logger: Optional[Logger] = None,
129
+ ) -> WhyLabsCallbackHandler:
130
+ """Instantiate whylogs Logger from params.
131
+
132
+ Args:
133
+ api_key (Optional[str]): WhyLabs API key. Optional because the preferred
134
+ way to specify the API key is with environment variable
135
+ WHYLABS_API_KEY.
136
+ org_id (Optional[str]): WhyLabs organization id to write profiles to.
137
+ If not set must be specified in environment variable
138
+ WHYLABS_DEFAULT_ORG_ID.
139
+ dataset_id (Optional[str]): The model or dataset this callback is gathering
140
+ telemetry for. If not set must be specified in environment variable
141
+ WHYLABS_DEFAULT_DATASET_ID.
142
+ sentiment (bool): If True will initialize a model to perform
143
+ sentiment analysis compound score. Defaults to False and will not gather
144
+ this metric.
145
+ toxicity (bool): If True will initialize a model to score
146
+ toxicity. Defaults to False and will not gather this metric.
147
+ themes (bool): If True will initialize a model to calculate
148
+ distance to configured themes. Defaults to None and will not gather this
149
+ metric.
150
+ logger (Optional[Logger]): If specified will bind the configured logger as
151
+ the telemetry gathering agent. Defaults to LangKit schema with periodic
152
+ WhyLabs writer.
153
+ """
154
+ # langkit library will import necessary whylogs libraries
155
+ import_langkit(sentiment=sentiment, toxicity=toxicity, themes=themes)
156
+
157
+ why = guard_import("whylogs")
158
+ get_callback_instance = guard_import(
159
+ "langkit.callback_handler"
160
+ ).get_callback_instance
161
+ WhyLabsWriter = guard_import("whylogs.api.writer.whylabs").WhyLabsWriter
162
+ udf_schema = guard_import("whylogs.experimental.core.udf_schema").udf_schema
163
+
164
+ if logger is None:
165
+ api_key = api_key or get_from_env("api_key", "WHYLABS_API_KEY")
166
+ org_id = org_id or get_from_env("org_id", "WHYLABS_DEFAULT_ORG_ID")
167
+ dataset_id = dataset_id or get_from_env(
168
+ "dataset_id", "WHYLABS_DEFAULT_DATASET_ID"
169
+ )
170
+ whylabs_writer = WhyLabsWriter(
171
+ api_key=api_key, org_id=org_id, dataset_id=dataset_id
172
+ )
173
+
174
+ whylabs_logger = why.logger(
175
+ mode="rolling", interval=5, when="M", schema=udf_schema()
176
+ )
177
+
178
+ whylabs_logger.append_writer(writer=whylabs_writer)
179
+ else:
180
+ diagnostic_logger.info("Using passed in whylogs logger {logger}")
181
+ whylabs_logger = logger
182
+
183
+ callback_handler_cls = get_callback_instance(logger=whylabs_logger, impl=cls)
184
+ diagnostic_logger.info(
185
+ "Started whylogs Logger with WhyLabsWriter and initialized LangKit. 📝"
186
+ )
187
+ return callback_handler_cls
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chains module for langchain_community
3
+
4
+ This module contains the community chains.
5
+ """
6
+
7
+ import importlib
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ if TYPE_CHECKING:
11
+ from langchain_community.chains.pebblo_retrieval.base import PebbloRetrievalQA
12
+
13
+ __all__ = ["PebbloRetrievalQA"]
14
+
15
+ _module_lookup = {
16
+ "PebbloRetrievalQA": "langchain_community.chains.pebblo_retrieval.base"
17
+ }
18
+
19
+
20
+ def __getattr__(name: str) -> Any:
21
+ if name in _module_lookup:
22
+ module = importlib.import_module(_module_lookup[name])
23
+ return getattr(module, name)
24
+ raise AttributeError(f"module {__name__} has no attribute {name}")
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/llm_requests.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chain that hits a URL and then uses an LLM to parse results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from langchain_classic.chains import LLMChain
8
+ from langchain_classic.chains.base import Chain
9
+ from langchain_core.callbacks import CallbackManagerForChainRun
10
+ from pydantic import ConfigDict, Field, model_validator
11
+
12
+ from langchain_community.utilities.requests import TextRequestsWrapper
13
+
14
+ DEFAULT_HEADERS = {
15
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" # noqa: E501
16
+ }
17
+
18
+
19
+ class LLMRequestsChain(Chain):
20
+ """Chain that requests a URL and then uses an LLM to parse results.
21
+
22
+ **Security Note**: This chain can make GET requests to arbitrary URLs,
23
+ including internal URLs.
24
+
25
+ Control access to who can run this chain and what network access
26
+ this chain has.
27
+
28
+ See https://python.langchain.com/docs/security for more information.
29
+ """
30
+
31
+ llm_chain: LLMChain
32
+ requests_wrapper: TextRequestsWrapper = Field(
33
+ default_factory=lambda: TextRequestsWrapper(headers=DEFAULT_HEADERS),
34
+ exclude=True,
35
+ )
36
+ text_length: int = 8000
37
+ requests_key: str = "requests_result" #: :meta private:
38
+ input_key: str = "url" #: :meta private:
39
+ output_key: str = "output" #: :meta private:
40
+
41
+ model_config = ConfigDict(
42
+ arbitrary_types_allowed=True,
43
+ extra="forbid",
44
+ )
45
+
46
+ @property
47
+ def input_keys(self) -> List[str]:
48
+ """Will be whatever keys the prompt expects.
49
+
50
+ :meta private:
51
+ """
52
+ return [self.input_key]
53
+
54
+ @property
55
+ def output_keys(self) -> List[str]:
56
+ """Will always return text key.
57
+
58
+ :meta private:
59
+ """
60
+ return [self.output_key]
61
+
62
+ @model_validator(mode="before")
63
+ @classmethod
64
+ def validate_environment(cls, values: Dict) -> Any:
65
+ """Validate that api key and python package exists in environment."""
66
+ try:
67
+ from bs4 import BeautifulSoup # noqa: F401
68
+
69
+ except ImportError:
70
+ raise ImportError(
71
+ "Could not import bs4 python package. "
72
+ "Please install it with `pip install bs4`."
73
+ )
74
+ return values
75
+
76
+ def _call(
77
+ self,
78
+ inputs: Dict[str, Any],
79
+ run_manager: Optional[CallbackManagerForChainRun] = None,
80
+ ) -> Dict[str, Any]:
81
+ from bs4 import BeautifulSoup
82
+
83
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
84
+ # Other keys are assumed to be needed for LLM prediction
85
+ other_keys = {k: v for k, v in inputs.items() if k != self.input_key}
86
+ url = inputs[self.input_key]
87
+ res = self.requests_wrapper.get(url)
88
+ # extract the text from the html
89
+ soup = BeautifulSoup(res, "html.parser") # type: ignore[arg-type]
90
+ other_keys[self.requests_key] = soup.get_text()[: self.text_length]
91
+ result = self.llm_chain.predict(
92
+ callbacks=_run_manager.get_child(), **other_keys
93
+ )
94
+ return {self.output_key: result}
95
+
96
+ @property
97
+ def _chain_type(self) -> str:
98
+ return "llm_requests_chain"
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__init__.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """**Chat Loaders** load chat messages from common communications platforms.
2
+
3
+ Load chat messages from various
4
+ communications platforms such as Facebook Messenger, Telegram, and
5
+ WhatsApp. The loaded chat messages can be used for fine-tuning models.
6
+
7
+ **Class hierarchy:**
8
+
9
+ .. code-block::
10
+
11
+ BaseChatLoader --> <name>ChatLoader # Examples: WhatsAppChatLoader, IMessageChatLoader
12
+
13
+ **Main helpers:**
14
+
15
+ .. code-block::
16
+
17
+ ChatSession
18
+
19
+ """ # noqa: E501
20
+
21
+ import importlib
22
+ from typing import TYPE_CHECKING, Any
23
+
24
+ if TYPE_CHECKING:
25
+ from langchain_community.chat_loaders.base import (
26
+ BaseChatLoader,
27
+ )
28
+ from langchain_community.chat_loaders.facebook_messenger import (
29
+ FolderFacebookMessengerChatLoader,
30
+ SingleFileFacebookMessengerChatLoader,
31
+ )
32
+ from langchain_community.chat_loaders.gmail import (
33
+ GMailLoader,
34
+ )
35
+ from langchain_community.chat_loaders.imessage import (
36
+ IMessageChatLoader,
37
+ )
38
+ from langchain_community.chat_loaders.langsmith import (
39
+ LangSmithDatasetChatLoader,
40
+ LangSmithRunChatLoader,
41
+ )
42
+ from langchain_community.chat_loaders.slack import (
43
+ SlackChatLoader,
44
+ )
45
+ from langchain_community.chat_loaders.telegram import (
46
+ TelegramChatLoader,
47
+ )
48
+ from langchain_community.chat_loaders.whatsapp import (
49
+ WhatsAppChatLoader,
50
+ )
51
+
52
+ __all__ = [
53
+ "BaseChatLoader",
54
+ "FolderFacebookMessengerChatLoader",
55
+ "GMailLoader",
56
+ "IMessageChatLoader",
57
+ "LangSmithDatasetChatLoader",
58
+ "LangSmithRunChatLoader",
59
+ "SingleFileFacebookMessengerChatLoader",
60
+ "SlackChatLoader",
61
+ "TelegramChatLoader",
62
+ "WhatsAppChatLoader",
63
+ ]
64
+
65
+ _module_lookup = {
66
+ "BaseChatLoader": "langchain_core.chat_loaders",
67
+ "FolderFacebookMessengerChatLoader": "langchain_community.chat_loaders.facebook_messenger", # noqa: E501
68
+ "GMailLoader": "langchain_community.chat_loaders.gmail",
69
+ "IMessageChatLoader": "langchain_community.chat_loaders.imessage",
70
+ "LangSmithDatasetChatLoader": "langchain_community.chat_loaders.langsmith",
71
+ "LangSmithRunChatLoader": "langchain_community.chat_loaders.langsmith",
72
+ "SingleFileFacebookMessengerChatLoader": "langchain_community.chat_loaders.facebook_messenger", # noqa: E501
73
+ "SlackChatLoader": "langchain_community.chat_loaders.slack",
74
+ "TelegramChatLoader": "langchain_community.chat_loaders.telegram",
75
+ "WhatsAppChatLoader": "langchain_community.chat_loaders.whatsapp",
76
+ }
77
+
78
+
79
+ def __getattr__(name: str) -> Any:
80
+ if name in _module_lookup:
81
+ module = importlib.import_module(_module_lookup[name])
82
+ return getattr(module, name)
83
+ raise AttributeError(f"module {__name__} has no attribute {name}")
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/base.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from langchain_core.chat_loaders import BaseChatLoader
2
+
3
+ __all__ = ["BaseChatLoader"]
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/facebook_messenger.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from pathlib import Path
4
+ from typing import Iterator, Union
5
+
6
+ from langchain_core.chat_loaders import BaseChatLoader
7
+ from langchain_core.chat_sessions import ChatSession
8
+ from langchain_core.messages import HumanMessage
9
+
10
+ logger = logging.getLogger(__file__)
11
+
12
+
13
+ class SingleFileFacebookMessengerChatLoader(BaseChatLoader):
14
+ """Load `Facebook Messenger` chat data from a single file.
15
+
16
+ Args:
17
+ path (Union[Path, str]): The path to the chat file.
18
+
19
+ """
20
+
21
+ def __init__(self, path: Union[Path, str]) -> None:
22
+ super().__init__()
23
+ self.file_path = path if isinstance(path, Path) else Path(path)
24
+
25
+ def lazy_load(self) -> Iterator[ChatSession]:
26
+ """Lazy loads the chat data from the file.
27
+
28
+ Yields:
29
+ ChatSession: A chat session containing the loaded messages.
30
+
31
+ """
32
+ with open(self.file_path) as f:
33
+ data = json.load(f)
34
+ sorted_data = sorted(data["messages"], key=lambda x: x["timestamp_ms"])
35
+ messages = []
36
+ for index, m in enumerate(sorted_data):
37
+ if "content" not in m:
38
+ logger.info(
39
+ f"""Skipping Message No.
40
+ {index + 1} as no content is present in the message"""
41
+ )
42
+ continue
43
+ messages.append(
44
+ HumanMessage(
45
+ content=m["content"], additional_kwargs={"sender": m["sender_name"]}
46
+ )
47
+ )
48
+ yield ChatSession(messages=messages)
49
+
50
+
51
+ class FolderFacebookMessengerChatLoader(BaseChatLoader):
52
+ """Load `Facebook Messenger` chat data from a folder.
53
+
54
+ Args:
55
+ path (Union[str, Path]): The path to the directory
56
+ containing the chat files.
57
+
58
+ """
59
+
60
+ def __init__(self, path: Union[str, Path]) -> None:
61
+ super().__init__()
62
+ self.directory_path = Path(path) if isinstance(path, str) else path
63
+
64
+ def lazy_load(self) -> Iterator[ChatSession]:
65
+ """Lazy loads the chat data from the folder.
66
+
67
+ Yields:
68
+ ChatSession: A chat session containing the loaded messages.
69
+
70
+ """
71
+ inbox_path = self.directory_path / "inbox"
72
+ for _dir in inbox_path.iterdir():
73
+ if _dir.is_dir():
74
+ for _file in _dir.iterdir():
75
+ if _file.suffix.lower() == ".json":
76
+ file_loader = SingleFileFacebookMessengerChatLoader(path=_file)
77
+ for result in file_loader.lazy_load():
78
+ yield result
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/gmail.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import re
3
+ from typing import Any, Iterator
4
+
5
+ from langchain_core._api.deprecation import deprecated
6
+ from langchain_core.chat_loaders import BaseChatLoader
7
+ from langchain_core.chat_sessions import ChatSession
8
+ from langchain_core.messages import HumanMessage
9
+
10
+
11
+ def _extract_email_content(msg: Any) -> HumanMessage:
12
+ from_email = None
13
+ for values in msg["payload"]["headers"]:
14
+ name = values["name"]
15
+ if name == "From":
16
+ from_email = values["value"]
17
+ if from_email is None:
18
+ raise ValueError
19
+ for part in msg["payload"]["parts"]:
20
+ if part["mimeType"] == "text/plain":
21
+ data = part["body"]["data"]
22
+ data = base64.urlsafe_b64decode(data).decode("utf-8")
23
+ # Regular expression to split the email body at the first
24
+ # occurrence of a line that starts with "On ... wrote:"
25
+ pattern = re.compile(r"\r\nOn .+(\r\n)*wrote:\r\n")
26
+ # Split the email body and extract the first part
27
+ newest_response = re.split(pattern, data)[0]
28
+ message = HumanMessage(
29
+ content=newest_response, additional_kwargs={"sender": from_email}
30
+ )
31
+ return message
32
+ raise ValueError
33
+
34
+
35
+ def _get_message_data(service: Any, message: Any) -> ChatSession:
36
+ msg = service.users().messages().get(userId="me", id=message["id"]).execute()
37
+ message_content = _extract_email_content(msg)
38
+ in_reply_to = None
39
+ email_data = msg["payload"]["headers"]
40
+ for values in email_data:
41
+ name = values["name"]
42
+ if name == "In-Reply-To":
43
+ in_reply_to = values["value"]
44
+ if in_reply_to is None:
45
+ raise ValueError
46
+
47
+ thread_id = msg["threadId"]
48
+
49
+ thread = service.users().threads().get(userId="me", id=thread_id).execute()
50
+ messages = thread["messages"]
51
+
52
+ response_email = None
53
+ for message in messages:
54
+ email_data = message["payload"]["headers"]
55
+ for values in email_data:
56
+ if values["name"] == "Message-ID":
57
+ message_id = values["value"]
58
+ if message_id == in_reply_to:
59
+ response_email = message
60
+ if response_email is None:
61
+ raise ValueError
62
+ starter_content = _extract_email_content(response_email)
63
+ return ChatSession(messages=[starter_content, message_content])
64
+
65
+
66
+ @deprecated(
67
+ since="0.0.32",
68
+ removal="1.0",
69
+ alternative_import="langchain_google_community.GMailLoader",
70
+ )
71
+ class GMailLoader(BaseChatLoader):
72
+ """Load data from `GMail`.
73
+
74
+ There are many ways you could want to load data from GMail.
75
+ This loader is currently fairly opinionated in how to do so.
76
+ The way it does it is it first looks for all messages that you have sent.
77
+ It then looks for messages where you are responding to a previous email.
78
+ It then fetches that previous email, and creates a training example
79
+ of that email, followed by your email.
80
+
81
+ Note that there are clear limitations here. For example,
82
+ all examples created are only looking at the previous email for context.
83
+
84
+ To use:
85
+
86
+ - Set up a Google Developer Account:
87
+ Go to the Google Developer Console, create a project,
88
+ and enable the Gmail API for that project.
89
+ This will give you a credentials.json file that you'll need later.
90
+ """
91
+
92
+ def __init__(self, creds: Any, n: int = 100, raise_error: bool = False) -> None:
93
+ super().__init__()
94
+ self.creds = creds
95
+ self.n = n
96
+ self.raise_error = raise_error
97
+
98
+ def lazy_load(self) -> Iterator[ChatSession]:
99
+ from googleapiclient.discovery import build
100
+
101
+ service = build("gmail", "v1", credentials=self.creds)
102
+ results = (
103
+ service.users()
104
+ .messages()
105
+ .list(userId="me", labelIds=["SENT"], maxResults=self.n)
106
+ .execute()
107
+ )
108
+ messages = results.get("messages", [])
109
+ for message in messages:
110
+ try:
111
+ yield _get_message_data(service, message)
112
+ except Exception as e:
113
+ # TODO: handle errors better
114
+ if self.raise_error:
115
+ raise e
116
+ else:
117
+ pass
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/imessage.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+ from typing import TYPE_CHECKING, Iterator, List, Optional, Union
6
+
7
+ from langchain_core.chat_loaders import BaseChatLoader
8
+ from langchain_core.chat_sessions import ChatSession
9
+ from langchain_core.messages import HumanMessage
10
+
11
+ if TYPE_CHECKING:
12
+ import sqlite3
13
+
14
+
15
+ def nanoseconds_from_2001_to_datetime(nanoseconds: int) -> datetime:
16
+ """Convert nanoseconds since 2001 to a datetime object.
17
+
18
+ Args:
19
+ nanoseconds (int): Nanoseconds since January 1, 2001.
20
+
21
+ Returns:
22
+ datetime: Datetime object.
23
+ """
24
+ # Convert nanoseconds to seconds (1 second = 1e9 nanoseconds)
25
+ timestamp_in_seconds = nanoseconds / 1e9
26
+
27
+ # The reference date is January 1, 2001, in Unix time
28
+ reference_date_seconds = datetime(2001, 1, 1).timestamp()
29
+
30
+ # Calculate the actual timestamp by adding the reference date
31
+ actual_timestamp = reference_date_seconds + timestamp_in_seconds
32
+
33
+ # Convert to a datetime object
34
+ return datetime.fromtimestamp(actual_timestamp)
35
+
36
+
37
+ class IMessageChatLoader(BaseChatLoader):
38
+ """Load chat sessions from the `iMessage` chat.db SQLite file.
39
+
40
+ It only works on macOS when you have iMessage enabled and have the chat.db file.
41
+
42
+ The chat.db file is likely located at ~/Library/Messages/chat.db. However, your
43
+ terminal may not have permission to access this file. To resolve this, you can
44
+ copy the file to a different location, change the permissions of the file, or
45
+ grant full disk access for your terminal emulator
46
+ in System Settings > Security and Privacy > Full Disk Access.
47
+ """
48
+
49
+ def __init__(self, path: Optional[Union[str, Path]] = None):
50
+ """
51
+ Initialize the IMessageChatLoader.
52
+
53
+ Args:
54
+ path (str or Path, optional): Path to the chat.db SQLite file.
55
+ Defaults to None, in which case the default path
56
+ ~/Library/Messages/chat.db will be used.
57
+ """
58
+ if path is None:
59
+ path = Path.home() / "Library" / "Messages" / "chat.db"
60
+ self.db_path = path if isinstance(path, Path) else Path(path)
61
+ if not self.db_path.exists():
62
+ raise FileNotFoundError(f"File {self.db_path} not found")
63
+ try:
64
+ import sqlite3 # noqa: F401
65
+ except ImportError as e:
66
+ raise ImportError(
67
+ "The sqlite3 module is required to load iMessage chats.\n"
68
+ "Please install it with `pip install pysqlite3`"
69
+ ) from e
70
+
71
+ @staticmethod
72
+ def _parse_attributed_body(attributed_body: bytes) -> str:
73
+ """
74
+ Parse the attributedBody field of the message table
75
+ for the text content of the message.
76
+
77
+ The attributedBody field is a binary blob that contains
78
+ the message content after the byte string b"NSString":
79
+
80
+ 5 bytes 1-3 bytes `len` bytes
81
+ ... | b"NSString" | preamble | `len` | contents | ...
82
+
83
+ The 5 preamble bytes are always b"\x01\x94\x84\x01+"
84
+
85
+ The size of `len` is either 1 byte or 3 bytes:
86
+ - If the first byte in `len` is b"\x81" then `len` is 3 bytes long.
87
+ So the message length is the 2 bytes after, in little Endian.
88
+ - Otherwise, the size of `len` is 1 byte, and the message length is
89
+ that byte.
90
+
91
+ Args:
92
+ attributed_body (bytes): attributedBody field of the message table.
93
+ Return:
94
+ str: Text content of the message.
95
+ """
96
+ content = attributed_body.split(b"NSString")[1][5:]
97
+ length, start = content[0], 1
98
+ if content[0] == 129:
99
+ length, start = int.from_bytes(content[1:3], "little"), 3
100
+ return content[start : start + length].decode("utf-8", errors="ignore")
101
+
102
+ @staticmethod
103
+ def _get_session_query(use_chat_handle_table: bool) -> str:
104
+ # Messages sent pre OSX 12 require a join through the chat_handle_join table
105
+ # However, the table doesn't exist if database created with OSX 12 or above.
106
+
107
+ joins_w_chat_handle = """
108
+ JOIN chat_handle_join ON
109
+ chat_message_join.chat_id = chat_handle_join.chat_id
110
+ JOIN handle ON
111
+ handle.ROWID = chat_handle_join.handle_id"""
112
+
113
+ joins_no_chat_handle = """
114
+ JOIN handle ON message.handle_id = handle.ROWID
115
+ """
116
+
117
+ joins = joins_w_chat_handle if use_chat_handle_table else joins_no_chat_handle
118
+
119
+ return f"""
120
+ SELECT message.date,
121
+ handle.id,
122
+ message.text,
123
+ message.is_from_me,
124
+ message.attributedBody
125
+ FROM message
126
+ JOIN chat_message_join ON
127
+ message.ROWID = chat_message_join.message_id
128
+ {joins}
129
+ WHERE chat_message_join.chat_id = ?
130
+ ORDER BY message.date ASC;
131
+ """
132
+
133
+ def _load_single_chat_session(
134
+ self, cursor: "sqlite3.Cursor", use_chat_handle_table: bool, chat_id: int
135
+ ) -> ChatSession:
136
+ """
137
+ Load a single chat session from the iMessage chat.db.
138
+
139
+ Args:
140
+ cursor: SQLite cursor object.
141
+ chat_id (int): ID of the chat session to load.
142
+
143
+ Returns:
144
+ ChatSession: Loaded chat session.
145
+ """
146
+ results: List[HumanMessage] = []
147
+
148
+ query = self._get_session_query(use_chat_handle_table)
149
+ cursor.execute(query, (chat_id,))
150
+ messages = cursor.fetchall()
151
+
152
+ for date, sender, text, is_from_me, attributedBody in messages:
153
+ if text:
154
+ content = text
155
+ elif attributedBody:
156
+ content = self._parse_attributed_body(attributedBody)
157
+ else: # Skip messages with no content
158
+ continue
159
+
160
+ results.append(
161
+ HumanMessage(
162
+ role=sender,
163
+ content=content,
164
+ additional_kwargs={
165
+ "message_time": date,
166
+ "message_time_as_datetime": nanoseconds_from_2001_to_datetime(
167
+ date
168
+ ),
169
+ "sender": sender,
170
+ "is_from_me": bool(is_from_me),
171
+ },
172
+ )
173
+ )
174
+
175
+ return ChatSession(messages=results)
176
+
177
+ def lazy_load(self) -> Iterator[ChatSession]:
178
+ """
179
+ Lazy load the chat sessions from the iMessage chat.db
180
+ and yield them in the required format.
181
+
182
+ Yields:
183
+ ChatSession: Loaded chat session.
184
+ """
185
+ import sqlite3
186
+
187
+ try:
188
+ conn = sqlite3.connect(self.db_path)
189
+ except sqlite3.OperationalError as e:
190
+ raise ValueError(
191
+ f"Could not open iMessage DB file {self.db_path}.\n"
192
+ "Make sure your terminal emulator has disk access to this file.\n"
193
+ " You can either copy the DB file to an accessible location"
194
+ " or grant full disk access for your terminal emulator."
195
+ " You can grant full disk access for your terminal emulator"
196
+ " in System Settings > Security and Privacy > Full Disk Access."
197
+ ) from e
198
+ cursor = conn.cursor()
199
+
200
+ # See if chat_handle_join table exists:
201
+ query = """SELECT name FROM sqlite_master
202
+ WHERE type='table' AND name='chat_handle_join';"""
203
+
204
+ cursor.execute(query)
205
+ is_chat_handle_join_exists = cursor.fetchone()
206
+
207
+ # Fetch the list of chat IDs sorted by time (most recent first)
208
+ query = """SELECT chat_id
209
+ FROM message
210
+ JOIN chat_message_join ON message.ROWID = chat_message_join.message_id
211
+ GROUP BY chat_id
212
+ ORDER BY MAX(date) DESC;"""
213
+ cursor.execute(query)
214
+ chat_ids = [row[0] for row in cursor.fetchall()]
215
+
216
+ for chat_id in chat_ids:
217
+ yield self._load_single_chat_session(
218
+ cursor, is_chat_handle_join_exists, chat_id
219
+ )
220
+
221
+ conn.close()
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/langsmith.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import TYPE_CHECKING, Dict, Iterable, Iterator, List, Optional, Union, cast
5
+
6
+ from langchain_core.chat_loaders import BaseChatLoader
7
+ from langchain_core.chat_sessions import ChatSession
8
+ from langchain_core.load.load import load
9
+
10
+ if TYPE_CHECKING:
11
+ from langsmith.client import Client
12
+ from langsmith.schemas import Run
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class LangSmithRunChatLoader(BaseChatLoader):
18
+ """
19
+ Load chat sessions from a list of LangSmith "llm" runs.
20
+
21
+ Attributes:
22
+ runs (Iterable[Union[str, Run]]): The list of LLM run IDs or run objects.
23
+ client (Client): Instance of LangSmith client for fetching data.
24
+ """
25
+
26
+ def __init__(
27
+ self, runs: Iterable[Union[str, Run]], client: Optional["Client"] = None
28
+ ):
29
+ """
30
+ Initialize a new LangSmithRunChatLoader instance.
31
+
32
+ :param runs: List of LLM run IDs or run objects.
33
+ :param client: An instance of LangSmith client, if not provided,
34
+ a new client instance will be created.
35
+ """
36
+ from langsmith.client import Client
37
+
38
+ self.runs = runs
39
+ self.client = client or Client()
40
+
41
+ @staticmethod
42
+ def _load_single_chat_session(llm_run: "Run") -> ChatSession:
43
+ """
44
+ Convert an individual LangSmith LLM run to a ChatSession.
45
+
46
+ :param llm_run: The LLM run object.
47
+ :return: A chat session representing the run's data.
48
+ """
49
+ chat_session = LangSmithRunChatLoader._get_messages_from_llm_run(llm_run)
50
+ functions = LangSmithRunChatLoader._get_functions_from_llm_run(llm_run)
51
+ if functions:
52
+ chat_session["functions"] = functions
53
+ return chat_session
54
+
55
+ @staticmethod
56
+ def _get_messages_from_llm_run(llm_run: "Run") -> ChatSession:
57
+ """
58
+ Extract messages from a LangSmith LLM run.
59
+
60
+ :param llm_run: The LLM run object.
61
+ :return: ChatSession with the extracted messages.
62
+ """
63
+ if llm_run.run_type != "llm":
64
+ raise ValueError(f"Expected run of type llm. Got: {llm_run.run_type}")
65
+ if "messages" not in llm_run.inputs:
66
+ raise ValueError(f"Run has no 'messages' inputs. Got {llm_run.inputs}")
67
+ if not llm_run.outputs:
68
+ raise ValueError("Cannot convert pending run")
69
+ messages = load(llm_run.inputs)["messages"]
70
+ message_chunk = load(llm_run.outputs)["generations"][0]["message"]
71
+ return ChatSession(messages=messages + [message_chunk])
72
+
73
+ @staticmethod
74
+ def _get_functions_from_llm_run(llm_run: "Run") -> Optional[List[Dict]]:
75
+ """
76
+ Extract functions from a LangSmith LLM run if they exist.
77
+
78
+ :param llm_run: The LLM run object.
79
+ :return: Functions from the run or None.
80
+ """
81
+ if llm_run.run_type != "llm":
82
+ raise ValueError(f"Expected run of type llm. Got: {llm_run.run_type}")
83
+ return (llm_run.extra or {}).get("invocation_params", {}).get("functions")
84
+
85
+ def lazy_load(self) -> Iterator[ChatSession]:
86
+ """
87
+ Lazy load the chat sessions from the iterable of run IDs.
88
+
89
+ This method fetches the runs and converts them to chat sessions on-the-fly,
90
+ yielding one session at a time.
91
+
92
+ :return: Iterator of chat sessions containing messages.
93
+ """
94
+ from langsmith.schemas import Run
95
+
96
+ for run_obj in self.runs:
97
+ try:
98
+ if hasattr(run_obj, "id"):
99
+ run = run_obj
100
+ else:
101
+ run = self.client.read_run(run_obj)
102
+ session = self._load_single_chat_session(cast(Run, run))
103
+ yield session
104
+ except ValueError as e:
105
+ logger.warning(f"Could not load run {run_obj}: {repr(e)}")
106
+ continue
107
+
108
+
109
+ class LangSmithDatasetChatLoader(BaseChatLoader):
110
+ """
111
+ Load chat sessions from a LangSmith dataset with the "chat" data type.
112
+
113
+ Attributes:
114
+ dataset_name (str): The name of the LangSmith dataset.
115
+ client (Client): Instance of LangSmith client for fetching data.
116
+ """
117
+
118
+ def __init__(self, *, dataset_name: str, client: Optional["Client"] = None):
119
+ """
120
+ Initialize a new LangSmithChatDatasetLoader instance.
121
+
122
+ :param dataset_name: The name of the LangSmith dataset.
123
+ :param client: An instance of LangSmith client; if not provided,
124
+ a new client instance will be created.
125
+ """
126
+ try:
127
+ from langsmith.client import Client
128
+ except ImportError as e:
129
+ raise ImportError(
130
+ "The LangSmith client is required to load LangSmith datasets.\n"
131
+ "Please install it with `pip install langsmith`"
132
+ ) from e
133
+
134
+ self.dataset_name = dataset_name
135
+ self.client = client or Client()
136
+
137
+ def lazy_load(self) -> Iterator[ChatSession]:
138
+ """
139
+ Lazy load the chat sessions from the specified LangSmith dataset.
140
+
141
+ This method fetches the chat data from the dataset and
142
+ converts each data point to chat sessions on-the-fly,
143
+ yielding one session at a time.
144
+
145
+ :return: Iterator of chat sessions containing messages.
146
+ """
147
+ from langchain_community.adapters import openai as oai_adapter
148
+
149
+ data = self.client.read_dataset_openai_finetuning(
150
+ dataset_name=self.dataset_name
151
+ )
152
+ for data_point in data:
153
+ yield ChatSession(
154
+ messages=[
155
+ oai_adapter.convert_dict_to_message(m)
156
+ for m in data_point.get("messages", [])
157
+ ],
158
+ functions=data_point.get("functions"),
159
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/slack.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import re
4
+ import zipfile
5
+ from pathlib import Path
6
+ from typing import Dict, Iterator, List, Union
7
+
8
+ from langchain_core.chat_loaders import BaseChatLoader
9
+ from langchain_core.chat_sessions import ChatSession
10
+ from langchain_core.messages import AIMessage, HumanMessage
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class SlackChatLoader(BaseChatLoader):
16
+ """Load `Slack` conversations from a dump zip file."""
17
+
18
+ def __init__(
19
+ self,
20
+ path: Union[str, Path],
21
+ ):
22
+ """
23
+ Initialize the chat loader with the path to the exported Slack dump zip file.
24
+
25
+ :param path: Path to the exported Slack dump zip file.
26
+ """
27
+ self.zip_path = path if isinstance(path, Path) else Path(path)
28
+ if not self.zip_path.exists():
29
+ raise FileNotFoundError(f"File {self.zip_path} not found")
30
+
31
+ @staticmethod
32
+ def _load_single_chat_session(messages: List[Dict]) -> ChatSession:
33
+ results: List[Union[AIMessage, HumanMessage]] = []
34
+ previous_sender = None
35
+ for message in messages:
36
+ if not isinstance(message, dict):
37
+ continue
38
+ text = message.get("text", "")
39
+ timestamp = message.get("ts", "")
40
+ sender = message.get("user", "")
41
+ if not sender:
42
+ continue
43
+ skip_pattern = re.compile(
44
+ r"<@U\d+> has joined the channel", flags=re.IGNORECASE
45
+ )
46
+ if skip_pattern.match(text):
47
+ continue
48
+ if sender == previous_sender:
49
+ results[-1].content += "\n\n" + text
50
+ results[-1].additional_kwargs["events"].append(
51
+ {"message_time": timestamp}
52
+ )
53
+ else:
54
+ results.append(
55
+ HumanMessage(
56
+ role=sender,
57
+ content=text,
58
+ additional_kwargs={
59
+ "sender": sender,
60
+ "events": [{"message_time": timestamp}],
61
+ },
62
+ )
63
+ )
64
+ previous_sender = sender
65
+ return ChatSession(messages=results)
66
+
67
+ @staticmethod
68
+ def _read_json(zip_file: zipfile.ZipFile, file_path: str) -> List[dict]:
69
+ """Read JSON data from a zip subfile."""
70
+ with zip_file.open(file_path, "r") as f:
71
+ data = json.load(f)
72
+ if not isinstance(data, list):
73
+ raise ValueError(f"Expected list of dictionaries, got {type(data)}")
74
+ return data
75
+
76
+ def lazy_load(self) -> Iterator[ChatSession]:
77
+ """
78
+ Lazy load the chat sessions from the Slack dump file and yield them
79
+ in the required format.
80
+
81
+ :return: Iterator of chat sessions containing messages.
82
+ """
83
+ with zipfile.ZipFile(str(self.zip_path), "r") as zip_file:
84
+ for file_path in zip_file.namelist():
85
+ if file_path.endswith(".json"):
86
+ messages = self._read_json(zip_file, file_path)
87
+ yield self._load_single_chat_session(messages)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/telegram.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ import tempfile
5
+ import zipfile
6
+ from pathlib import Path
7
+ from typing import Iterator, List, Union
8
+
9
+ from langchain_core.chat_loaders import BaseChatLoader
10
+ from langchain_core.chat_sessions import ChatSession
11
+ from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class TelegramChatLoader(BaseChatLoader):
17
+ """Load `telegram` conversations to LangChain chat messages.
18
+
19
+ To export, use the Telegram Desktop app from
20
+ https://desktop.telegram.org/, select a conversation, click the three dots
21
+ in the top right corner, and select "Export chat history". Then select
22
+ "Machine-readable JSON" (preferred) to export. Note: the 'lite' versions of
23
+ the desktop app (like "Telegram for MacOS") do not support exporting chat
24
+ history.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ path: Union[str, Path],
30
+ ):
31
+ """Initialize the TelegramChatLoader.
32
+
33
+ Args:
34
+ path (Union[str, Path]): Path to the exported Telegram chat zip,
35
+ directory, json, or HTML file.
36
+ """
37
+ self.path = path if isinstance(path, str) else str(path)
38
+
39
+ @staticmethod
40
+ def _load_single_chat_session_html(file_path: str) -> ChatSession:
41
+ """Load a single chat session from an HTML file.
42
+
43
+ Args:
44
+ file_path (str): Path to the HTML file.
45
+
46
+ Returns:
47
+ ChatSession: The loaded chat session.
48
+ """
49
+ try:
50
+ from bs4 import BeautifulSoup
51
+ except ImportError:
52
+ raise ImportError(
53
+ "Please install the 'beautifulsoup4' package to load"
54
+ " Telegram HTML files. You can do this by running"
55
+ "'pip install beautifulsoup4' in your terminal."
56
+ )
57
+ with open(file_path, "r", encoding="utf-8") as file:
58
+ soup = BeautifulSoup(file, "html.parser")
59
+
60
+ results: List[Union[HumanMessage, AIMessage]] = []
61
+ previous_sender = None
62
+ for message in soup.select(".message.default"):
63
+ timestamp = message.select_one(".pull_right.date.details")["title"] # type: ignore[index]
64
+ from_name_element = message.select_one(".from_name")
65
+ if from_name_element is None and previous_sender is None:
66
+ logger.debug("from_name not found in message")
67
+ continue
68
+ elif from_name_element is None:
69
+ from_name = previous_sender
70
+ else:
71
+ from_name = from_name_element.text.strip()
72
+ text = message.select_one(".text").text.strip() # type: ignore[union-attr]
73
+ results.append(
74
+ HumanMessage(
75
+ content=text,
76
+ additional_kwargs={
77
+ "sender": from_name,
78
+ "events": [{"message_time": timestamp}],
79
+ },
80
+ )
81
+ )
82
+ previous_sender = from_name
83
+
84
+ return ChatSession(messages=results)
85
+
86
+ @staticmethod
87
+ def _load_single_chat_session_json(file_path: str) -> ChatSession:
88
+ """Load a single chat session from a JSON file.
89
+
90
+ Args:
91
+ file_path (str): Path to the JSON file.
92
+
93
+ Returns:
94
+ ChatSession: The loaded chat session.
95
+ """
96
+ with open(file_path, "r", encoding="utf-8") as file:
97
+ data = json.load(file)
98
+
99
+ messages = data.get("messages", [])
100
+ results: List[BaseMessage] = []
101
+ for message in messages:
102
+ text = message.get("text", "")
103
+ timestamp = message.get("date", "")
104
+ from_name = message.get("from", "")
105
+ if from_name is None:
106
+ from_name = "Deleted Account"
107
+
108
+ results.append(
109
+ HumanMessage(
110
+ content=text,
111
+ additional_kwargs={
112
+ "sender": from_name,
113
+ "events": [{"message_time": timestamp}],
114
+ },
115
+ )
116
+ )
117
+
118
+ return ChatSession(messages=results)
119
+
120
+ @staticmethod
121
+ def _iterate_files(path: str) -> Iterator[str]:
122
+ """Iterate over files in a directory or zip file.
123
+
124
+ Args:
125
+ path (str): Path to the directory or zip file.
126
+
127
+ Yields:
128
+ str: Path to each file.
129
+ """
130
+ if os.path.isfile(path) and path.endswith((".html", ".json")):
131
+ yield path
132
+ elif os.path.isdir(path):
133
+ for root, _, files in os.walk(path):
134
+ for file in files:
135
+ if file.endswith((".html", ".json")):
136
+ yield os.path.join(root, file)
137
+ elif zipfile.is_zipfile(path):
138
+ with zipfile.ZipFile(path) as zip_file:
139
+ for file in zip_file.namelist():
140
+ if file.endswith((".html", ".json")):
141
+ with tempfile.TemporaryDirectory() as temp_dir:
142
+ yield zip_file.extract(file, path=temp_dir)
143
+
144
+ def lazy_load(self) -> Iterator[ChatSession]:
145
+ """Lazy load the messages from the chat file and yield them
146
+ in as chat sessions.
147
+
148
+ Yields:
149
+ ChatSession: The loaded chat session.
150
+ """
151
+ for file_path in self._iterate_files(self.path):
152
+ if file_path.endswith(".html"):
153
+ yield self._load_single_chat_session_html(file_path)
154
+ elif file_path.endswith(".json"):
155
+ yield self._load_single_chat_session_json(file_path)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/utils.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for chat loaders."""
2
+
3
+ from copy import deepcopy
4
+ from typing import Iterable, Iterator, List
5
+
6
+ from langchain_core.chat_sessions import ChatSession
7
+ from langchain_core.messages import AIMessage, BaseMessage
8
+
9
+
10
+ def merge_chat_runs_in_session(
11
+ chat_session: ChatSession, delimiter: str = "\n\n"
12
+ ) -> ChatSession:
13
+ """Merge chat runs together in a chat session.
14
+
15
+ A chat run is a sequence of messages from the same sender.
16
+
17
+ Args:
18
+ chat_session: A chat session.
19
+
20
+ Returns:
21
+ A chat session with merged chat runs.
22
+ """
23
+ messages: List[BaseMessage] = []
24
+ for message in chat_session["messages"]:
25
+ if isinstance(message.content, list):
26
+ text = ""
27
+ for content in message.content:
28
+ if isinstance(content, dict):
29
+ text += content.get("text", "") or ""
30
+ else:
31
+ text += content
32
+ message.content = text
33
+ if not isinstance(message.content, str):
34
+ raise ValueError(
35
+ "Chat Loaders only support messages with content type string, "
36
+ f"got {message.content}"
37
+ )
38
+ if not messages:
39
+ messages.append(deepcopy(message))
40
+ elif (
41
+ isinstance(message, type(messages[-1]))
42
+ and messages[-1].additional_kwargs.get("sender") is not None
43
+ and messages[-1].additional_kwargs["sender"]
44
+ == message.additional_kwargs.get("sender")
45
+ ):
46
+ if not isinstance(messages[-1].content, str):
47
+ raise ValueError(
48
+ "Chat Loaders only support messages with content type string, "
49
+ f"got {messages[-1].content}"
50
+ )
51
+ messages[-1].content = (
52
+ messages[-1].content + delimiter + message.content
53
+ ).strip()
54
+ messages[-1].additional_kwargs.get("events", []).extend(
55
+ message.additional_kwargs.get("events") or []
56
+ )
57
+ else:
58
+ messages.append(deepcopy(message))
59
+ return ChatSession(messages=messages)
60
+
61
+
62
+ def merge_chat_runs(chat_sessions: Iterable[ChatSession]) -> Iterator[ChatSession]:
63
+ """Merge chat runs together.
64
+
65
+ A chat run is a sequence of messages from the same sender.
66
+
67
+ Args:
68
+ chat_sessions: A list of chat sessions.
69
+
70
+ Returns:
71
+ A list of chat sessions with merged chat runs.
72
+ """
73
+ for chat_session in chat_sessions:
74
+ yield merge_chat_runs_in_session(chat_session)
75
+
76
+
77
+ def map_ai_messages_in_session(chat_sessions: ChatSession, sender: str) -> ChatSession:
78
+ """Convert messages from the specified 'sender' to AI messages.
79
+
80
+ This is useful for fine-tuning the AI to adapt to your voice.
81
+ """
82
+ messages = []
83
+ num_converted = 0
84
+ for message in chat_sessions["messages"]:
85
+ if message.additional_kwargs.get("sender") == sender:
86
+ message = AIMessage(
87
+ content=message.content,
88
+ additional_kwargs=message.additional_kwargs.copy(),
89
+ example=getattr(message, "example", None),
90
+ )
91
+ num_converted += 1
92
+ messages.append(message)
93
+ return ChatSession(messages=messages)
94
+
95
+
96
+ def map_ai_messages(
97
+ chat_sessions: Iterable[ChatSession], sender: str
98
+ ) -> Iterator[ChatSession]:
99
+ """Convert messages from the specified 'sender' to AI messages.
100
+
101
+ This is useful for fine-tuning the AI to adapt to your voice.
102
+ """
103
+ for chat_session in chat_sessions:
104
+ yield map_ai_messages_in_session(chat_session, sender)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/whatsapp.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import re
4
+ import zipfile
5
+ from typing import Iterator, List, Union
6
+
7
+ from langchain_core.chat_loaders import BaseChatLoader
8
+ from langchain_core.chat_sessions import ChatSession
9
+ from langchain_core.messages import AIMessage, HumanMessage
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class WhatsAppChatLoader(BaseChatLoader):
15
+ """Load `WhatsApp` conversations from a dump zip file or directory."""
16
+
17
+ def __init__(self, path: str):
18
+ """Initialize the WhatsAppChatLoader.
19
+
20
+ Args:
21
+ path (str): Path to the exported WhatsApp chat
22
+ zip directory, folder, or file.
23
+
24
+ To generate the dump, open the chat, click the three dots in the top
25
+ right corner, and select "More". Then select "Export chat" and
26
+ choose "Without media".
27
+ """
28
+ self.path = path
29
+ ignore_lines = [
30
+ "This message was deleted",
31
+ "<Media omitted>",
32
+ "image omitted",
33
+ "Messages and calls are end-to-end encrypted. No one outside of this chat,"
34
+ " not even WhatsApp, can read or listen to them.",
35
+ ]
36
+ self._ignore_lines = re.compile(
37
+ r"(" + "|".join([r"\u200E*" + line for line in ignore_lines]) + r")",
38
+ flags=re.IGNORECASE,
39
+ )
40
+ self._message_line_regex = re.compile(
41
+ r"\u200E*\[?(\d{1,2}/\d{1,2}/\d{2,4}, \d{1,2}:\d{2}:\d{2} (?:AM|PM))\]?[ \u200E]*([^:]+): (.+)", # noqa
42
+ flags=re.IGNORECASE,
43
+ )
44
+
45
+ def _load_single_chat_session(self, file_path: str) -> ChatSession:
46
+ """Load a single chat session from a file.
47
+
48
+ Args:
49
+ file_path (str): Path to the chat file.
50
+
51
+ Returns:
52
+ ChatSession: The loaded chat session.
53
+ """
54
+ with open(file_path, "r", encoding="utf-8") as file:
55
+ txt = file.read()
56
+
57
+ # Split messages by newlines, but keep multi-line messages grouped
58
+ chat_lines: List[str] = []
59
+ current_message = ""
60
+ for line in txt.split("\n"):
61
+ if self._message_line_regex.match(line):
62
+ if current_message:
63
+ chat_lines.append(current_message)
64
+ current_message = line
65
+ else:
66
+ current_message += " " + line.strip()
67
+ if current_message:
68
+ chat_lines.append(current_message)
69
+ results: List[Union[HumanMessage, AIMessage]] = []
70
+ for line in chat_lines:
71
+ result = self._message_line_regex.match(line.strip())
72
+ if result:
73
+ timestamp, sender, text = result.groups()
74
+ if not self._ignore_lines.match(text.strip()):
75
+ results.append(
76
+ HumanMessage(
77
+ role=sender,
78
+ content=text,
79
+ additional_kwargs={
80
+ "sender": sender,
81
+ "events": [{"message_time": timestamp}],
82
+ },
83
+ )
84
+ )
85
+ else:
86
+ logger.debug(f"Could not parse line: {line}")
87
+ return ChatSession(messages=results)
88
+
89
+ @staticmethod
90
+ def _iterate_files(path: str) -> Iterator[str]:
91
+ """Iterate over the files in a directory or zip file.
92
+
93
+ Args:
94
+ path (str): Path to the directory or zip file.
95
+
96
+ Yields:
97
+ str: The path to each file.
98
+ """
99
+ if os.path.isfile(path):
100
+ yield path
101
+ elif os.path.isdir(path):
102
+ for root, _, files in os.walk(path):
103
+ for file in files:
104
+ if file.endswith(".txt"):
105
+ yield os.path.join(root, file)
106
+ elif zipfile.is_zipfile(path):
107
+ with zipfile.ZipFile(path) as zip_file:
108
+ for file in zip_file.namelist():
109
+ if file.endswith(".txt"):
110
+ yield zip_file.extract(file)
111
+
112
+ def lazy_load(self) -> Iterator[ChatSession]:
113
+ """Lazy load the messages from the chat file and yield
114
+ them as chat sessions.
115
+
116
+ Yields:
117
+ Iterator[ChatSession]: The loaded chat sessions.
118
+ """
119
+ yield self._load_single_chat_session(self.path)
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/__init__.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """**Chat message history** stores a history of the message interactions in a chat.
2
+
3
+
4
+ **Class hierarchy:**
5
+
6
+ .. code-block::
7
+
8
+ BaseChatMessageHistory --> <name>ChatMessageHistory # Examples: FileChatMessageHistory, PostgresChatMessageHistory
9
+
10
+ **Main helpers:**
11
+
12
+ .. code-block::
13
+
14
+ AIMessage, HumanMessage, BaseMessage
15
+
16
+ """ # noqa: E501
17
+
18
+ import importlib
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ if TYPE_CHECKING:
22
+ from langchain_community.chat_message_histories.astradb import (
23
+ AstraDBChatMessageHistory,
24
+ )
25
+ from langchain_community.chat_message_histories.cassandra import (
26
+ CassandraChatMessageHistory,
27
+ )
28
+ from langchain_community.chat_message_histories.cosmos_db import (
29
+ CosmosDBChatMessageHistory,
30
+ )
31
+ from langchain_community.chat_message_histories.dynamodb import (
32
+ DynamoDBChatMessageHistory,
33
+ )
34
+ from langchain_community.chat_message_histories.elasticsearch import (
35
+ ElasticsearchChatMessageHistory,
36
+ )
37
+ from langchain_community.chat_message_histories.file import (
38
+ FileChatMessageHistory,
39
+ )
40
+ from langchain_community.chat_message_histories.firestore import (
41
+ FirestoreChatMessageHistory,
42
+ )
43
+ from langchain_community.chat_message_histories.in_memory import (
44
+ ChatMessageHistory,
45
+ )
46
+ from langchain_community.chat_message_histories.kafka import (
47
+ KafkaChatMessageHistory,
48
+ )
49
+ from langchain_community.chat_message_histories.momento import (
50
+ MomentoChatMessageHistory,
51
+ )
52
+ from langchain_community.chat_message_histories.mongodb import (
53
+ MongoDBChatMessageHistory,
54
+ )
55
+ from langchain_community.chat_message_histories.neo4j import (
56
+ Neo4jChatMessageHistory,
57
+ )
58
+ from langchain_community.chat_message_histories.postgres import (
59
+ PostgresChatMessageHistory,
60
+ )
61
+ from langchain_community.chat_message_histories.redis import (
62
+ RedisChatMessageHistory,
63
+ )
64
+ from langchain_community.chat_message_histories.rocksetdb import (
65
+ RocksetChatMessageHistory,
66
+ )
67
+ from langchain_community.chat_message_histories.singlestoredb import (
68
+ SingleStoreDBChatMessageHistory,
69
+ )
70
+ from langchain_community.chat_message_histories.sql import (
71
+ SQLChatMessageHistory,
72
+ )
73
+ from langchain_community.chat_message_histories.streamlit import (
74
+ StreamlitChatMessageHistory,
75
+ )
76
+ from langchain_community.chat_message_histories.tidb import (
77
+ TiDBChatMessageHistory,
78
+ )
79
+ from langchain_community.chat_message_histories.upstash_redis import (
80
+ UpstashRedisChatMessageHistory,
81
+ )
82
+ from langchain_community.chat_message_histories.xata import (
83
+ XataChatMessageHistory,
84
+ )
85
+ from langchain_community.chat_message_histories.zep import (
86
+ ZepChatMessageHistory,
87
+ )
88
+ from langchain_community.chat_message_histories.zep_cloud import (
89
+ ZepCloudChatMessageHistory,
90
+ )
91
+
92
+ __all__ = [
93
+ "AstraDBChatMessageHistory",
94
+ "CassandraChatMessageHistory",
95
+ "ChatMessageHistory",
96
+ "CosmosDBChatMessageHistory",
97
+ "DynamoDBChatMessageHistory",
98
+ "ElasticsearchChatMessageHistory",
99
+ "FileChatMessageHistory",
100
+ "FirestoreChatMessageHistory",
101
+ "MomentoChatMessageHistory",
102
+ "MongoDBChatMessageHistory",
103
+ "Neo4jChatMessageHistory",
104
+ "PostgresChatMessageHistory",
105
+ "RedisChatMessageHistory",
106
+ "RocksetChatMessageHistory",
107
+ "SQLChatMessageHistory",
108
+ "SingleStoreDBChatMessageHistory",
109
+ "StreamlitChatMessageHistory",
110
+ "TiDBChatMessageHistory",
111
+ "UpstashRedisChatMessageHistory",
112
+ "XataChatMessageHistory",
113
+ "ZepChatMessageHistory",
114
+ "ZepCloudChatMessageHistory",
115
+ "KafkaChatMessageHistory",
116
+ ]
117
+
118
+ _module_lookup = {
119
+ "AstraDBChatMessageHistory": "langchain_community.chat_message_histories.astradb",
120
+ "CassandraChatMessageHistory": "langchain_community.chat_message_histories.cassandra", # noqa: E501
121
+ "ChatMessageHistory": "langchain_community.chat_message_histories.in_memory",
122
+ "CosmosDBChatMessageHistory": "langchain_community.chat_message_histories.cosmos_db", # noqa: E501
123
+ "DynamoDBChatMessageHistory": "langchain_community.chat_message_histories.dynamodb",
124
+ "ElasticsearchChatMessageHistory": "langchain_community.chat_message_histories.elasticsearch", # noqa: E501
125
+ "FileChatMessageHistory": "langchain_community.chat_message_histories.file",
126
+ "FirestoreChatMessageHistory": "langchain_community.chat_message_histories.firestore", # noqa: E501
127
+ "MomentoChatMessageHistory": "langchain_community.chat_message_histories.momento",
128
+ "MongoDBChatMessageHistory": "langchain_community.chat_message_histories.mongodb",
129
+ "Neo4jChatMessageHistory": "langchain_community.chat_message_histories.neo4j",
130
+ "PostgresChatMessageHistory": "langchain_community.chat_message_histories.postgres",
131
+ "RedisChatMessageHistory": "langchain_community.chat_message_histories.redis",
132
+ "RocksetChatMessageHistory": "langchain_community.chat_message_histories.rocksetdb",
133
+ "SQLChatMessageHistory": "langchain_community.chat_message_histories.sql",
134
+ "SingleStoreDBChatMessageHistory": "langchain_community.chat_message_histories.singlestoredb", # noqa: E501
135
+ "StreamlitChatMessageHistory": "langchain_community.chat_message_histories.streamlit", # noqa: E501
136
+ "TiDBChatMessageHistory": "langchain_community.chat_message_histories.tidb",
137
+ "UpstashRedisChatMessageHistory": "langchain_community.chat_message_histories.upstash_redis", # noqa: E501
138
+ "XataChatMessageHistory": "langchain_community.chat_message_histories.xata",
139
+ "ZepChatMessageHistory": "langchain_community.chat_message_histories.zep",
140
+ "ZepCloudChatMessageHistory": "langchain_community.chat_message_histories.zep_cloud", # noqa: E501
141
+ "KafkaChatMessageHistory": "langchain_community.chat_message_histories.kafka",
142
+ }
143
+
144
+
145
+ def __getattr__(name: str) -> Any:
146
+ if name in _module_lookup:
147
+ module = importlib.import_module(_module_lookup[name])
148
+ return getattr(module, name)
149
+ raise AttributeError(f"module {__name__} has no attribute {name}")
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/astradb.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Astra DB - based chat message history, based on astrapy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ from typing import TYPE_CHECKING, List, Optional, Sequence
8
+
9
+ from langchain_community.utilities.astradb import (
10
+ SetupMode,
11
+ _AstraDBCollectionEnvironment,
12
+ )
13
+
14
+ if TYPE_CHECKING:
15
+ from astrapy.db import AstraDB, AsyncAstraDB
16
+
17
+ from langchain_core._api.deprecation import deprecated
18
+ from langchain_core.chat_history import BaseChatMessageHistory
19
+ from langchain_core.messages import (
20
+ BaseMessage,
21
+ message_to_dict,
22
+ messages_from_dict,
23
+ )
24
+
25
+ DEFAULT_COLLECTION_NAME = "langchain_message_store"
26
+
27
+
28
+ @deprecated(
29
+ since="0.0.25",
30
+ removal="1.0",
31
+ alternative_import="langchain_astradb.AstraDBChatMessageHistory",
32
+ )
33
+ class AstraDBChatMessageHistory(BaseChatMessageHistory):
34
+ def __init__(
35
+ self,
36
+ *,
37
+ session_id: str,
38
+ collection_name: str = DEFAULT_COLLECTION_NAME,
39
+ token: Optional[str] = None,
40
+ api_endpoint: Optional[str] = None,
41
+ astra_db_client: Optional[AstraDB] = None,
42
+ async_astra_db_client: Optional[AsyncAstraDB] = None,
43
+ namespace: Optional[str] = None,
44
+ setup_mode: SetupMode = SetupMode.SYNC,
45
+ pre_delete_collection: bool = False,
46
+ ) -> None:
47
+ """Chat message history that stores history in Astra DB.
48
+
49
+ Args:
50
+ session_id: arbitrary key that is used to store the messages
51
+ of a single chat session.
52
+ collection_name: name of the Astra DB collection to create/use.
53
+ token: API token for Astra DB usage.
54
+ api_endpoint: full URL to the API endpoint,
55
+ such as "https://<DB-ID>-us-east1.apps.astra.datastax.com".
56
+ astra_db_client: *alternative to token+api_endpoint*,
57
+ you can pass an already-created 'astrapy.db.AstraDB' instance.
58
+ async_astra_db_client: *alternative to token+api_endpoint*,
59
+ you can pass an already-created 'astrapy.db.AsyncAstraDB' instance.
60
+ namespace: namespace (aka keyspace) where the
61
+ collection is created. Defaults to the database's "default namespace".
62
+ setup_mode: mode used to create the Astra DB collection (SYNC, ASYNC or
63
+ OFF).
64
+ pre_delete_collection: whether to delete the collection
65
+ before creating it. If False and the collection already exists,
66
+ the collection will be used as is.
67
+ """
68
+ self.astra_env = _AstraDBCollectionEnvironment(
69
+ collection_name=collection_name,
70
+ token=token,
71
+ api_endpoint=api_endpoint,
72
+ astra_db_client=astra_db_client,
73
+ async_astra_db_client=async_astra_db_client,
74
+ namespace=namespace,
75
+ setup_mode=setup_mode,
76
+ pre_delete_collection=pre_delete_collection,
77
+ )
78
+
79
+ self.collection = self.astra_env.collection
80
+ self.async_collection = self.astra_env.async_collection
81
+
82
+ self.session_id = session_id
83
+ self.collection_name = collection_name
84
+
85
+ @property
86
+ def messages(self) -> List[BaseMessage]:
87
+ """Retrieve all session messages from DB"""
88
+ self.astra_env.ensure_db_setup()
89
+ message_blobs = [
90
+ doc["body_blob"]
91
+ for doc in sorted(
92
+ self.collection.paginated_find(
93
+ filter={
94
+ "session_id": self.session_id,
95
+ },
96
+ projection={
97
+ "timestamp": 1,
98
+ "body_blob": 1,
99
+ },
100
+ ),
101
+ key=lambda _doc: _doc["timestamp"],
102
+ )
103
+ ]
104
+ items = [json.loads(message_blob) for message_blob in message_blobs]
105
+ messages = messages_from_dict(items)
106
+ return messages
107
+
108
+ @messages.setter
109
+ def messages(self, messages: List[BaseMessage]) -> None:
110
+ raise NotImplementedError("Use add_messages instead")
111
+
112
+ async def aget_messages(self) -> List[BaseMessage]:
113
+ await self.astra_env.aensure_db_setup()
114
+ docs = self.async_collection.paginated_find(
115
+ filter={
116
+ "session_id": self.session_id,
117
+ },
118
+ projection={
119
+ "timestamp": 1,
120
+ "body_blob": 1,
121
+ },
122
+ )
123
+ sorted_docs = sorted(
124
+ [doc async for doc in docs],
125
+ key=lambda _doc: _doc["timestamp"],
126
+ )
127
+ message_blobs = [doc["body_blob"] for doc in sorted_docs]
128
+ items = [json.loads(message_blob) for message_blob in message_blobs]
129
+ messages = messages_from_dict(items)
130
+ return messages
131
+
132
+ def add_messages(self, messages: Sequence[BaseMessage]) -> None:
133
+ self.astra_env.ensure_db_setup()
134
+ docs = [
135
+ {
136
+ "timestamp": time.time(),
137
+ "session_id": self.session_id,
138
+ "body_blob": json.dumps(message_to_dict(message)),
139
+ }
140
+ for message in messages
141
+ ]
142
+ self.collection.chunked_insert_many(docs)
143
+
144
+ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:
145
+ await self.astra_env.aensure_db_setup()
146
+ docs = [
147
+ {
148
+ "timestamp": time.time(),
149
+ "session_id": self.session_id,
150
+ "body_blob": json.dumps(message_to_dict(message)),
151
+ }
152
+ for message in messages
153
+ ]
154
+ await self.async_collection.chunked_insert_many(docs)
155
+
156
+ def clear(self) -> None:
157
+ self.astra_env.ensure_db_setup()
158
+ self.collection.delete_many(filter={"session_id": self.session_id})
159
+
160
+ async def aclear(self) -> None:
161
+ await self.astra_env.aensure_db_setup()
162
+ await self.async_collection.delete_many(filter={"session_id": self.session_id})
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/cassandra.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cassandra-based chat message history, based on cassIO."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import uuid
7
+ from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence
8
+
9
+ from langchain_community.utilities.cassandra import SetupMode
10
+
11
+ if TYPE_CHECKING:
12
+ from cassandra.cluster import Session
13
+ from cassio.table.table_types import RowType
14
+
15
+ from langchain_core.chat_history import BaseChatMessageHistory
16
+ from langchain_core.messages import (
17
+ BaseMessage,
18
+ message_to_dict,
19
+ messages_from_dict,
20
+ )
21
+
22
+ DEFAULT_TABLE_NAME = "message_store"
23
+ DEFAULT_TTL_SECONDS = None
24
+
25
+
26
+ def _rows_to_messages(rows: Iterable[RowType]) -> List[BaseMessage]:
27
+ message_blobs = [row["body_blob"] for row in rows][::-1]
28
+ items = [json.loads(message_blob) for message_blob in message_blobs]
29
+ messages = messages_from_dict(items)
30
+ return messages
31
+
32
+
33
+ class CassandraChatMessageHistory(BaseChatMessageHistory):
34
+ """Chat message history that is backed by Cassandra."""
35
+
36
+ def __init__(
37
+ self,
38
+ session_id: str,
39
+ session: Optional[Session] = None,
40
+ keyspace: Optional[str] = None,
41
+ table_name: str = DEFAULT_TABLE_NAME,
42
+ ttl_seconds: Optional[int] = DEFAULT_TTL_SECONDS,
43
+ *,
44
+ setup_mode: SetupMode = SetupMode.SYNC,
45
+ ) -> None:
46
+ """
47
+ Initialize a new instance of CassandraChatMessageHistory.
48
+
49
+ Args:
50
+ session_id: arbitrary key that is used to store the messages
51
+ of a single chat session.
52
+ session: Cassandra driver session.
53
+ If not provided, it is resolved from cassio.
54
+ keyspace: Cassandra key space. If not provided, it is resolved from cassio.
55
+ table_name: name of the table to use.
56
+ ttl_seconds: time-to-live (seconds) for automatic expiration
57
+ of stored entries. None (default) for no expiration.
58
+ setup_mode: mode used to create the Cassandra table (SYNC, ASYNC or OFF).
59
+ """
60
+ try:
61
+ from cassio.table import ClusteredCassandraTable
62
+ except (ImportError, ModuleNotFoundError):
63
+ raise ImportError(
64
+ "Could not import cassio python package. "
65
+ "Please install it with `pip install cassio`."
66
+ )
67
+ self.session_id = session_id
68
+ self.ttl_seconds = ttl_seconds
69
+ kwargs: Dict[str, Any] = {}
70
+ if setup_mode == SetupMode.ASYNC:
71
+ kwargs["async_setup"] = True
72
+ self.table = ClusteredCassandraTable(
73
+ session=session,
74
+ keyspace=keyspace,
75
+ table=table_name,
76
+ ttl_seconds=ttl_seconds,
77
+ primary_key_type=["TEXT", "TIMEUUID"],
78
+ ordering_in_partition="DESC",
79
+ skip_provisioning=setup_mode == SetupMode.OFF,
80
+ **kwargs,
81
+ )
82
+
83
+ @property
84
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
85
+ """Retrieve all session messages from DB"""
86
+ # The latest are returned, in chronological order
87
+ rows = self.table.get_partition(
88
+ partition_id=self.session_id,
89
+ )
90
+ return _rows_to_messages(rows)
91
+
92
+ async def aget_messages(self) -> List[BaseMessage]:
93
+ """Retrieve all session messages from DB"""
94
+ # The latest are returned, in chronological order
95
+ rows = await self.table.aget_partition(
96
+ partition_id=self.session_id,
97
+ )
98
+ return _rows_to_messages(rows)
99
+
100
+ def add_message(self, message: BaseMessage) -> None:
101
+ """Write a message to the table
102
+
103
+ Args:
104
+ message: A message to write.
105
+ """
106
+ this_row_id = uuid.uuid4()
107
+ self.table.put(
108
+ partition_id=self.session_id,
109
+ row_id=this_row_id,
110
+ body_blob=json.dumps(message_to_dict(message)),
111
+ ttl_seconds=self.ttl_seconds,
112
+ )
113
+
114
+ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:
115
+ for message in messages:
116
+ this_row_id = uuid.uuid4()
117
+ await self.table.aput(
118
+ partition_id=self.session_id,
119
+ row_id=this_row_id,
120
+ body_blob=json.dumps(message_to_dict(message)),
121
+ ttl_seconds=self.ttl_seconds,
122
+ )
123
+
124
+ def clear(self) -> None:
125
+ """Clear session memory from DB"""
126
+ self.table.delete_partition(self.session_id)
127
+
128
+ async def aclear(self) -> None:
129
+ """Clear session memory from DB"""
130
+ await self.table.adelete_partition(self.session_id)