langroid 0.31.2__py3-none-any.whl → 0.33.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. {langroid-0.31.2.dist-info → langroid-0.33.3.dist-info}/METADATA +150 -124
  2. langroid-0.33.3.dist-info/RECORD +7 -0
  3. {langroid-0.31.2.dist-info → langroid-0.33.3.dist-info}/WHEEL +1 -1
  4. langroid-0.33.3.dist-info/entry_points.txt +4 -0
  5. pyproject.toml +317 -212
  6. langroid/__init__.py +0 -106
  7. langroid/agent/.chainlit/config.toml +0 -121
  8. langroid/agent/.chainlit/translations/bn.json +0 -231
  9. langroid/agent/.chainlit/translations/en-US.json +0 -229
  10. langroid/agent/.chainlit/translations/gu.json +0 -231
  11. langroid/agent/.chainlit/translations/he-IL.json +0 -231
  12. langroid/agent/.chainlit/translations/hi.json +0 -231
  13. langroid/agent/.chainlit/translations/kn.json +0 -231
  14. langroid/agent/.chainlit/translations/ml.json +0 -231
  15. langroid/agent/.chainlit/translations/mr.json +0 -231
  16. langroid/agent/.chainlit/translations/ta.json +0 -231
  17. langroid/agent/.chainlit/translations/te.json +0 -231
  18. langroid/agent/.chainlit/translations/zh-CN.json +0 -229
  19. langroid/agent/__init__.py +0 -41
  20. langroid/agent/base.py +0 -1981
  21. langroid/agent/batch.py +0 -398
  22. langroid/agent/callbacks/__init__.py +0 -0
  23. langroid/agent/callbacks/chainlit.py +0 -598
  24. langroid/agent/chat_agent.py +0 -1899
  25. langroid/agent/chat_document.py +0 -454
  26. langroid/agent/helpers.py +0 -0
  27. langroid/agent/junk +0 -13
  28. langroid/agent/openai_assistant.py +0 -882
  29. langroid/agent/special/__init__.py +0 -59
  30. langroid/agent/special/arangodb/__init__.py +0 -0
  31. langroid/agent/special/arangodb/arangodb_agent.py +0 -656
  32. langroid/agent/special/arangodb/system_messages.py +0 -186
  33. langroid/agent/special/arangodb/tools.py +0 -107
  34. langroid/agent/special/arangodb/utils.py +0 -36
  35. langroid/agent/special/doc_chat_agent.py +0 -1466
  36. langroid/agent/special/lance_doc_chat_agent.py +0 -262
  37. langroid/agent/special/lance_rag/__init__.py +0 -9
  38. langroid/agent/special/lance_rag/critic_agent.py +0 -198
  39. langroid/agent/special/lance_rag/lance_rag_task.py +0 -82
  40. langroid/agent/special/lance_rag/query_planner_agent.py +0 -260
  41. langroid/agent/special/lance_tools.py +0 -61
  42. langroid/agent/special/neo4j/__init__.py +0 -0
  43. langroid/agent/special/neo4j/csv_kg_chat.py +0 -174
  44. langroid/agent/special/neo4j/neo4j_chat_agent.py +0 -433
  45. langroid/agent/special/neo4j/system_messages.py +0 -120
  46. langroid/agent/special/neo4j/tools.py +0 -32
  47. langroid/agent/special/relevance_extractor_agent.py +0 -127
  48. langroid/agent/special/retriever_agent.py +0 -56
  49. langroid/agent/special/sql/__init__.py +0 -17
  50. langroid/agent/special/sql/sql_chat_agent.py +0 -654
  51. langroid/agent/special/sql/utils/__init__.py +0 -21
  52. langroid/agent/special/sql/utils/description_extractors.py +0 -190
  53. langroid/agent/special/sql/utils/populate_metadata.py +0 -85
  54. langroid/agent/special/sql/utils/system_message.py +0 -35
  55. langroid/agent/special/sql/utils/tools.py +0 -64
  56. langroid/agent/special/table_chat_agent.py +0 -263
  57. langroid/agent/structured_message.py +0 -9
  58. langroid/agent/task.py +0 -2093
  59. langroid/agent/tool_message.py +0 -393
  60. langroid/agent/tools/__init__.py +0 -38
  61. langroid/agent/tools/duckduckgo_search_tool.py +0 -50
  62. langroid/agent/tools/file_tools.py +0 -234
  63. langroid/agent/tools/google_search_tool.py +0 -39
  64. langroid/agent/tools/metaphor_search_tool.py +0 -67
  65. langroid/agent/tools/orchestration.py +0 -303
  66. langroid/agent/tools/recipient_tool.py +0 -235
  67. langroid/agent/tools/retrieval_tool.py +0 -32
  68. langroid/agent/tools/rewind_tool.py +0 -137
  69. langroid/agent/tools/segment_extract_tool.py +0 -41
  70. langroid/agent/typed_task.py +0 -19
  71. langroid/agent/xml_tool_message.py +0 -382
  72. langroid/agent_config.py +0 -0
  73. langroid/cachedb/__init__.py +0 -17
  74. langroid/cachedb/base.py +0 -58
  75. langroid/cachedb/momento_cachedb.py +0 -108
  76. langroid/cachedb/redis_cachedb.py +0 -153
  77. langroid/embedding_models/__init__.py +0 -39
  78. langroid/embedding_models/base.py +0 -74
  79. langroid/embedding_models/clustering.py +0 -189
  80. langroid/embedding_models/models.py +0 -461
  81. langroid/embedding_models/protoc/__init__.py +0 -0
  82. langroid/embedding_models/protoc/embeddings.proto +0 -19
  83. langroid/embedding_models/protoc/embeddings_pb2.py +0 -33
  84. langroid/embedding_models/protoc/embeddings_pb2.pyi +0 -50
  85. langroid/embedding_models/protoc/embeddings_pb2_grpc.py +0 -79
  86. langroid/embedding_models/remote_embeds.py +0 -153
  87. langroid/exceptions.py +0 -65
  88. langroid/experimental/team-save.py +0 -391
  89. langroid/language_models/.chainlit/config.toml +0 -121
  90. langroid/language_models/.chainlit/translations/en-US.json +0 -231
  91. langroid/language_models/__init__.py +0 -53
  92. langroid/language_models/azure_openai.py +0 -153
  93. langroid/language_models/base.py +0 -678
  94. langroid/language_models/config.py +0 -18
  95. langroid/language_models/mock_lm.py +0 -124
  96. langroid/language_models/openai_gpt.py +0 -1923
  97. langroid/language_models/prompt_formatter/__init__.py +0 -16
  98. langroid/language_models/prompt_formatter/base.py +0 -40
  99. langroid/language_models/prompt_formatter/hf_formatter.py +0 -132
  100. langroid/language_models/prompt_formatter/llama2_formatter.py +0 -75
  101. langroid/language_models/utils.py +0 -147
  102. langroid/mytypes.py +0 -84
  103. langroid/parsing/__init__.py +0 -52
  104. langroid/parsing/agent_chats.py +0 -38
  105. langroid/parsing/code-parsing.md +0 -86
  106. langroid/parsing/code_parser.py +0 -121
  107. langroid/parsing/config.py +0 -0
  108. langroid/parsing/document_parser.py +0 -718
  109. langroid/parsing/image_text.py +0 -32
  110. langroid/parsing/para_sentence_split.py +0 -62
  111. langroid/parsing/parse_json.py +0 -155
  112. langroid/parsing/parser.py +0 -313
  113. langroid/parsing/repo_loader.py +0 -790
  114. langroid/parsing/routing.py +0 -36
  115. langroid/parsing/search.py +0 -275
  116. langroid/parsing/spider.py +0 -102
  117. langroid/parsing/table_loader.py +0 -94
  118. langroid/parsing/url_loader.py +0 -111
  119. langroid/parsing/url_loader_cookies.py +0 -73
  120. langroid/parsing/urls.py +0 -273
  121. langroid/parsing/utils.py +0 -373
  122. langroid/parsing/web_search.py +0 -155
  123. langroid/prompts/__init__.py +0 -9
  124. langroid/prompts/chat-gpt4-system-prompt.md +0 -68
  125. langroid/prompts/dialog.py +0 -17
  126. langroid/prompts/prompts_config.py +0 -5
  127. langroid/prompts/templates.py +0 -141
  128. langroid/pydantic_v1/__init__.py +0 -10
  129. langroid/pydantic_v1/main.py +0 -4
  130. langroid/utils/.chainlit/config.toml +0 -121
  131. langroid/utils/.chainlit/translations/en-US.json +0 -231
  132. langroid/utils/__init__.py +0 -19
  133. langroid/utils/algorithms/__init__.py +0 -3
  134. langroid/utils/algorithms/graph.py +0 -103
  135. langroid/utils/configuration.py +0 -98
  136. langroid/utils/constants.py +0 -30
  137. langroid/utils/docker.py +0 -37
  138. langroid/utils/git_utils.py +0 -252
  139. langroid/utils/globals.py +0 -49
  140. langroid/utils/llms/__init__.py +0 -0
  141. langroid/utils/llms/strings.py +0 -8
  142. langroid/utils/logging.py +0 -135
  143. langroid/utils/object_registry.py +0 -66
  144. langroid/utils/output/__init__.py +0 -20
  145. langroid/utils/output/citations.py +0 -41
  146. langroid/utils/output/printing.py +0 -99
  147. langroid/utils/output/status.py +0 -40
  148. langroid/utils/pandas_utils.py +0 -30
  149. langroid/utils/pydantic_utils.py +0 -602
  150. langroid/utils/system.py +0 -286
  151. langroid/utils/types.py +0 -93
  152. langroid/utils/web/__init__.py +0 -0
  153. langroid/utils/web/login.py +0 -83
  154. langroid/vector_store/__init__.py +0 -50
  155. langroid/vector_store/base.py +0 -357
  156. langroid/vector_store/chromadb.py +0 -214
  157. langroid/vector_store/lancedb.py +0 -401
  158. langroid/vector_store/meilisearch.py +0 -299
  159. langroid/vector_store/momento.py +0 -278
  160. langroid/vector_store/qdrant_cloud.py +0 -6
  161. langroid/vector_store/qdrantdb.py +0 -468
  162. langroid-0.31.2.dist-info/RECORD +0 -162
  163. {langroid-0.31.2.dist-info → langroid-0.33.3.dist-info/licenses}/LICENSE +0 -0
@@ -1,393 +0,0 @@
1
- """
2
- Structured messages to an agent, typically from an LLM, to be handled by
3
- an agent. The messages could represent, for example:
4
- - information or data given to the agent
5
- - request for information or data from the agent
6
- - request to run a method of the agent
7
- """
8
-
9
- import copy
10
- import json
11
- import textwrap
12
- from abc import ABC
13
- from random import choice
14
- from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar
15
-
16
- from docstring_parser import parse
17
-
18
- from langroid.language_models.base import LLMFunctionSpec
19
- from langroid.pydantic_v1 import BaseModel, Extra
20
- from langroid.utils.pydantic_utils import (
21
- _recursive_purge_dict_key,
22
- generate_simple_schema,
23
- )
24
- from langroid.utils.types import is_instance_of
25
-
26
- K = TypeVar("K")
27
-
28
-
29
- def remove_if_exists(k: K, d: dict[K, Any]) -> None:
30
- """Removes key `k` from `d` if present."""
31
- if k in d:
32
- d.pop(k)
33
-
34
-
35
- def format_schema_for_strict(schema: Any) -> None:
36
- """
37
- Recursively set additionalProperties to False and replace
38
- oneOf and allOf with anyOf, required for OpenAI structured outputs.
39
- Additionally, remove all defaults and set all fields to required.
40
- This may not be equivalent to the original schema.
41
- """
42
- if isinstance(schema, dict):
43
- if "type" in schema and schema["type"] == "object":
44
- schema["additionalProperties"] = False
45
-
46
- if "properties" in schema:
47
- properties = schema["properties"]
48
- all_properties = list(properties.keys())
49
- for k, v in properties.items():
50
- if "default" in v:
51
- if k == "request":
52
- v["enum"] = [v["default"]]
53
-
54
- v.pop("default")
55
- schema["required"] = all_properties
56
- else:
57
- schema["properties"] = {}
58
- schema["required"] = []
59
-
60
- anyOf = (
61
- schema.get("oneOf", []) + schema.get("allOf", []) + schema.get("anyOf", [])
62
- )
63
- if "allOf" in schema or "oneOf" in schema or "anyOf" in schema:
64
- schema["anyOf"] = anyOf
65
-
66
- remove_if_exists("allOf", schema)
67
- remove_if_exists("oneOf", schema)
68
-
69
- for v in schema.values():
70
- format_schema_for_strict(v)
71
- elif isinstance(schema, list):
72
- for v in schema:
73
- format_schema_for_strict(v)
74
-
75
-
76
- class ToolMessage(ABC, BaseModel):
77
- """
78
- Abstract Class for a class that defines the structure of a "Tool" message from an
79
- LLM. Depending on context, "tools" are also referred to as "plugins",
80
- or "function calls" (in the context of OpenAI LLMs).
81
- Essentially, they are a way for the LLM to express its intent to run a special
82
- function or method. Currently these "tools" are handled by methods of the
83
- agent.
84
-
85
- Attributes:
86
- request (str): name of agent method to map to.
87
- purpose (str): purpose of agent method, expressed in general terms.
88
- (This is used when auto-generating the tool instruction to the LLM)
89
- """
90
-
91
- request: str
92
- purpose: str
93
- id: str = "" # placeholder for OpenAI-API tool_call_id
94
-
95
- # If enabled, forces strict adherence to schema.
96
- # Currently only supported by OpenAI LLMs. When unset, enables if supported.
97
- _strict: Optional[bool] = None
98
- _allow_llm_use: bool = True # allow an LLM to use (i.e. generate) this tool?
99
-
100
- # Optional param to limit number of result tokens to retain in msg history.
101
- # Some tools can have large results that we may not want to fully retain,
102
- # e.g. result of a db query, which the LLM later reduces to a summary, so
103
- # in subsequent dialog we may only want to retain the summary,
104
- # and replace this raw result truncated to _max_result_tokens.
105
- # Important to note: unlike _max_result_tokens, this param is used
106
- # NOT used to immediately truncate the result;
107
- # it is only used to truncate what is retained in msg history AFTER the
108
- # response to this result.
109
- _max_retained_tokens: int | None = None
110
-
111
- # Optional param to limit number of tokens in the result of the tool.
112
- _max_result_tokens: int | None = None
113
-
114
- class Config:
115
- extra = Extra.allow
116
- arbitrary_types_allowed = False
117
- validate_all = True
118
- validate_assignment = True
119
- # do not include these fields in the generated schema
120
- # since we don't require the LLM to specify them
121
- schema_extra = {"exclude": {"purpose", "id"}}
122
-
123
- @classmethod
124
- def name(cls) -> str:
125
- return str(cls.default_value("request")) # redundant str() to appease mypy
126
-
127
- @classmethod
128
- def instructions(cls) -> str:
129
- """
130
- Instructions on tool usage.
131
- """
132
- return ""
133
-
134
- @classmethod
135
- def langroid_tools_instructions(cls) -> str:
136
- """
137
- Instructions on tool usage when `use_tools == True`, i.e.
138
- when using langroid built-in tools
139
- (as opposed to OpenAI-like function calls/tools).
140
- """
141
- return """
142
- IMPORTANT: When using this or any other tool/function, you MUST include a
143
- `request` field and set it equal to the FUNCTION/TOOL NAME you intend to use.
144
- """
145
-
146
- @classmethod
147
- def require_recipient(cls) -> Type["ToolMessage"]:
148
- class ToolMessageWithRecipient(cls): # type: ignore
149
- recipient: str # no default, so it is required
150
-
151
- return ToolMessageWithRecipient
152
-
153
- @classmethod
154
- def examples(cls) -> List["ToolMessage" | Tuple[str, "ToolMessage"]]:
155
- """
156
- Examples to use in few-shot demos with formatting instructions.
157
- Each example can be either:
158
- - just a ToolMessage instance, e.g. MyTool(param1=1, param2="hello"), or
159
- - a tuple (description, ToolMessage instance), where the description is
160
- a natural language "thought" that leads to the tool usage,
161
- e.g. ("I want to find the square of 5", SquareTool(num=5))
162
- In some scenarios, including such a description can significantly
163
- enhance reliability of tool use.
164
- Returns:
165
- """
166
- return []
167
-
168
- @classmethod
169
- def usage_examples(cls, random: bool = False) -> str:
170
- """
171
- Instruction to the LLM showing examples of how to use the tool-message.
172
-
173
- Args:
174
- random (bool): whether to pick a random example from the list of examples.
175
- Set to `true` when using this to illustrate a dialog between LLM and
176
- user.
177
- (if false, use ALL examples)
178
- Returns:
179
- str: examples of how to use the tool/function-call
180
- """
181
- # pick a random example of the fields
182
- if len(cls.examples()) == 0:
183
- return ""
184
- if random:
185
- examples = [choice(cls.examples())]
186
- else:
187
- examples = cls.examples()
188
- formatted_examples = [
189
- (
190
- f"EXAMPLE {i}: (THOUGHT: {ex[0]}) => \n{ex[1].format_example()}"
191
- if isinstance(ex, tuple)
192
- else f"EXAMPLE {i}:\n {ex.format_example()}"
193
- )
194
- for i, ex in enumerate(examples, 1)
195
- ]
196
- return "\n\n".join(formatted_examples)
197
-
198
- def to_json(self) -> str:
199
- return self.json(indent=4, exclude=self.Config.schema_extra["exclude"])
200
-
201
- def format_example(self) -> str:
202
- return self.json(indent=4, exclude=self.Config.schema_extra["exclude"])
203
-
204
- def dict_example(self) -> Dict[str, Any]:
205
- return self.dict(exclude=self.Config.schema_extra["exclude"])
206
-
207
- def get_value_of_type(self, target_type: Type[Any]) -> Any:
208
- """Try to find a value of a desired type in the fields of the ToolMessage."""
209
- ignore_fields = self.Config.schema_extra["exclude"].union(["request"])
210
- for field_name in set(self.dict().keys()) - ignore_fields:
211
- value = getattr(self, field_name)
212
- if is_instance_of(value, target_type):
213
- return value
214
- return None
215
-
216
- @classmethod
217
- def default_value(cls, f: str) -> Any:
218
- """
219
- Returns the default value of the given field, for the message-class
220
- Args:
221
- f (str): field name
222
-
223
- Returns:
224
- Any: default value of the field, or None if not set or if the
225
- field does not exist.
226
- """
227
- schema = cls.schema()
228
- properties = schema["properties"]
229
- return properties.get(f, {}).get("default", None)
230
-
231
- @classmethod
232
- def format_instructions(cls, tool: bool = False) -> str:
233
- """
234
- Default Instructions to the LLM showing how to use the tool/function-call.
235
- Works for GPT4 but override this for weaker LLMs if needed.
236
-
237
- Args:
238
- tool: instructions for Langroid-native tool use? (e.g. for non-OpenAI LLM)
239
- (or else it would be for OpenAI Function calls).
240
- Ignored in the default implementation, but can be used in subclasses.
241
- Returns:
242
- str: instructions on how to use the message
243
- """
244
- # TODO: when we attempt to use a "simpler schema"
245
- # (i.e. all nested fields explicit without definitions),
246
- # we seem to get worse results, so we turn it off for now
247
- param_dict = (
248
- # cls.simple_schema() if tool else
249
- cls.llm_function_schema(request=True).parameters
250
- )
251
- examples_str = ""
252
- if cls.examples():
253
- examples_str = "EXAMPLES:\n" + cls.usage_examples()
254
- return textwrap.dedent(
255
- f"""
256
- TOOL: {cls.default_value("request")}
257
- PURPOSE: {cls.default_value("purpose")}
258
- JSON FORMAT: {
259
- json.dumps(param_dict, indent=4)
260
- }
261
- {examples_str}
262
- """.lstrip()
263
- )
264
-
265
- @staticmethod
266
- def group_format_instructions() -> str:
267
- """Template for instructions for a group of tools.
268
- Works with GPT4 but override this for weaker LLMs if needed.
269
- """
270
- return textwrap.dedent(
271
- """
272
- === ALL AVAILABLE TOOLS and THEIR FORMAT INSTRUCTIONS ===
273
- You have access to the following TOOLS to accomplish your task:
274
-
275
- {format_instructions}
276
-
277
- When one of the above TOOLs is applicable, you must express your
278
- request as "TOOL:" followed by the request in the above format.
279
- """
280
- )
281
-
282
- @classmethod
283
- def llm_function_schema(
284
- cls,
285
- request: bool = False,
286
- defaults: bool = True,
287
- ) -> LLMFunctionSpec:
288
- """
289
- Clean up the schema of the Pydantic class (which can recursively contain
290
- other Pydantic classes), to create a version compatible with OpenAI
291
- Function-call API.
292
-
293
- Adapted from this excellent library:
294
- https://github.com/jxnl/instructor/blob/main/instructor/function_calls.py
295
-
296
- Args:
297
- request: whether to include the "request" field in the schema.
298
- (we set this to True when using Langroid-native TOOLs as opposed to
299
- OpenAI Function calls)
300
- defaults: whether to include fields with default values in the schema,
301
- in the "properties" section.
302
-
303
- Returns:
304
- LLMFunctionSpec: the schema as an LLMFunctionSpec
305
-
306
- """
307
- schema = copy.deepcopy(cls.schema())
308
- docstring = parse(cls.__doc__ or "")
309
- parameters = {
310
- k: v for k, v in schema.items() if k not in ("title", "description")
311
- }
312
- for param in docstring.params:
313
- if (name := param.arg_name) in parameters["properties"] and (
314
- description := param.description
315
- ):
316
- if "description" not in parameters["properties"][name]:
317
- parameters["properties"][name]["description"] = description
318
-
319
- excludes = cls.Config.schema_extra["exclude"]
320
- if not request:
321
- excludes = excludes.union({"request"})
322
- # exclude 'excludes' from parameters["properties"]:
323
- parameters["properties"] = {
324
- field: details
325
- for field, details in parameters["properties"].items()
326
- if field not in excludes and (defaults or details.get("default") is None)
327
- }
328
- parameters["required"] = sorted(
329
- k
330
- for k, v in parameters["properties"].items()
331
- if ("default" not in v and k not in excludes)
332
- )
333
- if request:
334
- parameters["required"].append("request")
335
-
336
- # If request is present it must match the default value
337
- # Similar to defining request as a literal type
338
- parameters["request"] = {
339
- "enum": [cls.default_value("request")],
340
- "type": "string",
341
- }
342
-
343
- if "description" not in schema:
344
- if docstring.short_description:
345
- schema["description"] = docstring.short_description
346
- else:
347
- schema["description"] = (
348
- f"Correctly extracted `{cls.__name__}` with all "
349
- f"the required parameters with correct types"
350
- )
351
-
352
- # Handle nested ToolMessage fields
353
- if "definitions" in parameters:
354
- for v in parameters["definitions"].values():
355
- if "exclude" in v:
356
- v.pop("exclude")
357
-
358
- remove_if_exists("purpose", v["properties"])
359
- remove_if_exists("id", v["properties"])
360
- if (
361
- "request" in v["properties"]
362
- and "default" in v["properties"]["request"]
363
- ):
364
- if "required" not in v:
365
- v["required"] = []
366
- v["required"].append("request")
367
- v["properties"]["request"] = {
368
- "type": "string",
369
- "enum": [v["properties"]["request"]["default"]],
370
- }
371
-
372
- parameters.pop("exclude")
373
- _recursive_purge_dict_key(parameters, "title")
374
- _recursive_purge_dict_key(parameters, "additionalProperties")
375
- return LLMFunctionSpec(
376
- name=cls.default_value("request"),
377
- description=cls.default_value("purpose"),
378
- parameters=parameters,
379
- )
380
-
381
- @classmethod
382
- def simple_schema(cls) -> Dict[str, Any]:
383
- """
384
- Return a simplified schema for the message, with only the request and
385
- required fields.
386
- Returns:
387
- Dict[str, Any]: simplified schema
388
- """
389
- schema = generate_simple_schema(
390
- cls,
391
- exclude=list(cls.Config.schema_extra["exclude"]),
392
- )
393
- return schema
@@ -1,38 +0,0 @@
1
- from . import google_search_tool
2
- from . import recipient_tool
3
- from . import rewind_tool
4
- from . import orchestration
5
- from .google_search_tool import GoogleSearchTool
6
- from .recipient_tool import AddRecipientTool, RecipientTool
7
- from .rewind_tool import RewindTool
8
- from .orchestration import (
9
- AgentDoneTool,
10
- DoneTool,
11
- ForwardTool,
12
- PassTool,
13
- SendTool,
14
- AgentSendTool,
15
- DonePassTool,
16
- ResultTool,
17
- FinalResultTool,
18
- )
19
-
20
- __all__ = [
21
- "GoogleSearchTool",
22
- "AddRecipientTool",
23
- "RecipientTool",
24
- "google_search_tool",
25
- "recipient_tool",
26
- "rewind_tool",
27
- "RewindTool",
28
- "orchestration",
29
- "AgentDoneTool",
30
- "DoneTool",
31
- "DonePassTool",
32
- "ForwardTool",
33
- "PassTool",
34
- "SendTool",
35
- "AgentSendTool",
36
- "ResultTool",
37
- "FinalResultTool",
38
- ]
@@ -1,50 +0,0 @@
1
- """
2
- A tool to trigger a DuckDuckGo search for a given query, and return the top results with
3
- their titles, links, summaries. Since the tool is stateless (i.e. does not need
4
- access to agent state), it can be enabled for any agent, without having to define a
5
- special method inside the agent: `agent.enable_message(DuckduckgoSearchTool)`
6
- """
7
-
8
- from typing import List, Tuple
9
-
10
- from langroid.agent.tool_message import ToolMessage
11
- from langroid.parsing.web_search import duckduckgo_search
12
-
13
-
14
- class DuckduckgoSearchTool(ToolMessage):
15
- request: str = "duckduckgo_search"
16
- purpose: str = """
17
- To search the web and return up to <num_results>
18
- links relevant to the given <query>. When using this tool,
19
- ONLY show the required JSON, DO NOT SAY ANYTHING ELSE.
20
- Wait for the results of the web search, and then use them to
21
- compose your response.
22
- """
23
- query: str
24
- num_results: int
25
-
26
- def handle(self) -> str:
27
- """
28
- Conducts a search using DuckDuckGo based on the provided query
29
- and number of results by triggering a duckduckgo_search.
30
-
31
- Returns:
32
- str: A formatted string containing the titles, links, and
33
- summaries of each search result, separated by two newlines.
34
- """
35
- search_results = duckduckgo_search(self.query, self.num_results)
36
- # return Title, Link, Summary of each result, separated by two newlines
37
- results_str = "\n\n".join(str(result) for result in search_results)
38
- return f"""
39
- BELOW ARE THE RESULTS FROM THE WEB SEARCH. USE THESE TO COMPOSE YOUR RESPONSE:
40
- {results_str}
41
- """
42
-
43
- @classmethod
44
- def examples(cls) -> List["ToolMessage" | Tuple[str, "ToolMessage"]]:
45
- return [
46
- cls(
47
- query="When was the Llama2 Large Language Model (LLM) released?",
48
- num_results=3,
49
- ),
50
- ]