brainsqueeze commited on
Commit
d1b6ca9
·
verified ·
1 Parent(s): 1636162

Delete ask_candid/agents

Browse files
ask_candid/agents/__init__.py DELETED
File without changes
ask_candid/agents/elastic.py DELETED
@@ -1,842 +0,0 @@
1
- from typing import TypedDict, List
2
- from functools import partial
3
- import json
4
- import ast
5
- from ask_candid.base.api_base import BaseAPI
6
- import os
7
- import pandas as pd
8
- from pydantic import BaseModel, Field
9
-
10
- from langchain_core.runnables import RunnableSequence
11
- from langchain_core.language_models.llms import LLM
12
- from langchain.agents.openai_functions_agent.base import create_openai_functions_agent
13
- from langchain.agents.agent import AgentExecutor
14
- from langchain.agents.agent_types import AgentType
15
- from langchain.prompts import ChatPromptTemplate, PromptTemplate, MessagesPlaceholder
16
- from langchain.output_parsers import PydanticOutputParser
17
- from langchain.schema import BaseMessage
18
- from langchain.agents import create_tool_calling_agent, AgentExecutor
19
- from langchain_core.tools import Tool
20
-
21
- from langgraph.graph import StateGraph, END
22
-
23
- from ask_candid.tools.elastic.index_data_tool import IndexShowDataTool
24
- from ask_candid.tools.elastic.index_details_tool import IndexDetailsTool
25
- from ask_candid.tools.elastic.index_search_tool import create_search_tool
26
-
27
- tools = [
28
- IndexShowDataTool(),
29
- IndexDetailsTool(),
30
- create_search_tool(pcs_codes={}),
31
- ]
32
-
33
-
34
- class AutocodingAPI(BaseAPI):
35
- def __init__(self):
36
- super().__init__(
37
- url=os.getenv("AUTOCODING_API_URL"),
38
- headers={
39
- "x-api-key": os.getenv("AUTOCODING_API_KEY"),
40
- "Content-Type": "application/json",
41
- },
42
- )
43
-
44
- def __call__(self, text: str, taxonomy: str = "pcs-v3"):
45
- params = {"text": text, "taxonomy": taxonomy}
46
- return self.get(**params)
47
-
48
-
49
- def find_subject_levels(filtered_df, subject_level_i, target_value):
50
- """
51
- Filters the DataFrame from the last valid NaN in 'Subject Level i' and retrieves corresponding values for lower levels.
52
-
53
- Parameters:
54
- filtered_df (pd.DataFrame): The input DataFrame.
55
- subject_level_i (int): The subject level to filter from (1 to 4).
56
- target_value (str): The value to search for in 'Subject Level i'.
57
-
58
- Returns:
59
- dict: A dictionary containing values for 'Subject Level i' to 'Subject Level 1'.
60
- pd.DataFrame: The filtered DataFrame from the determined start index to the target_value row.
61
- """
62
- if subject_level_i < 1 or subject_level_i > 4:
63
- raise ValueError("subject_level_i should be between 1 and 4")
64
-
65
- # Define the target column dynamically
66
- target_column = f"Subject Level {subject_level_i}"
67
-
68
- # Find indices where the target column has the target value
69
- target_indices = filtered_df[
70
- filtered_df[target_column].astype(str).str.strip() == target_value
71
- ].index
72
-
73
- if target_indices.empty:
74
- return {}, pd.DataFrame() # Return empty if target_value is not found
75
-
76
- # Get the first occurrence of the target value
77
- first_target_index = target_indices[0]
78
-
79
- # Initialize dictionary to store subject level values
80
- subject_level_values = {target_column: target_value}
81
-
82
- # Initialize subject level start index
83
- subject_level_start = first_target_index
84
-
85
- # Find the last non-NaN row for each subject level
86
- for level in range(subject_level_i - 1, 0, -1): # Loop from subject_level_i-1 to 1
87
- column_name = f"Subject Level {level}"
88
-
89
- # Start checking above the previous found index
90
- current_index = subject_level_start - 1
91
-
92
- while current_index >= 0 and pd.isna(
93
- filtered_df.loc[current_index, column_name]
94
- ):
95
- current_index -= 1 # Move up while NaN is found
96
-
97
- # Move one row down to get the last valid row in 'Subject Level level'
98
- subject_level_start = current_index + 1
99
-
100
- # Ensure we store the correct value at each subject level
101
- if subject_level_start in filtered_df.index:
102
- subject_level_values[column_name] = filtered_df.loc[
103
- subject_level_start - 1, column_name
104
- ]
105
-
106
- # Ensure valid slicing range
107
- min_start_index = subject_level_start
108
-
109
- if min_start_index < first_target_index:
110
- filtered_df = filtered_df.loc[min_start_index:first_target_index]
111
- else:
112
- filtered_df = pd.DataFrame()
113
-
114
- return subject_level_values, filtered_df
115
-
116
-
117
- def extract_heirarchy(full_code, target_value):
118
- # df = pd.read_excel(
119
- # r"C:\Users\mukul.rawat\OneDrive - Candid\Documents\Projects\Gen AI\azure_devops\ask-candid-assistant\PCS_Taxonomy_Definitions_2024.xlsx"
120
- # )
121
- df = pd.read_excel(r"C:\Users\siqi.deng\Downloads\PCS_Taxonomy_Definitions_2024.xlsx")
122
- filtered_df = df[df["PCS Code"].str.startswith(full_code[:2], na=False)]
123
- for i in range(1, 5):
124
- column_name = f"Subject Level {i}"
125
- if (df[column_name].str.strip() == target_value).any():
126
- break
127
-
128
- subject_level_values, filtered_df = find_subject_levels(
129
- filtered_df, i, target_value
130
- )
131
- sorted_values = [
132
- value
133
- for key, value in sorted(
134
- subject_level_values.items(), key=lambda x: int(x[0].split()[-1])
135
- )
136
- ]
137
- # Joining values in the required format
138
- result = " : ".join(sorted_values)
139
- return result
140
-
141
-
142
- class GraphState(TypedDict):
143
- query: str = Field(
144
- ..., description="The user's query to be processed by the system."
145
- )
146
- agent_out: str = Field(
147
- ...,
148
- description="The output generated by the AI agent after processing the query.",
149
- )
150
- next_step: str = Field(
151
- ..., description="The next step in the workflow, determined by query analysis."
152
- )
153
- es_query: dict = Field(
154
- ..., description="The Elasticsearch query generated or used by the agent."
155
- )
156
-
157
- es_result: dict = Field(
158
- ...,
159
- description="The Elasticsearch query result generated or used by the agent.",
160
- )
161
- pcs_codes: dict = Field(..., description="pcs codes")
162
-
163
-
164
- class AnalysisResult(BaseModel):
165
- category: str = Field(..., description="Either 'general' or 'Database'")
166
-
167
-
168
- def agent_factory(llm: LLM) -> AgentExecutor:
169
- """
170
- Creates and configures an AgentExecutor instance for interacting with Elasticsearch.
171
-
172
- This function initializes an OpenAI GPT-4-based LLM with specific parameters,
173
- constructs a prompt tailored for Elasticsearch assistance, and integrates the
174
- agent with a set of tools to handle user queries. The agent is designed to work
175
- with OpenAI functions for enhanced capabilities.
176
-
177
- Returns:
178
- AgentExecutor: Configured agent ready to execute tasks with specified tools,
179
- providing detailed intermediate steps for transparency.
180
- """
181
-
182
- # llm = ChatOpenAI(
183
- # model="gpt-4o", temperature=0, api_key=OPENAI["key"], streaming=False
184
- # )
185
-
186
- tags_ = []
187
- agent = AgentType.OPENAI_FUNCTIONS
188
- tags_.append(agent.value if isinstance(agent, AgentType) else agent)
189
- # Create the prompt
190
- prompt = ChatPromptTemplate.from_messages(
191
- [
192
- ("system", "You are a helpful elasticsearch assistant"),
193
- MessagesPlaceholder(variable_name="chat_history", optional=True),
194
- ("human", "{input}"),
195
- MessagesPlaceholder(variable_name="agent_scratchpad"),
196
- ]
197
- )
198
-
199
- # Create the agent
200
- agent_obj = create_openai_functions_agent(llm, tools, prompt)
201
-
202
- return AgentExecutor.from_agent_and_tools(
203
- agent=agent_obj,
204
- tools=tools,
205
- tags=tags_,
206
- verbose=True,
207
- return_intermediate_steps=True,
208
- )
209
-
210
-
211
- def agent_factory_claude(llm: LLM) -> AgentExecutor:
212
- """
213
- Creates and configures an AgentExecutor instance for interacting with Elasticsearch.
214
-
215
- This function initializes an OpenAI GPT-4-based LLM with specific parameters,
216
- constructs a prompt tailored for Elasticsearch assistance, and integrates the
217
- agent with a set of tools to handle user queries. The agent is designed to work
218
- with OpenAI functions for enhanced capabilities.
219
-
220
- Returns:
221
- AgentExecutor: Configured agent ready to execute tasks with specified tools,
222
- providing detailed intermediate steps for transparency.
223
- """
224
-
225
- # llm = ChatOpenAI(
226
- # model="gpt-4o", temperature=0, api_key=OPENAI["key"], streaming=False
227
- # )
228
-
229
- # tags_ = []
230
- # agent = AgentType.OPENAI_FUNCTIONS
231
- # tags_.append(agent.value if isinstance(agent, AgentType) else agent)
232
- # Create the prompt
233
- prompt = ChatPromptTemplate.from_messages(
234
- [
235
- ("system", "You are a helpful elasticsearch assistant"),
236
- MessagesPlaceholder(variable_name="chat_history", optional=True),
237
- ("human", "{input}"),
238
- MessagesPlaceholder(variable_name="agent_scratchpad"),
239
- ]
240
- )
241
-
242
- agent = create_tool_calling_agent(llm, tools, prompt)
243
- agent_executor = AgentExecutor.from_agent_and_tools(
244
- agent=agent, tools=tools, verbose=True, return_intermediate_steps=True
245
- )
246
- # Create the agent
247
- return agent_executor
248
-
249
-
250
- # define graph node functions
251
- def general_query(state: GraphState, llm: LLM) -> GraphState:
252
- """
253
- Processes a user query using an LLM and updates the graph state with the response.
254
-
255
- Args:
256
- state (GraphState): Current graph state containing the user's query.
257
- llm (LLM): Language model to process the query.
258
-
259
- Returns:
260
- GraphState: Updated state with the LLM's response in "agent_out".
261
- """
262
- print("> General query")
263
- prompt = ChatPromptTemplate.from_template(
264
- "Answer based on the user's query: {query}"
265
- )
266
- chain = prompt | llm
267
- response = chain.invoke({"query": state["query"]})
268
- if isinstance(response, BaseMessage):
269
- state["agent_out"] = response.content
270
- else:
271
- state["agent_out"] = str(response)
272
- return state
273
-
274
-
275
- def database_agent(state: GraphState, llm: LLM) -> GraphState:
276
- """
277
- Executes a database query using an Elasticsearch agent and updates the graph state.
278
-
279
- The agent queries indices and field names in the Elasticsearch database,
280
- selects the appropriate index (`organization_dev_2`), and answers the user's question.
281
-
282
- Args:
283
- state (GraphState): Current graph state containing the user's query.
284
-
285
- Returns:
286
- GraphState: Updated state with the agent's output in "agent_out" and
287
- the Elasticsearch query in "es_query".
288
- """
289
-
290
- print("> database agent")
291
- input_data = {
292
- "input": f"""
293
- You are an Elasticsearch database agent designed to accurately understand and respond to user queries. Follow these steps:
294
-
295
- 1. Understand the user query to determine the required information.
296
- 2. Query the indices in the Elasticsearch database.
297
- 3. Retrieve the mappings and field names relevant to the query.
298
- 4. Use the organization_dev_2 index to extract the necessary data.
299
- 5. Present the response in a clear and natural language format, addressing the user's question directly.
300
-
301
- User's quer:
302
- ```{state["query"]}```
303
- """
304
- }
305
- agent_exec = agent_factory_claude(llm)
306
- res = agent_exec.invoke(input_data)
307
- state["agent_out"] = res["output"]
308
-
309
- es_queries, es_results = {}, {}
310
- for i, action in enumerate(res.get("intermediate_steps", []), start=1):
311
- if action[0].tool == "elastic_index_search_tool":
312
- es_queries[f"query_{i}"] = json.loads(
313
- action[0].tool_input.get("query") or "{}"
314
- )
315
- es_results[f"query_{i}"] = ast.literal_eval(action[-1] or "{}")
316
-
317
- # if len(res["intermediate_steps"]) > 1:
318
- # es_queries = {
319
- # f"query_{i}": action[0].tool_input.get("query", "")
320
- # for i, action in enumerate(res.get("intermediate_steps", []), start=1)
321
- # if action[0].tool == "elastic_index_search_tool"
322
- # }
323
-
324
- # es_results = {
325
- # f"result_{i}": action[-1]
326
- # for i, action in enumerate(res.get("intermediate_steps", []), start=1)
327
- # if action[0].tool == "elastic_index_search_tool"
328
- # }
329
-
330
- # state["es_query"] = es_queries
331
- # state["es_result"] = es_results
332
- # else:
333
- # state["es_query"] = res["intermediate_steps"][-1][0].tool_input["query"]
334
- # state["es_result"] = {"result": res["intermediate_steps"][-2][-1]}
335
-
336
- state["es_query"] = es_queries
337
- state["es_result"] = es_results
338
- return state
339
-
340
-
341
- def analyse_query(state: GraphState, llm: LLM) -> GraphState:
342
- """
343
- Analyzes the user's query to classify it as either general or database-specific
344
- and determines the next processing step.
345
-
346
- Args:
347
- state (GraphState): Current graph state containing the user's query.
348
- llm (LLM): Language model used for query analysis.
349
-
350
- Returns:
351
- GraphState: Updated state with the classification result and the
352
- next processing step in "next_step".
353
- """
354
-
355
- print("> analyse query")
356
- prompt_template = """Your task is to analyze the query ```{query}``` and classify it in:
357
- general: it's a basic general enquiry
358
- Database: query which is complicated and would require to go into the database and extract specific information
359
- Output format:
360
- {{"category": "<your_classification>"}}
361
- """
362
-
363
- # Create the prompt
364
- prompt = ChatPromptTemplate.from_template(prompt_template)
365
-
366
- # Define the parser
367
- parser = PydanticOutputParser(pydantic_object=AnalysisResult)
368
-
369
- # Create the chain
370
- chain = RunnableSequence(prompt, llm)
371
- # Invoke the chain with the query
372
- response = chain.invoke({"query": state["query"]})
373
- if "Database" in response.content:
374
- state["next_step"] = "es_database_agent"
375
- else:
376
- state["next_step"] = "general_query"
377
- return state
378
-
379
-
380
- def final_answer(state: GraphState, llm: LLM) -> GraphState:
381
- """
382
- Generates and presents the final response based on the user's query and the AI's output.
383
-
384
- Args:
385
- state (GraphState): Current graph state containing the query and AI output.
386
- llm (LLM): Language model used to format the final response.
387
-
388
- Returns:
389
- GraphState: Updated state with the formatted final answer in "agent_out".
390
- """
391
-
392
- print("> Final Answer")
393
- prompt_template = """
394
- You are a chat agent that takes outputs generated by Elasticsearch and presents them in a conversational, natural language format, as if responding to a user's query.
395
-
396
- Query: ```{query}```
397
-
398
- AI Output:
399
- ```{output}```
400
- """
401
- prompt = ChatPromptTemplate.from_template(prompt_template)
402
- chain = RunnableSequence(prompt, llm)
403
- response = chain.invoke({"query": state["query"], "output": state["agent_out"]})
404
-
405
- return {"agent_out": response.content}
406
-
407
-
408
- def build_compute_graph(llm: LLM) -> StateGraph:
409
- """
410
- Constructs a compute graph for processing user queries using a defined workflow.
411
-
412
- The workflow includes nodes for query analysis, handling general or database-specific queries,
413
- and generating the final response. Conditional logic determines the path based on query type.
414
-
415
- Args:
416
- llm (LLM): Language model to be used in various nodes for processing queries.
417
-
418
- Returns:
419
- StateGraph: Configured compute graph ready for execution.
420
- """
421
- # Create the workflow
422
- workflow = StateGraph(GraphState)
423
-
424
- # Add nodes
425
- workflow.add_node("analyse", partial(analyse_query, llm=llm))
426
- workflow.add_node("general_query", partial(general_query, llm=llm))
427
- workflow.add_node("es_database_agent", partial(database_agent, llm=llm))
428
- workflow.add_node("final_answer", partial(final_answer, llm=llm))
429
-
430
- # Set entry point
431
- workflow.set_entry_point("analyse")
432
-
433
- # Add conditional edges
434
- workflow.add_conditional_edges(
435
- "analyse",
436
- lambda x: x["next_step"], # Use the return value of analyse_query directly
437
- {"es_database_agent": "es_database_agent", "general_query": "general_query"},
438
- )
439
-
440
- # Add edges to end the workflow
441
- workflow.add_edge("es_database_agent", "final_answer")
442
- workflow.add_edge("general_query", "final_answer")
443
- workflow.add_edge("final_answer", END)
444
-
445
- return workflow
446
-
447
-
448
- class ElasticGraph(StateGraph):
449
- llm: LLM
450
- tools: List[Tool]
451
-
452
- def __init__(self, llm: LLM, tools: List[Tool]):
453
- super().__init__(GraphState)
454
- self.llm = llm
455
- self.tools = tools
456
- self.construct_graph()
457
-
458
- def Extract_PCS_Codes(self, state):
459
- """Todo: Add Subject heirarchies, Population, Geo"""
460
- print("query", state["query"])
461
- autocoding_api = AutocodingAPI()
462
- autocoding_response = autocoding_api(text=state["query"]).get("data", {})
463
- # population_served = autocoding_response.get("population", {})
464
- subjects = autocoding_response.get("subject", {})
465
- descriptions = []
466
- heirarchy_string = []
467
- if subjects and isinstance(subjects, list) and "description" in subjects[0]:
468
- for subject in subjects:
469
- # if subject['description'] in subjects_list:
470
- descriptions.append(subject["description"])
471
- heirarchy_string.append(
472
- extract_heirarchy(subject["full_code"], subject["description"])
473
- )
474
- print("descriptions", descriptions)
475
-
476
- populations = autocoding_response.get("population", {})
477
- population_dict = []
478
- if (
479
- populations
480
- and isinstance(populations, list)
481
- and "description" in populations[0]
482
- ):
483
- for population in populations:
484
- population_dict.append(population["description"])
485
- state["pcs_codes"] = {
486
- "subject": descriptions,
487
- "heirarchy_string": heirarchy_string,
488
- "population": population_dict,
489
- }
490
- print("pcs_codes_new", state["pcs_codes"])
491
- return state
492
-
493
- def agent_factory(self) -> AgentExecutor:
494
- """
495
- Creates and configures an AgentExecutor instance for interacting with Elasticsearch.
496
-
497
- This function initializes an OpenAI GPT-4-based LLM with specific parameters,
498
- constructs a prompt tailored for Elasticsearch assistance, and integrates the
499
- agent with a set of tools to handle user queries. The agent is designed to work
500
- with OpenAI functions for enhanced capabilities.
501
-
502
- Returns:
503
- AgentExecutor: Configured agent ready to execute tasks with specified tools,
504
- providing detailed intermediate steps for transparency.
505
- """
506
-
507
- # llm = ChatOpenAI(
508
- # model="gpt-4o", temperature=0, api_key=OPENAI["key"], streaming=False
509
- # )
510
-
511
- tags_ = []
512
- agent = AgentType.OPENAI_FUNCTIONS
513
- tags_.append(agent.value if isinstance(agent, AgentType) else agent)
514
- # Create the prompt
515
- prompt = ChatPromptTemplate.from_messages(
516
- [
517
- ("system", "You are a helpful elasticsearch assistant"),
518
- MessagesPlaceholder(variable_name="chat_history", optional=True),
519
- ("human", "{input}"),
520
- MessagesPlaceholder(variable_name="agent_scratchpad"),
521
- ]
522
- )
523
-
524
- # Create the agent
525
- agent_obj = create_openai_functions_agent(self.llm, tools, prompt)
526
-
527
- return AgentExecutor.from_agent_and_tools(
528
- agent=agent_obj,
529
- tools=tools,
530
- tags=tags_,
531
- verbose=True,
532
- return_intermediate_steps=True,
533
- )
534
-
535
- def agent_factory_claude(self, pcs_codes, prefix) -> AgentExecutor:
536
- """
537
- Creates and configures an AgentExecutor instance for interacting with Elasticsearch.
538
-
539
- This function initializes an OpenAI GPT-4-based LLM with specific parameters,
540
- constructs a prompt tailored for Elasticsearch assistance, and integrates the
541
- agent with a set of tools to handle user queries. The agent is designed to work
542
- with OpenAI functions for enhanced capabilities.
543
-
544
- Returns:
545
- AgentExecutor: Configured agent ready to execute tasks with specified tools,
546
- providing detailed intermediate steps for transparency.
547
- """
548
- prompt = ChatPromptTemplate.from_messages(
549
- [
550
- ("system", f"You are a helpful elasticsearch assistant. {prefix}"),
551
- MessagesPlaceholder(variable_name="chat_history", optional=True),
552
- ("human", "{input}"),
553
- MessagesPlaceholder(variable_name="agent_scratchpad"),
554
- ]
555
- )
556
-
557
- tools = [
558
- # ListIndicesTool(),
559
- IndexShowDataTool(),
560
- IndexDetailsTool(),
561
- create_search_tool(pcs_codes=pcs_codes),
562
- ]
563
- agent = create_tool_calling_agent(self.llm, tools, prompt)
564
-
565
- agent_executor = AgentExecutor.from_agent_and_tools(
566
- agent=agent,
567
- tools=tools,
568
- verbose=True,
569
- return_intermediate_steps=True,
570
- )
571
- # Create the agent
572
- return agent_executor
573
-
574
- def analyse_query(self, state: GraphState) -> GraphState:
575
- """
576
- Analyzes the user's query to classify it as either general or database-specific
577
- and determines the next processing step.
578
-
579
- Args:
580
- state (GraphState): Current graph state containing the user's query.
581
- llm (LLM): Language model used for query analysis.
582
-
583
- Returns:
584
- GraphState: Updated state with the classification result and the
585
- next processing step in "next_step".
586
- """
587
-
588
- print("> analyse query")
589
- prompt_template = """Your task is to analyze the query ```{query}``` and classify it in:
590
- grant: Grant Index - A query where users seek information about grants, funding opportunities, and grantmakers. This includes inquiries about the purpose of funding, eligibility criteria, application processes, grant recipients, funding amounts, deadlines, and how grants can be used for specific projects or initiatives. Users may also request grants tailored to their unique needs, industries, or social impact goals
591
-
592
- org: Org Index - Query which asks speicific details about the organizations, their mission statement, where they are located
593
- Output format:
594
- {{"category": "<your_classification>"}}
595
- """
596
- parser = PydanticOutputParser(pydantic_object=AnalysisResult)
597
-
598
- # Create the prompt
599
- prompt = PromptTemplate(
600
- template=prompt_template,
601
- input_variables=["query"],
602
- partial_variables={"format_instructions": parser.get_format_instructions()},
603
- )
604
- # Create the chain
605
- chain = RunnableSequence(prompt, self.llm, parser)
606
- # Invoke the chain with the query
607
- response = chain.invoke({"query": state["query"]})
608
- if response.category == "grant":
609
- state["next_step"] = "grant-index"
610
- else:
611
- state["next_step"] = "org-index"
612
- return state
613
-
614
- def grant_index_agent(self, state: GraphState) -> GraphState:
615
- print("> Grant Index Agent")
616
- # autocoding test
617
-
618
- input_data = {
619
- "input": f"""
620
- You are an Elasticsearch database agent designed to accurately understand and respond to user queries. Follow these steps:
621
-
622
- 1. Understand the user query to determine the required information.
623
- 2. Query the indices in the Elasticsearch database.
624
- 3. Retrieve the mappings and field names relevant to the query.
625
- 4. Use the ``grants_qa_1`` index to extract the necessary data.
626
- 5. Ensure that you correctly identify the grantmaker (funder) or recipient (funded entity) if mentioned in the query.
627
- Users may not always provide the exact name, so the Elasticsearch query should accommodate partial or incomplete names
628
- by searching for relevant keywords.
629
- 6. Present the response in a clear and natural language format, addressing the user's question directly.
630
-
631
- Description of some of the fields in the index but rest of the fields which are not here should be easy to understand:
632
- *fiscal_year: Year when grantmaker allocates budget for funding and grants. format YYYY
633
- *recipient_state: is abbreviated for eg. NY, FL, CA
634
- *recipient_city - Full Name of the City e.g, New York City, Boston
635
- *recipient_country - Country Abbreviation of the recipient organization e.g USA
636
-
637
- Note: Do not include `title`, `program_area`, `text` field in the elastic search query
638
- User's query:
639
- ```{state["query"]}```
640
- """
641
- }
642
- pcs_codes = state["pcs_codes"]
643
- pcs_match_term = ""
644
- for pcs_code in pcs_codes["subject"]:
645
- if pcs_code != "Philanthropy":
646
- pcs_match_term += f"*'pcs_v3.subject.value.name': {pcs_code}* \n"
647
-
648
- for pcs_code in pcs_codes["population"]:
649
- if pcs_code != "Other population":
650
- pcs_match_term += f"*'pcs_v3.population.value.name': {pcs_code}* \n"
651
- print("pcs_match_term", pcs_match_term)
652
- prefix = f"""
653
- You are an intelligent agent tasked with generating accurate Elasticsearch DSL queries.
654
- Analyze the intent behind the query and determine the appropriate Elasticsearch operations required.
655
- Guidelines for generating right elastic seach query:
656
- 1. Automatically determine whether to return document hits or aggregation results based on the query structure.
657
- 2. Use keyword fields instead of text fields for aggregations and sorting to avoid fielddata errors
658
- 3. Avoid using field.keyword if a keyword field is already present to prevent redundant queries.
659
- 4. Ensure efficient query execution by selecting appropriate query types for filtering, searching, and aggregating.
660
-
661
- Instruction for pcs_v3 Field-
662
- If {pcs_codes['subject']} not empty:
663
- Only include all of the following match terms. No other pcs_v3 fields should be added, duplicated, or altered except for those listed below.
664
- - {pcs_match_term}
665
- """
666
- agent_exec = self.agent_factory_claude(
667
- pcs_codes=state["pcs_codes"], prefix=prefix
668
- )
669
- res = agent_exec.invoke(input_data)
670
- state["agent_out"] = res["output"]
671
- es_queries, es_results = {}, {}
672
- for i, action in enumerate(res.get("intermediate_steps", []), start=1):
673
- if action[0].tool == "elastic_index_search_tool":
674
- print("query", action[0].tool_input.get("query"))
675
- es_queries[f"query_{i}"] = json.loads(
676
- action[0].tool_input.get("query") or "{}"
677
- )
678
- es_results[f"query_{i}"] = ast.literal_eval(action[-1] or "{}")
679
-
680
- state["es_query"] = es_queries
681
- state["es_result"] = es_results
682
- return state
683
-
684
- def org_index_agent(self, state: GraphState) -> GraphState:
685
- """
686
- Executes a database query using an Elasticsearch agent and updates the graph state.
687
-
688
- The agent queries indices and field names in the Elasticsearch database,
689
- selects the appropriate index (`organization_dev_2`), and answers the user's question.
690
-
691
- Args:
692
- state (GraphState): Current graph state containing the user's query.
693
-
694
- Returns:
695
- GraphState: Updated state with the agent's output in "agent_out" and
696
- the Elasticsearch query in "es_query".
697
- """
698
-
699
- print("> Org Index Agent")
700
- mapping_description = """
701
- "admin1_code": "state abbreviation"
702
- "admin1_description": "Full name/label of the state"
703
- "city": Full Name of the city with 1st letter being capital for e.g. New York City
704
- "assets": "The assets value of the most recent fiscals available for the organization."
705
- "country_code": "Country abbreviation"
706
- "country_name": "Country name"
707
- "fiscal_year": "The year of the most recent fiscals available for the organization. (YYYY format)"
708
- "mission_statement": "The mission statement of the organization."
709
- "roles": "grantmaker: Indicates the organization gives grants., recipient: Indicates the organization receives grants., company: Indicates the organization is a company/corporation."
710
-
711
- """
712
- input_data = {
713
- "input": f"""
714
- You are an Elasticsearch database agent designed to accurately understand and respond to user queries. Follow these steps:
715
-
716
- 1. Understand the user query to determine the required information.
717
- 2. Query the indices in the Elasticsearch database.
718
- 3. Retrieve the mappings and field names relevant to the query.
719
- 4. Use the `organization_qa_ds1` index to extract the necessary data.
720
- 5. Present the response in a clear and natural language format, addressing the user's question directly.
721
-
722
-
723
- Given Below is mapping description of some of the fields
724
- ```{mapping_description}```
725
-
726
-
727
- User's query:
728
- ```{state["query"]}```
729
- """
730
- }
731
-
732
- pcs_codes = state["pcs_codes"]
733
- pcs_match_term = ""
734
- for pcs_code in pcs_codes["subject"]:
735
- pcs_match_term += f'"taxonomy_descriptions": "{pcs_code}" \n"'
736
-
737
- print("pcs_match_term", pcs_match_term)
738
- prefix = f"""You are an intelligent agent tasked with generating accurate Elasticsearch DSL queries.
739
- Analyze the intent behind the query and determine the appropriate Elasticsearch operations required.
740
- Guidelines for generating right elastic seach query:
741
- 1. Automatically determine whether to return document hits or aggregation results based on the query structure.
742
- 2. Use keyword fields instead of text fields for aggregations and sorting to avoid fielddata errors
743
- 3. Avoid using field.keyword if a keyword field is already present to prevent redundant queries.
744
- 4. Ensure efficient query execution by selecting appropriate query types for filtering, searching, and aggregating.
745
-
746
- Instructions to use `taxonomy_descriptions` field:
747
- If {pcs_codes['subject']} not empty, only add the following match term:
748
- Only add the following `match` term, No other `taxonomy_descriptions` fields should be added, duplicated, or modified except belowIf {pcs_codes['subject']} not empty,
749
- - {pcs_match_term}
750
-
751
-
752
- Avoid using `ntee_major_description` field in the es query
753
-
754
- """
755
- agent_exec = self.agent_factory_claude(
756
- pcs_codes=state["pcs_codes"], prefix=prefix
757
- )
758
- res = agent_exec.invoke(input_data)
759
- state["agent_out"] = res["output"]
760
-
761
- es_queries, es_results = {}, {}
762
- for i, action in enumerate(res.get("intermediate_steps", []), start=1):
763
- if action[0].tool == "elastic_index_search_tool":
764
- es_queries[f"query_{i}"] = json.loads(
765
- action[0].tool_input.get("query") or "{}"
766
- )
767
- es_results[f"query_{i}"] = ast.literal_eval(action[-1] or "{}")
768
-
769
- state["es_query"] = es_queries
770
- state["es_result"] = es_results
771
- return state
772
-
773
- def final_answer(self, state: GraphState) -> GraphState:
774
- """
775
- Generates and presents the final response based on the user's query and the AI's output.
776
-
777
- Args:
778
- state (GraphState): Current graph state containing the query and AI output.
779
- llm (LLM): Language model used to format the final response.
780
-
781
- Returns:
782
- GraphState: Updated state with the formatted final answer in "agent_out".
783
- """
784
-
785
- print("> Final Answer")
786
- prompt_template = """
787
- You are a chat agent that takes outputs generated by Elasticsearch and presents them in a conversational, natural language format, as if responding to a user's query.
788
-
789
- Query: ```{query}```
790
-
791
- AI Output:
792
- ```{output}```
793
- """
794
- prompt = ChatPromptTemplate.from_template(prompt_template)
795
- chain = RunnableSequence(prompt, self.llm)
796
- response = chain.invoke({"query": state["query"], "output": state["agent_out"]})
797
-
798
- return {"agent_out": response.content}
799
-
800
- def construct_graph(self) -> StateGraph:
801
- """
802
- Constructs a compute graph for processing user queries using a defined workflow.
803
-
804
- The workflow includes nodes for query analysis, handling general or database-specific queries,
805
- and generating the final response. Conditional logic determines the path based on query type.
806
-
807
- Args:
808
- llm (LLM): Language model to be used in various nodes for processing queries.
809
-
810
- Returns:
811
- StateGraph: Configured compute graph ready for execution.
812
- """
813
-
814
- # Add nodes
815
- self.add_node("Context_Extraction", self.Extract_PCS_Codes)
816
- self.add_node("analyse", self.analyse_query)
817
- self.add_node("grant-index", self.grant_index_agent)
818
- self.add_node("org-index", self.org_index_agent)
819
- self.add_node("final_answer", self.final_answer)
820
-
821
- # Set entry point
822
- self.set_entry_point("Context_Extraction")
823
- self.add_edge("Context_Extraction", "analyse")
824
-
825
- # Add conditional edges
826
- self.add_conditional_edges(
827
- "analyse",
828
- lambda x: x["next_step"], # Use the return value of analyse_query directly
829
- {"org-index": "org-index", "grant-index": "grant-index"},
830
- )
831
-
832
- # Add edges to end the workflow
833
- self.add_edge("org-index", "final_answer")
834
- self.add_edge("grant-index", "final_answer")
835
- self.add_edge("final_answer", END)
836
-
837
-
838
- def build_elastic_graph(llm: LLM, tools: List[Tool]):
839
- """Compile Elastic Agent Graph"""
840
- elastic_graph = ElasticGraph(llm=llm, tools=tools)
841
- graph = elastic_graph.compile()
842
- return graph
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ask_candid/agents/schema.py DELETED
@@ -1,27 +0,0 @@
1
- from typing import List, Dict, TypedDict, Sequence, Union, Annotated
2
-
3
- from langchain_core.messages import BaseMessage
4
- from langgraph.graph.message import add_messages
5
-
6
-
7
- class Context(TypedDict):
8
- """PCS + geonames context payload for common tasks like recommendations.
9
- """
10
- subject: List[str]
11
- population: List[str]
12
- geography: List[Union[str, int]]
13
-
14
-
15
- class AgentState(TypedDict):
16
- """State of the chat agent for the execution graph(s).
17
- """
18
- # The add_messages function defines how an update should be processed
19
- # Default is to replace. add_messages says "append"
20
- messages: Annotated[Sequence[BaseMessage], add_messages]
21
- user_input: str
22
- org_dict: Dict
23
-
24
- # Recommendation-specific fields
25
- intent: str
26
- context: Context
27
- recommendation: str