langroid 0.6.7__py3-none-any.whl → 0.9.0__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 (37) hide show
  1. langroid/agent/base.py +499 -55
  2. langroid/agent/callbacks/chainlit.py +1 -1
  3. langroid/agent/chat_agent.py +191 -37
  4. langroid/agent/chat_document.py +142 -29
  5. langroid/agent/openai_assistant.py +20 -4
  6. langroid/agent/special/lance_doc_chat_agent.py +25 -18
  7. langroid/agent/special/lance_rag/critic_agent.py +37 -5
  8. langroid/agent/special/lance_rag/query_planner_agent.py +102 -63
  9. langroid/agent/special/lance_tools.py +10 -2
  10. langroid/agent/special/sql/sql_chat_agent.py +69 -13
  11. langroid/agent/task.py +179 -43
  12. langroid/agent/tool_message.py +19 -7
  13. langroid/agent/tools/__init__.py +5 -0
  14. langroid/agent/tools/orchestration.py +216 -0
  15. langroid/agent/tools/recipient_tool.py +6 -11
  16. langroid/agent/tools/rewind_tool.py +1 -1
  17. langroid/agent/typed_task.py +19 -0
  18. langroid/language_models/.chainlit/config.toml +121 -0
  19. langroid/language_models/.chainlit/translations/en-US.json +231 -0
  20. langroid/language_models/base.py +114 -12
  21. langroid/language_models/mock_lm.py +10 -1
  22. langroid/language_models/openai_gpt.py +260 -36
  23. langroid/mytypes.py +0 -1
  24. langroid/parsing/parse_json.py +19 -2
  25. langroid/utils/pydantic_utils.py +19 -0
  26. langroid/vector_store/base.py +3 -1
  27. langroid/vector_store/lancedb.py +2 -0
  28. {langroid-0.6.7.dist-info → langroid-0.9.0.dist-info}/METADATA +4 -1
  29. {langroid-0.6.7.dist-info → langroid-0.9.0.dist-info}/RECORD +32 -33
  30. pyproject.toml +2 -1
  31. langroid/agent/special/lance_rag_new/__init__.py +0 -9
  32. langroid/agent/special/lance_rag_new/critic_agent.py +0 -171
  33. langroid/agent/special/lance_rag_new/lance_rag_task.py +0 -144
  34. langroid/agent/special/lance_rag_new/query_planner_agent.py +0 -222
  35. langroid/agent/team.py +0 -1758
  36. {langroid-0.6.7.dist-info → langroid-0.9.0.dist-info}/LICENSE +0 -0
  37. {langroid-0.6.7.dist-info → langroid-0.9.0.dist-info}/WHEEL +0 -0
@@ -1,222 +0,0 @@
1
- """
2
- LanceQueryPlanAgent is a ChatAgent created with a specific document schema.
3
- Given a QUERY, the LLM constructs a Query Plan consisting of:
4
- - filter condition if needed (or empty string if no filter is needed)
5
- - query - a possibly rephrased query that can be used to match the `content` field
6
- - dataframe_calc - a Pandas-dataframe calculation/aggregation string, possibly empty
7
- - original_query - the original query for reference
8
-
9
- This agent has access to two tools:
10
- - QueryPlanTool, which is used to generate the Query Plan, and the handler of
11
- this tool simply passes it on to the RAG agent named in config.doc_agent_name.
12
- - QueryPlanFeedbackTool, which is used to handle feedback on the Query Plan and
13
- Result from the RAG agent. The QueryPlanFeedbackTool is used by
14
- the QueryPlanCritic, who inserts feedback into the `feedback` field
15
- """
16
-
17
- import logging
18
-
19
- import langroid as lr
20
- from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig
21
- from langroid.agent.chat_document import ChatDocument
22
- from langroid.agent.special.lance_tools import (
23
- QueryPlan,
24
- QueryPlanAnswerTool,
25
- QueryPlanFeedbackTool,
26
- QueryPlanTool,
27
- )
28
- from langroid.utils.constants import DONE, NO_ANSWER
29
-
30
- logger = logging.getLogger(__name__)
31
-
32
-
33
- class LanceQueryPlanAgentConfig(ChatAgentConfig):
34
- name: str = "LancePlanner"
35
- critic_name: str = "QueryPlanCritic"
36
- doc_agent_name: str = "LanceRAG"
37
- doc_schema: str = ""
38
- use_tools = False
39
- max_retries: int = 5 # max number of retries for query plan
40
- use_functions_api = True
41
-
42
- system_message = f"""
43
- You will receive a QUERY, to be answered based on an EXTREMELY LARGE collection
44
- of documents you DO NOT have access to, but your ASSISTANT does.
45
- You only know that these documents have a special `content` field
46
- and additional FILTERABLE fields in the SCHEMA below, along with the
47
- SAMPLE VALUES for each field, and the DTYPE in PANDAS TERMINOLOGY.
48
-
49
- {{doc_schema}}
50
-
51
- Based on the QUERY and the above SCHEMA, your task is to determine a QUERY PLAN,
52
- consisting of:
53
- - a PANDAS-TYPE FILTER (can be empty string) that would help the ASSISTANT to
54
- answer the query.
55
- Remember the FILTER can refer to ANY fields in the above SCHEMA
56
- EXCEPT the `content` field of the documents.
57
- ONLY USE A FILTER IF EXPLICITLY MENTIONED IN THE QUERY.
58
- TO get good results, for STRING MATCHES, consider using LIKE instead of =, e.g.
59
- "CEO LIKE '%Jobs%'" instead of "CEO = 'Steve Jobs'"
60
- YOUR FILTER MUST BE A PANDAS-TYPE FILTER, respecting the shown DTYPES.
61
- - a possibly REPHRASED QUERY (CANNOT BE EMPTY) to be answerable given the FILTER.
62
- Keep in mind that the ASSISTANT does NOT know anything about the FILTER fields,
63
- so the REPHRASED QUERY should NOT mention ANY FILTER fields.
64
- The assistant will answer based on documents whose CONTENTS match the QUERY,
65
- possibly REPHRASED.
66
- !!!!****THE REPHRASED QUERY SHOULD NEVER BE EMPTY****!!!
67
- - an OPTIONAL SINGLE-LINE Pandas-dataframe calculation/aggregation string
68
- that can be used to calculate the answer to the original query,
69
- e.g. "df["rating"].mean()",
70
- or "df.groupby("director").mean()["rating"]",
71
- or EMPTY string if no calc is needed.
72
- The dataframe calc CAN refer to the `content` field.
73
- If a DataFrame calculation is NOT needed, leave this field EMPTY.
74
-
75
- IMPORTANT: The DataFrame `df` in this calculation is the result of
76
- applying the FILTER AND REPHRASED QUERY to the documents.
77
-
78
- WATCH OUT!! When deciding the dataframe calc, if any, CAREFULLY
79
- note what the query is asking, and ensure that the result of your
80
- dataframe calc expression would answer the query.
81
-
82
-
83
- EXAMPLE:
84
- -------
85
- Suppose there is a document-set about crime reports, where:
86
- CONTENT = crime report,
87
- Filterable SCHEMA consists of City, Year, num_deaths.
88
-
89
- Then given this ORIGINAL QUERY:
90
-
91
- Total deaths in shoplifting crimes in Los Angeles in 2023?
92
-
93
- A POSSIBLE QUERY PLAN could be:
94
-
95
- FILTER: "City LIKE '%Los Angeles%' AND Year = 2023"
96
- REPHRASED QUERY: "shoplifting crime" --> this will be used to MATCH content of docs
97
- [NOTE: we dropped the FILTER fields City and Year since the
98
- ASSISTANT does not know about them and only uses the query to
99
- match the CONTENT of the docs.]
100
- DATAFRAME CALCULATION: "df["num_deaths"].sum()"
101
- NOTE!!! The DataFrame `df` in this calculation is the result of
102
- applying the FILTER AND REPHRASED QUERY to the documents,
103
- hence this computation will give the total deaths in shoplifting crimes.
104
- ------------- END OF EXAMPLE ----------------
105
-
106
- The FILTER must be a PANDAS-like condition, e.g.
107
- "year > 2000 AND genre = 'ScienceFiction'".
108
- To ensure you get useful results, you should make your FILTER
109
- NOT TOO STRICT, e.g. look for approximate match using LIKE, etc.
110
- E.g. "CEO LIKE '%Jobs%'" instead of "CEO = 'Steve Jobs'"
111
- Use DOT NOTATION to refer to nested fields, e.g. `metadata.year`, etc.
112
-
113
- You must FIRST present the QUERY PLAN using the `query_plan` tool/function.
114
- This will be handled by your document assistant, who will produce an ANSWER.
115
-
116
- You may receive FEEDBACK on your QUERY PLAN and received ANSWER,
117
- from the 'QueryPlanCritic' who may offer suggestions for
118
- a better FILTER, REPHRASED QUERY, or DATAFRAME CALCULATION.
119
-
120
- If you keep getting feedback or keep getting a {NO_ANSWER} from the assistant
121
- at least 3 times, then simply say '{DONE} {NO_ANSWER}' and nothing else.
122
-
123
- At the BEGINNING if there is no query, ASK the user what they want to know.
124
- """
125
-
126
- def set_system_message(self) -> None:
127
- self.system_message = self.system_message.format(
128
- doc_schema=self.doc_schema,
129
- )
130
-
131
-
132
- class LanceQueryPlanAgent(ChatAgent):
133
- def __init__(self, config: LanceQueryPlanAgentConfig):
134
- super().__init__(config)
135
- self.config: LanceQueryPlanAgentConfig = config
136
- self.curr_query_plan: QueryPlan | None = None
137
- # how many times re-trying query plan in response to feedback:
138
- self.n_retries: int = 0
139
- self.result: str = "" # answer received from LanceRAG
140
- # This agent should generate the QueryPlanTool
141
- # as well as handle it for validation
142
- self.enable_message(QueryPlanTool, use=True, handle=True)
143
- self.enable_message(QueryPlanFeedbackTool, use=False, handle=True)
144
-
145
- def query_plan(self, msg: QueryPlanTool) -> ChatDocument:
146
- """Valid, forward to RAG Agent"""
147
- # save, to be used to assemble QueryPlanResultTool
148
- if len(msg.plan.dataframe_calc.split("\n")) > 1:
149
- return "DATAFRAME CALCULATION must be a SINGLE LINE; Retry the `query_plan`"
150
- self.curr_query_plan = msg.plan
151
- # return a ChatDocument with tool_messages set to this tool,
152
- # so caller can directly get the tool without parsing
153
- return self.create_agent_response(tool_messages=[msg])
154
-
155
- def query_plan_feedback(self, msg: QueryPlanFeedbackTool) -> str:
156
- """Process Critic feedback on QueryPlan + Answer from RAG Agent"""
157
- # We should have saved answer in self.result by this time,
158
- # since this Agent seeks feedback only after receiving RAG answer.
159
- if msg.suggested_fix == "":
160
- self.n_retries = 0
161
- # This means the Query Plan or Result is good, as judged by Critic
162
- if self.result == "":
163
- # This was feedback for query with no result
164
- return "QUERY PLAN LOOKS GOOD!"
165
- elif self.result == NO_ANSWER:
166
- return NO_ANSWER
167
- else: # non-empty and non-null answer
168
- return DONE + " " + self.result
169
- self.n_retries += 1
170
- if self.n_retries >= self.config.max_retries:
171
- # bail out to avoid infinite loop
172
- self.n_retries = 0
173
- return DONE + " " + NO_ANSWER
174
- return f"""
175
- here is FEEDBACK about your QUERY PLAN, and a SUGGESTED FIX.
176
- Modify the QUERY PLAN if needed:
177
- FEEDBACK: {msg.feedback}
178
- SUGGESTED FIX: {msg.suggested_fix}
179
- """
180
-
181
- def handle_message_fallback(
182
- self, msg: str | ChatDocument
183
- ) -> str | ChatDocument | None:
184
- """
185
- Process answer received from RAG Agent:
186
- Construct a QueryPlanAnswerTool with the answer,
187
- and forward to Critic for feedback.
188
- """
189
- # TODO we don't need to use this fallback method. instead we can
190
- # first call result = super().agent_response(), and if result is None,
191
- # then we know there was no tool, so we run below code
192
- if (
193
- isinstance(msg, ChatDocument)
194
- and self.curr_query_plan is not None
195
- and msg.metadata.parent is not None
196
- ):
197
- # save result, to be used in query_plan_feedback()
198
- self.result = msg.content
199
- # assemble QueryPlanAnswerTool...
200
- query_plan_answer_tool = QueryPlanAnswerTool( # type: ignore
201
- plan=self.curr_query_plan,
202
- answer=self.result,
203
- )
204
- response_tmpl = self.create_agent_response()
205
- # ... add the QueryPlanAnswerTool to the response
206
- # (Notice how the Agent is directly sending a tool, not the LLM)
207
- response_tmpl.tool_messages = [query_plan_answer_tool]
208
- # set the recipient to the Critic so it can give feedback
209
- response_tmpl.metadata.recipient = self.config.critic_name
210
- self.curr_query_plan = None # reset
211
- return response_tmpl
212
- if (
213
- isinstance(msg, ChatDocument)
214
- and not self.has_tool_message_attempt(msg)
215
- and msg.metadata.sender == lr.Entity.LLM
216
- ):
217
- # remind LLM to use the QueryPlanFeedbackTool
218
- return """
219
- You forgot to use the `query_plan` tool/function.
220
- Re-try your response using the `query_plan` tool/function.
221
- """
222
- return None