langroid 0.33.6__py3-none-any.whl → 0.33.7__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.
- langroid/__init__.py +106 -0
- langroid/agent/__init__.py +41 -0
- langroid/agent/base.py +1983 -0
- langroid/agent/batch.py +398 -0
- langroid/agent/callbacks/__init__.py +0 -0
- langroid/agent/callbacks/chainlit.py +598 -0
- langroid/agent/chat_agent.py +1899 -0
- langroid/agent/chat_document.py +454 -0
- langroid/agent/openai_assistant.py +882 -0
- langroid/agent/special/__init__.py +59 -0
- langroid/agent/special/arangodb/__init__.py +0 -0
- langroid/agent/special/arangodb/arangodb_agent.py +656 -0
- langroid/agent/special/arangodb/system_messages.py +186 -0
- langroid/agent/special/arangodb/tools.py +107 -0
- langroid/agent/special/arangodb/utils.py +36 -0
- langroid/agent/special/doc_chat_agent.py +1466 -0
- langroid/agent/special/lance_doc_chat_agent.py +262 -0
- langroid/agent/special/lance_rag/__init__.py +9 -0
- langroid/agent/special/lance_rag/critic_agent.py +198 -0
- langroid/agent/special/lance_rag/lance_rag_task.py +82 -0
- langroid/agent/special/lance_rag/query_planner_agent.py +260 -0
- langroid/agent/special/lance_tools.py +61 -0
- langroid/agent/special/neo4j/__init__.py +0 -0
- langroid/agent/special/neo4j/csv_kg_chat.py +174 -0
- langroid/agent/special/neo4j/neo4j_chat_agent.py +433 -0
- langroid/agent/special/neo4j/system_messages.py +120 -0
- langroid/agent/special/neo4j/tools.py +32 -0
- langroid/agent/special/relevance_extractor_agent.py +127 -0
- langroid/agent/special/retriever_agent.py +56 -0
- langroid/agent/special/sql/__init__.py +17 -0
- langroid/agent/special/sql/sql_chat_agent.py +654 -0
- langroid/agent/special/sql/utils/__init__.py +21 -0
- langroid/agent/special/sql/utils/description_extractors.py +190 -0
- langroid/agent/special/sql/utils/populate_metadata.py +85 -0
- langroid/agent/special/sql/utils/system_message.py +35 -0
- langroid/agent/special/sql/utils/tools.py +64 -0
- langroid/agent/special/table_chat_agent.py +263 -0
- langroid/agent/task.py +2095 -0
- langroid/agent/tool_message.py +393 -0
- langroid/agent/tools/__init__.py +38 -0
- langroid/agent/tools/duckduckgo_search_tool.py +50 -0
- langroid/agent/tools/file_tools.py +234 -0
- langroid/agent/tools/google_search_tool.py +39 -0
- langroid/agent/tools/metaphor_search_tool.py +68 -0
- langroid/agent/tools/orchestration.py +303 -0
- langroid/agent/tools/recipient_tool.py +235 -0
- langroid/agent/tools/retrieval_tool.py +32 -0
- langroid/agent/tools/rewind_tool.py +137 -0
- langroid/agent/tools/segment_extract_tool.py +41 -0
- langroid/agent/xml_tool_message.py +382 -0
- langroid/cachedb/__init__.py +17 -0
- langroid/cachedb/base.py +58 -0
- langroid/cachedb/momento_cachedb.py +108 -0
- langroid/cachedb/redis_cachedb.py +153 -0
- langroid/embedding_models/__init__.py +39 -0
- langroid/embedding_models/base.py +74 -0
- langroid/embedding_models/models.py +461 -0
- langroid/embedding_models/protoc/__init__.py +0 -0
- langroid/embedding_models/protoc/embeddings.proto +19 -0
- langroid/embedding_models/protoc/embeddings_pb2.py +33 -0
- langroid/embedding_models/protoc/embeddings_pb2.pyi +50 -0
- langroid/embedding_models/protoc/embeddings_pb2_grpc.py +79 -0
- langroid/embedding_models/remote_embeds.py +153 -0
- langroid/exceptions.py +71 -0
- langroid/language_models/__init__.py +53 -0
- langroid/language_models/azure_openai.py +153 -0
- langroid/language_models/base.py +678 -0
- langroid/language_models/config.py +18 -0
- langroid/language_models/mock_lm.py +124 -0
- langroid/language_models/openai_gpt.py +1964 -0
- langroid/language_models/prompt_formatter/__init__.py +16 -0
- langroid/language_models/prompt_formatter/base.py +40 -0
- langroid/language_models/prompt_formatter/hf_formatter.py +132 -0
- langroid/language_models/prompt_formatter/llama2_formatter.py +75 -0
- langroid/language_models/utils.py +151 -0
- langroid/mytypes.py +84 -0
- langroid/parsing/__init__.py +52 -0
- langroid/parsing/agent_chats.py +38 -0
- langroid/parsing/code_parser.py +121 -0
- langroid/parsing/document_parser.py +718 -0
- langroid/parsing/para_sentence_split.py +62 -0
- langroid/parsing/parse_json.py +155 -0
- langroid/parsing/parser.py +313 -0
- langroid/parsing/repo_loader.py +790 -0
- langroid/parsing/routing.py +36 -0
- langroid/parsing/search.py +275 -0
- langroid/parsing/spider.py +102 -0
- langroid/parsing/table_loader.py +94 -0
- langroid/parsing/url_loader.py +111 -0
- langroid/parsing/urls.py +273 -0
- langroid/parsing/utils.py +373 -0
- langroid/parsing/web_search.py +156 -0
- langroid/prompts/__init__.py +9 -0
- langroid/prompts/dialog.py +17 -0
- langroid/prompts/prompts_config.py +5 -0
- langroid/prompts/templates.py +141 -0
- langroid/pydantic_v1/__init__.py +10 -0
- langroid/pydantic_v1/main.py +4 -0
- langroid/utils/__init__.py +19 -0
- langroid/utils/algorithms/__init__.py +3 -0
- langroid/utils/algorithms/graph.py +103 -0
- langroid/utils/configuration.py +98 -0
- langroid/utils/constants.py +30 -0
- langroid/utils/git_utils.py +252 -0
- langroid/utils/globals.py +49 -0
- langroid/utils/logging.py +135 -0
- langroid/utils/object_registry.py +66 -0
- langroid/utils/output/__init__.py +20 -0
- langroid/utils/output/citations.py +41 -0
- langroid/utils/output/printing.py +99 -0
- langroid/utils/output/status.py +40 -0
- langroid/utils/pandas_utils.py +30 -0
- langroid/utils/pydantic_utils.py +602 -0
- langroid/utils/system.py +286 -0
- langroid/utils/types.py +93 -0
- langroid/vector_store/__init__.py +50 -0
- langroid/vector_store/base.py +359 -0
- langroid/vector_store/chromadb.py +214 -0
- langroid/vector_store/lancedb.py +406 -0
- langroid/vector_store/meilisearch.py +299 -0
- langroid/vector_store/momento.py +278 -0
- langroid/vector_store/qdrantdb.py +468 -0
- {langroid-0.33.6.dist-info → langroid-0.33.7.dist-info}/METADATA +95 -94
- langroid-0.33.7.dist-info/RECORD +127 -0
- {langroid-0.33.6.dist-info → langroid-0.33.7.dist-info}/WHEEL +1 -1
- langroid-0.33.6.dist-info/RECORD +0 -7
- langroid-0.33.6.dist-info/entry_points.txt +0 -4
- pyproject.toml +0 -356
- {langroid-0.33.6.dist-info → langroid-0.33.7.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,393 @@
|
|
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
|
@@ -0,0 +1,38 @@
|
|
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
|
+
]
|
@@ -0,0 +1,50 @@
|
|
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
|
+
]
|