chat_agent
ChatAgentConfig
¶
Bases: AgentConfig
Configuration for ChatAgent
Attributes:
| Name | Type | Description |
|---|---|---|
system_message |
str
|
system message to include in message sequence
(typically defines role and task of agent).
Used only if |
user_message |
Optional[str]
|
user message to include in message sequence.
Used only if |
use_tools |
bool
|
whether to use our own ToolMessages mechanism |
handle_llm_no_tool |
Any
|
desired agent_response when LLM generates non-tool msg. |
use_functions_api |
bool
|
whether to use functions/tools native to the LLM API
(e.g. OpenAI's |
use_tools_api |
bool
|
When |
strict_recovery |
bool
|
whether to enable strict schema recovery when there is a tool-generation error. |
enable_orchestration_tool_handling |
bool
|
whether to enable handling of orchestration tools, e.g. ForwardTool, DoneTool, PassTool, etc. |
output_format |
Optional[type]
|
When supported by the LLM (certain OpenAI LLMs and local LLMs served by providers such as vLLM), ensures that the output is a JSON matching the corresponding schema via grammar-based decoding |
handle_output_format |
bool
|
When |
use_output_format |
bool
|
When |
instructions_output_format |
bool
|
Controls whether we generate instructions for
|
use_tools_on_output_format |
bool
|
Controls whether to automatically switch
to the Langroid-native tools mechanism when |
output_format_include_defaults |
bool
|
Whether to include fields with default arguments in the output schema |
full_citations |
bool
|
Whether to show source reference citation + content for each citation, or just the main reference citation. |
search_for_tools_everywhere |
bool
|
Whether to search for tools everywhere, or only in specific LLM response elements based on use_tools / use_functions_api / use_tools_api config settings. |
recognize_recipient_in_content |
bool
|
Whether to parse LLM response text content
for recipient routing patterns, specifically:
- |
context_overflow_strategy |
Literal['truncate', 'drop_turns']
|
Strategy for handling context overflow when message history exceeds model context length. Options: - "truncate": Truncate content of early messages (preserves all messages but with shortened content). This maintains the message sequence. - "drop_turns": Drop complete conversation turns (USER + all responses until next USER). More aggressive but cleaner for voice agents. Default is "truncate" for backward compatibility. |
ChatAgent(config=ChatAgentConfig(), task=None)
¶
Bases: Agent
Chat Agent interacting with external env
(could be human, or external tools).
The agent (the LLM actually) is provided with an optional "Task Spec",
which is a sequence of LLMMessages. These are used to initialize
the task_messages of the agent.
In most applications we will use a ChatAgent rather than a bare Agent.
The Agent class mainly exists to hold various common methods and attributes.
One difference between ChatAgent and Agent is that ChatAgent's
llm_response method uses "chat mode" API (i.e. one that takes a
message sequence rather than a single message),
whereas the same method in the Agent class uses "completion mode" API (i.e. one
that takes a single message).
config: settings for the agent
Source code in langroid/agent/chat_agent.py
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | |
task_messages
property
¶
The task messages are the initial messages that define the task of the agent. There will be at least a system message plus possibly a user msg. Returns: List[LLMMessage]: the task messages
all_llm_tools_known
property
¶
All known tools; we include output_format if it is a ToolMessage.
init_state()
¶
Initialize the state of the agent. Just conversation state here, but subclasses can override this to initialize other state.
Source code in langroid/agent/chat_agent.py
from_id(id)
staticmethod
¶
Get an agent from its ID Args: agent_id (str): ID of the agent Returns: ChatAgent: The agent with the given ID
clone(i=0)
¶
Create i'th clone of this agent, ensuring tool use/handling is cloned. Important: We assume all member variables are in the init method here and in the Agent class. TODO: We are attempting to clone an agent after its state has been changed in possibly many ways. Below is an imperfect solution. Caution advised. Revisit later.
Source code in langroid/agent/chat_agent.py
clear_history(start=-2, end=-1)
¶
Clear the message history, deleting messages from index start,
up to index end.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
int
|
index of first message to delete; default = -2 (i.e. delete last 2 messages, typically these are the last user and assistant messages) |
-2
|
end
|
int
|
index of last message to delete; Default = -1 (i.e. delete all messages up to the last one) |
-1
|
Source code in langroid/agent/chat_agent.py
update_history(message, response)
¶
Update the message history with the latest user message and LLM response. Args: message (str): user message response: (str): LLM response
Source code in langroid/agent/chat_agent.py
export_history()
¶
Export message history as a portable, versioned JSON snapshot.
Returns:
| Type | Description |
|---|---|
str
|
A JSON string containing the current message history. |
Source code in langroid/agent/chat_agent.py
import_history(snapshot, max_size_bytes=100 * 1024 * 1024)
¶
Restore message history from :meth:export_history output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snapshot
|
str
|
Versioned JSON snapshot to restore. |
required |
max_size_bytes
|
int
|
Maximum total decoded attachment size. Defaults to 100 MiB. |
100 * 1024 * 1024
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the snapshot is malformed, has an unknown version,
starts with a non-system message, or exceeds |
Source code in langroid/agent/chat_agent.py
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 | |
tool_format_rules()
¶
Specification of tool formatting rules
(typically JSON-based but can be non-JSON, e.g. XMLToolMessage),
based on the currently enabled usable ToolMessages
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
formatting rules |
Source code in langroid/agent/chat_agent.py
tool_instructions()
¶
Instructions for tools or function-calls, for enabled and usable Tools. These are inserted into system prompt regardless of whether we are using our own ToolMessage mechanism or the LLM's function-call mechanism.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
concatenation of instructions for all usable tools |
Source code in langroid/agent/chat_agent.py
augment_system_message(message)
¶
Augment the system message with the given message. Args: message (str): system message
last_message_with_role(role)
¶
from message_history, return the last message with role role
Source code in langroid/agent/chat_agent.py
last_message_idx_with_role(role)
¶
Index of last message in message_history, with specified role. Return -1 if not found. Index = 0 is the first message in the history.
Source code in langroid/agent/chat_agent.py
nth_message_idx_with_role(role, n)
¶
Index of nth message in message_history, with specified role.
(n is assumed to be 1-based, i.e. 1 is the first message with that role).
Return -1 if not found. Index = 0 is the first message in the history.
Source code in langroid/agent/chat_agent.py
update_last_message(message, role=Role.USER)
¶
Update the last message that has role role in the message history.
Useful when we want to replace a long user prompt, that may contain context
documents plus a question, with just the question.
Args:
message (str): new message to replace with
role (str): role of message to replace
Source code in langroid/agent/chat_agent.py
delete_last_message(role=Role.USER)
¶
Delete the last message that has role role from the message history.
Args:
role (str): role of message to delete
Source code in langroid/agent/chat_agent.py
handle_message_fallback(msg)
¶
Fallback method for the "no-tools" scenario, i.e., the current msg
(presumably emitted by the LLM) does not have any tool that the agent
can handle.
NOTE: The msg may contain tools but either (a) the agent is not
enabled to handle them, or (b) there's an explicit recipient field
in the tool that doesn't match the agent's name.
Uses the self.config.non_tool_routing to determine the action to take.
This method can be overridden by subclasses, e.g., to create a "reminder" message when a tool is expected but the LLM "forgot" to generate one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
str | ChatDocument
|
The input msg to handle |
required |
Returns: Any: The result of the handler method
Source code in langroid/agent/chat_agent.py
unhandled_tools()
¶
The set of tools that are known but not handled. Useful in task flow: an agent can refuse to accept an incoming msg when it only has unhandled tools.
Source code in langroid/agent/chat_agent.py
enable_message(message_class, use=True, handle=True, force=False, require_recipient=False, include_defaults=True)
¶
Add the tool (message class) to the agent, and enable either - tool USE (i.e. the LLM can generate JSON to use this tool), - tool HANDLING (i.e. the agent can handle JSON from this tool),
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_class
|
Optional[Type[ToolMessage] | List[Type[ToolMessage]]]
|
The ToolMessage class OR List of such classes to enable, for USE, or HANDLING, or both. If this is a list of ToolMessage classes, then the remain args are applied to all classes. Optional; if None, then apply the enabling to all tools in the agent's toolset that have been enabled so far. |
required |
use
|
bool
|
IF True, allow the agent (LLM) to use this tool (or all tools), else disallow |
True
|
handle
|
bool
|
if True, allow the agent (LLM) to handle (i.e. respond to) this tool (or all tools) |
True
|
force
|
bool
|
whether to FORCE the agent (LLM) to USE the specific
tool represented by |
False
|
require_recipient
|
bool
|
whether to require that recipient be specified
when using the tool message (only applies if |
False
|
include_defaults
|
bool
|
whether to include fields that have default values, in the "properties" section of the JSON format instructions. (Normally the OpenAI completion API ignores these fields, but the Assistant fn-calling seems to pay attn to these, and if we don't want this, we should set this to False.) |
True
|
Source code in langroid/agent/chat_agent.py
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 | |
set_output_format(output_type, force_tools=None, use=None, handle=None, instructions=None, is_copy=False)
¶
Sets output_format to output_type and, if force_tools is enabled,
switches to the native Langroid tools mechanism to ensure that no tool
calls not of output_type are generated. By default, force_tools
follows the use_tools_on_output_format parameter in the config.
If output_type is None, restores to the state prior to setting
output_format.
If use, we enable use of output_type when it is a subclass
of ToolMesage. Note that this primarily controls instruction
generation: the model will always generate output_type regardless
of whether use is set. Defaults to the use_output_format
parameter in the config. Similarly, handling of output_type is
controlled by handle, which defaults to the
handle_output_format parameter in the config.
instructions controls whether we generate instructions specifying
the output format schema. Defaults to the instructions_output_format
parameter in the config.
is_copy is set when called via __getitem__. In that case, we must
copy certain fields to ensure that we do not overwrite the main agent's
setings.
Source code in langroid/agent/chat_agent.py
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 | |
disable_message_handling(message_class=None)
¶
Disable this agent from RESPONDING to a message_class (Tool). If
message_class is None, then disable this agent from responding to ALL.
Args:
message_class: The ToolMessage class to disable; Optional.
Source code in langroid/agent/chat_agent.py
disable_message_use(message_class)
¶
Disable this agent from USING a message class (Tool).
If message_class is None, then disable this agent from USING ALL tools.
Args:
message_class: The ToolMessage class to disable.
If None, disable all.
Source code in langroid/agent/chat_agent.py
disable_message_use_except(message_class)
¶
Disable this agent from USING ALL messages EXCEPT a message class (Tool) Args: message_class: The only ToolMessage class to allow
Source code in langroid/agent/chat_agent.py
get_tool_messages(msg, all_tools=False)
¶
Extracts messages and tracks whether any errors occurred. If strict mode was enabled, disables it for the tool, else triggers strict recovery.
Source code in langroid/agent/chat_agent.py
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 | |
truncate_message(idx, tokens=5, warning='...[Contents truncated!]', inplace=True)
¶
Truncate message at idx in msg history to tokens tokens.
If inplace is True, the message is truncated in place, else it LEAVES the original message INTACT and returns a new message
Source code in langroid/agent/chat_agent.py
llm_response(message=None)
¶
Respond to a single user message, appended to the message history, in "chat" mode Args: message (str|ChatDocument): message or ChatDocument object to respond to. If None, use the self.task_messages Returns: LLM response as a ChatDocument object
Source code in langroid/agent/chat_agent.py
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 | |
llm_response_async(message=None)
async
¶
Async version of llm_response. See there for details.
Source code in langroid/agent/chat_agent.py
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 | |
init_message_history()
¶
Initialize the message history with the system message and user message
Source code in langroid/agent/chat_agent.py
llm_response_messages(messages, output_len=None, tool_choice='auto')
¶
Respond to a series of messages, e.g. with OpenAI ChatCompletion Args: messages: seq of messages (with role, content fields) sent to LLM output_len: max number of tokens expected in response. If None, use the LLM's default model_max_output_tokens. Returns: Document (i.e. with fields "content", "metadata")
Source code in langroid/agent/chat_agent.py
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 | |
llm_response_messages_async(messages, output_len=None, tool_choice='auto')
async
¶
Async version of llm_response_messages. See there for details.
Source code in langroid/agent/chat_agent.py
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 | |
llm_response_forget(message=None)
¶
LLM Response to single message, and restore message_history. In effect a "one-off" message & response that leaves agent message history state intact.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str | ChatDocument
|
message to respond to. |
None
|
Returns:
| Type | Description |
|---|---|
ChatDocument
|
A Document object with the response. |
Source code in langroid/agent/chat_agent.py
llm_response_forget_async(message=None)
async
¶
Async version of llm_response_forget. See there for details.
Source code in langroid/agent/chat_agent.py
chat_num_tokens(messages=None)
¶
Total number of tokens in the message history so far.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
Optional[List[LLMMessage]]
|
if provided, compute the number of tokens in this list of messages, rather than the current message history. |
None
|
Returns: int: number of tokens in message history
Source code in langroid/agent/chat_agent.py
message_history_str(i=None)
¶
Return a string representation of the message history Args: i: if provided, return only the i-th message when i is postive, or last k messages when i = -k. Returns: