Spaces:
Runtime error
Runtime error
File size: 39,182 Bytes
1dfef0f 26f5620 03aebad 836d49c 26f5620 cd8de6f 26f5620 cd8de6f d036780 cd8de6f 26f5620 2d14e5a b0eca46 26f5620 87c8549 16c9822 01cc5e8 b7e4e52 aaf11bc 9b810cb b7e4e52 3fb3844 55391d4 97851ae abd3036 d5ab1b1 ff8595b 95010ac 9b810cb 93a2770 6ead180 aaf11bc c63d0c0 cf02c0e 65f51b7 069acab 26e01cd 0db0aa5 9eabe16 860b981 4d61251 cea2331 37ebfbe fddf6b5 e35d057 fe25c9a de4ea78 918897e b65c6f7 0636b11 f03d005 03aebad 450a49d fe25c9a 3970176 fe25c9a 65f51b7 fe25c9a 3970176 450a49d 3970176 450a49d 3970176 450a49d 3970176 450a49d 65f51b7 450a49d 3970176 450a49d 3970176 fe25c9a 7b1f7dd 26f5620 de4ea78 26f5620 de4ea78 26f5620 de4ea78 26f5620 de4ea78 ef3d9bb de4ea78 7df3234 26f5620 f03d005 9af2eae 26f5620 7240bca f03d005 ef3d9bb 26f5620 f03d005 26f5620 b22ce48 26f5620 1dfef0f 26f5620 ef3d9bb 26f5620 93a2770 3970176 93a2770 3970176 93a2770 3970176 93a2770 3970176 93a2770 3970176 93a2770 3970176 93a2770 3970176 93a2770 95010ac de4ea78 95010ac 26f5620 ac6b8be 9027aff ac6b8be 26f5620 70f8384 ac6b8be b997ea4 de4ea78 b997ea4 29304ec de4ea78 29304ec ac6b8be b997ea4 ac6b8be 7b1f7dd 29304ec 7b1f7dd cf02c0e 9ac015d cf02c0e d7bc0b0 9ac015d 9fabb76 9ac015d 6ead180 cf02c0e 3df23ae cf02c0e 9ac015d 2a62957 9c7a7bf 2a62957 b034ca7 9c7a7bf b034ca7 9c7a7bf 2a62957 9c7a7bf b034ca7 9c7a7bf b034ca7 9c7a7bf 9ac015d 3b7eced 9ac015d f5a754e 9ac015d 4b0f2c2 9ac015d 62c3d7a 9ac015d 9fabb76 9ac015d 6ead180 3df23ae 6ead180 9ac015d 6ead180 65f51b7 5a9cf8b 2131451 9d72879 0db0aa5 9eabe16 0db0aa5 fddf6b5 f1d6b50 37ebfbe fddf6b5 f1d6b50 fddf6b5 94dcdd5 0db0aa5 e35d057 37ebfbe 5a9cf8b 26e01cd 5a9cf8b 26e01cd de4ea78 26e01cd de4ea78 26e01cd 65f51b7 26e01cd 5a9cf8b 26e01cd 7a645cc 5a9cf8b 26e01cd 6ead180 7622d0c 5a9cf8b 26e01cd 6ead180 7622d0c 6ead180 7622d0c 6ead180 94e7570 9b810cb 65f51b7 9027aff 26f5620 65f51b7 7622d0c 65f51b7 26f5620 65f51b7 7622d0c 65f51b7 26f5620 65f51b7 9027aff 7622d0c 7240bca 65f51b7 26f5620 9027aff 65f51b7 7b1f7dd 3cc3529 7b1f7dd 3cc3529 7b1f7dd de4ea78 3cc3529 7b1f7dd 3cc3529 de4ea78 7b1f7dd 67f0c93 7b1f7dd 67f0c93 7b1f7dd 3cc3529 67f0c93 7b1f7dd 67f0c93 3cc3529 7b1f7dd 3cc3529 65f51b7 7622d0c 65f51b7 7b1f7dd 3cc3529 65f51b7 3cc3529 65f51b7 3cc3529 de4ea78 3cc3529 de4ea78 3cc3529 591c3ba de4ea78 591c3ba de4ea78 7b1f7dd de4ea78 7b1f7dd de4ea78 7b1f7dd de4ea78 7b1f7dd de4ea78 7b1f7dd de4ea78 fe25c9a de4ea78 fe25c9a de4ea78 fe25c9a 7b1f7dd 65f51b7 67f0c93 65f51b7 3cc3529 67f0c93 3cc3529 67f0c93 3cc3529 67f0c93 3cc3529 65f51b7 67f0c93 3cc3529 67f0c93 3cc3529 de4ea78 3cc3529 7b1f7dd de4ea78 3cc3529 7b1f7dd 3cc3529 7b1f7dd de4ea78 7b1f7dd 3cc3529 7b1f7dd 3cc3529 65f51b7 3cc3529 65f51b7 3cc3529 23ba2f5 a1d5445 c0d9cc5 a1d5445 c754c7a 23ba2f5 287fae2 c754c7a 23ba2f5 a1d5445 7622d0c a1d5445 cc0fca2 a1d5445 23ba2f5 cc0fca2 23ba2f5 a1d5445 3cc3529 65f51b7 3cc3529 65f51b7 3cc3529 65f51b7 3cc3529 65f51b7 3cc3529 65f51b7 d977a88 3cc3529 d977a88 3cc3529 d977a88 3cc3529 d977a88 3cc3529 d977a88 3cc3529 d977a88 3cc3529 d977a88 5a9cf8b 3cc3529 5a9cf8b 9027aff 9ac015d 5a5c64e ad00d9c 7622d0c ad00d9c 7622d0c c2a5d8c dae11a5 9027aff e35d057 dae11a5 5a5c64e dae11a5 7622d0c dae11a5 7a08145 dae11a5 7a08145 ef3d9bb e35d057 dae11a5 7622d0c e35d057 7622d0c c2a5d8c 7622d0c e35d057 dae11a5 23ba2f5 dae11a5 c2a5d8c 7622d0c dae11a5 23ba2f5 dae11a5 7622d0c dae11a5 7622d0c dae11a5 7622d0c f75a052 dae11a5 23ba2f5 c2a5d8c dae11a5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 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 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 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 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 |
# agent.py
import os
from dotenv import load_dotenv
from langgraph.graph import START, StateGraph, MessagesState
from langgraph.prebuilt import tools_condition
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_groq import ChatGroq
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_community.document_loaders import WikipediaLoader
from langchain_community.utilities import WikipediaAPIWrapper
from langchain_community.document_loaders import ArxivLoader
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.tools import tool
from langchain.tools.retriever import create_retriever_tool
from supabase.client import Client, create_client
from sentence_transformers import SentenceTransformer
from langchain.embeddings.base import Embeddings
from typing import List
import numpy as np
import yaml
import pandas as pd
import uuid
import requests
import json
from langchain_core.documents import Document
from langchain_community.vectorstores import FAISS
#from langchain.embeddings import BERTEmbeddings
#from langchain_community.embeddings import HuggingFaceEmbeddings
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api._errors import TranscriptsDisabled, VideoUnavailable
import re
from langchain_community.document_loaders import TextLoader, PyMuPDFLoader
from docx import Document as DocxDocument
import openpyxl
from io import StringIO
from transformers import BertTokenizer, BertModel
import torch
import torch.nn.functional as F
from langchain_community.chat_models import ChatOpenAI
from langchain_community.tools import Tool
import time
from huggingface_hub import InferenceClient
from langchain_community.llms import HuggingFaceHub
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
from huggingface_hub import login
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, BitsAndBytesConfig
from langchain_huggingface import HuggingFaceEndpoint
#from langchain.agents import initialize_agent
#from langchain.agents import AgentType
from typing import Union, List
from functools import reduce
import operator
from typing import Union
from functools import reduce
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api._errors import TranscriptsDisabled, VideoUnavailable
from langchain_community.vectorstores import FAISS
from langchain.schema import Document
load_dotenv()
@tool
def calculator(inputs: Union[str, dict]):
"""
Perform mathematical operations based on the operation provided.
Supports both binary (a, b) operations and list operations.
"""
# If input is a JSON string, parse it
if isinstance(inputs, str):
try:
import json
inputs = json.loads(inputs)
except Exception as e:
return f"Invalid input format: {e}"
# Handle list-based operations like SUM
if "list" in inputs:
nums = inputs.get("list", [])
op = inputs.get("operation", "").lower()
if not isinstance(nums, list) or not all(isinstance(n, (int, float)) for n in nums):
return "Invalid list input. Must be a list of numbers."
if op == "sum":
return sum(nums)
elif op == "multiply":
return reduce(operator.mul, nums, 1)
else:
return f"Unsupported list operation: {op}"
# Handle basic two-number operations
a = inputs.get("a")
b = inputs.get("b")
operation = inputs.get("operation", "").lower()
if a is None or b is None or not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
return "Both 'a' and 'b' must be numbers."
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide":
if b == 0:
return "Error: Division by zero"
return a / b
elif operation == "modulus":
return a % b
else:
return f"Unknown operation: {operation}"
@tool
def wiki_search(query: str) -> str:
"""Search Wikipedia for a query and return up to 2 results."""
search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
formatted_search_docs = "\n\n---\n\n".join(
[
f'<Document source="{doc.metadata.get("source", "Wikipedia")}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
for doc in search_docs
]
)
return formatted_search_docs
@tool
def wikidata_query(query: str) -> str:
"""
Run a SPARQL query on Wikidata and return results.
"""
endpoint_url = "https://query.wikidata.org/sparql"
headers = {
"Accept": "application/sparql-results+json"
}
response = requests.get(endpoint_url, headers=headers, params={"query": query})
data = response.json()
return json.dumps(data, indent=2)
@tool
def web_search(query: str) -> str:
"""Search Tavily for a query and return up to 3 results."""
tavily_key = os.getenv("TAVILY_API_KEY")
if not tavily_key:
return "Error: Tavily API key not set."
search_tool = TavilySearchResults(tavily_api_key=tavily_key, max_results=3)
search_docs = search_tool.invoke(query=query)
formatted_search_docs = "\n\n---\n\n".join(
[
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
for doc in search_docs
])
return formatted_search_docs
@tool
def arxiv_search(query: str) -> str:
"""Search Arxiv for a query and return maximum 3 result.
Args:
query: The search query."""
search_docs = ArxivLoader(query=query, load_max_docs=3).load()
formatted_search_docs = "\n\n---\n\n".join(
[
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
for doc in search_docs
])
return formatted_search_docs
@tool
def analyze_attachment(file_path: str) -> str:
"""
Analyzes attachments including PY, PDF, TXT, DOCX, and XLSX files and returns text content.
Args:
file_path: Local path to the attachment.
"""
if not os.path.exists(file_path):
return f"File not found: {file_path}"
try:
ext = file_path.lower()
if ext.endswith(".pdf"):
loader = PyMuPDFLoader(file_path)
documents = loader.load()
content = "\n\n".join([doc.page_content for doc in documents])
elif ext.endswith(".txt") or ext.endswith(".py"):
# Both .txt and .py are plain text files
with open(file_path, "r", encoding="utf-8") as file:
content = file.read()
elif ext.endswith(".docx"):
doc = DocxDocument(file_path)
content = "\n".join([para.text for para in doc.paragraphs])
elif ext.endswith(".xlsx"):
wb = openpyxl.load_workbook(file_path, data_only=True)
content = ""
for sheet in wb:
content += f"Sheet: {sheet.title}\n"
for row in sheet.iter_rows(values_only=True):
content += "\t".join([str(cell) if cell is not None else "" for cell in row]) + "\n"
else:
return "Unsupported file format. Please use PY, PDF, TXT, DOCX, or XLSX."
return content[:3000] # Limit output size for readability
except Exception as e:
return f"An error occurred while processing the file: {str(e)}"
@tool
def get_youtube_transcript(url: str) -> str:
"""
Fetch transcript text from a YouTube video.
Args:
url (str): Full YouTube video URL.
Returns:
str: Transcript text as a single string.
Raises:
ValueError: If no transcript is available or URL is invalid.
"""
try:
# Extract video ID
video_id = extract_video_id(url)
transcript = YouTubeTranscriptApi.get_transcript(video_id)
# Combine all transcript text
full_text = " ".join([entry['text'] for entry in transcript])
return full_text
except (TranscriptsDisabled, VideoUnavailable) as e:
raise ValueError(f"Transcript not available: {e}")
except Exception as e:
raise ValueError(f"Failed to fetch transcript: {e}")
@tool
def extract_video_id(url: str) -> str:
"""
Extract the video ID from a YouTube URL.
"""
match = re.search(r"(?:v=|youtu\.be/)([A-Za-z0-9_-]{11})", url)
if not match:
raise ValueError("Invalid YouTube URL")
return match.group(1)
# -----------------------------
# Load configuration from YAML
# -----------------------------
with open("config.yaml", "r") as f:
config = yaml.safe_load(f)
provider = config["provider"]
model_config = config["models"][provider]
#prompt_path = config["system_prompt_path"]
enabled_tool_names = config["tools"]
# -----------------------------
# Load system prompt
# -----------------------------
# load the system prompt from the file
with open("system_prompt.txt", "r", encoding="utf-8") as f:
system_prompt = f.read()
# System message
sys_msg = SystemMessage(content=system_prompt)
# -----------------------------
# Map tool names to functions
# -----------------------------
tool_map = {
"math": calculator,
"wiki_search": wiki_search,
"web_search": web_search,
"arxiv_search": arxiv_search,
"get_youtube_transcript": get_youtube_transcript,
"extract_video_id": extract_video_id,
"analyze_attachment": analyze_attachment,
"wikidata_query": wikidata_query
}
# Then define which tools you want enabled
enabled_tool_names = [
"math",
"wiki_search",
"web_search",
"arxiv_search",
"get_youtube_transcript",
"extract_video_id",
"analyze_attachment",
"wikidata_query"
]
tools = [tool_map[name] for name in enabled_tool_names]
# Safe version
tools = []
for name in enabled_tool_names:
if name not in tool_map:
print(f"โ Tool not found: {name}")
continue
tools.append(tool_map[name])
# -----------------------------
# Create FAISS Vector Store
# -----------------------------
import faiss
class MyVectorStore:
def __init__(self, index: faiss.Index):
self.index = index
def save_local(self, path: str):
# Save the FAISS index to the specified file
faiss.write_index(self.index, path)
print(f"Index saved to {path}")
@classmethod
def load_local(cls, path: str):
# Load the FAISS index from the specified file
index = faiss.read_index(path)
return cls(index)
# -----------------------------
# Prepare Documents
# -----------------------------
# Define the URL where the JSON file is hosted
import json
from langchain.schema import Document
def reverse_text(text: str) -> str:
return text[::-1].replace("\\", "") # Handle escaped quotes
# Load the JSON file
with open("https://huggingface.co/spaces/wt002/Final_Assignment_Project/blob/main/questions.json", "r", encoding="utf-8") as f:
data = json.load(f)
# Convert each question into a Document
docs = [
Document(
page_content=(
str(reverse_text(item["question"]))
if isinstance(item["question"], (list, bytes))
else reverse_text(item["question"])
if item["question"].startswith(('.', ','))
else item["question"]
),
metadata={
"task_id": item["task_id"],
"level": item["Level"],
"file_name": item["file_name"] # Added from your URL example
}
)
for item in data
if "question" in item and item["question"] # Skip empty questions
]
# Now extract texts
texts = [doc.page_content for doc in docs]
# Initialize the embedding model
embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
docs = [Document(page_content=texts, metadata={"task_id": item["task_id"]}) for item in data]
# Create the FAISS index
#vector_store = FAISS.from_documents(docs, embedding_model)
vector_store = FAISS.from_texts(texts = text_chunks, embedding = embeddings)
# Save the FAISS index
vector_store = MyVectorStore(index)
# Assuming you already have a FAISS index
index = faiss.IndexFlatL2(768) # Or whatever dimensionality your embeddings have
vector_store = MyVectorStore(index)
# Save
vector_store.save_local("/home/wendy/Downloads/faiss_index.index")
# Load
loaded_store = MyVectorStore.load_local("/home/wendy/Downloads/faiss_index.index")
# -----------------------------
# Create LangChain Retriever Tool
# -----------------------------
retriever = FAISS.load_local("faiss_index.index", embedding_model).as_retriever()
question_retriever_tool = create_retriever_tool(
retriever=retriever,
name="Question_Search",
description="A tool to retrieve documents related to a user's question."
)
# Define the LLM before using it
#llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo") # or "gpt-3.5-turbo" "gpt-4"
#llm = ChatMistralAI(model="mistral-7b-instruct-v0.1")
# Get the Hugging Face API token from the environment variable
#hf_token = os.getenv("HF_TOKEN")
llm = HuggingFaceEndpoint(
repo_id="HuggingFaceH4/zephyr-7b-beta",
task="text-generation",
huggingfacehub_api_token=os.getenv("HF_TOKEN"),
temperature=0.7,
max_new_tokens=512
)
# -------------------------------
# Step 8: Use the Planner, Classifier, and Decision Logic
# -------------------------------
def process_question(question):
# Step 1: Planner generates the task sequence
tasks = planner(question)
print(f"Tasks to perform: {tasks}")
# Step 2: Classify the task (based on question)
task_type = task_classifier(question)
print(f"Task type: {task_type}")
# Step 3: Use the classifier and planner to decide on the next task or node
state = {"question": question, "last_response": ""}
next_task = decide_task(state)
print(f"Next task: {next_task}")
# Step 4: Use node skipper logic (skip if needed)
skip = node_skipper(state)
if skip:
print(f"Skipping to {skip}")
return skip # Or move directly to generating answer
# Step 5: Execute task (with error handling)
try:
if task_type == "wiki_search":
response = wiki_search(question)
elif task_type == "math":
response = calculator(question)
else:
response = "Default answer logic"
# Step 6: Final response formatting
final_response = final_answer_tool(state, {'wiki_search': response})
return final_response
except Exception as e:
print(f"Error executing task: {e}")
return "Sorry, I encountered an error processing your request."
# Run the process
#question = "How many albums did Mercedes Sosa release between 2000 and 2009?"
#response = agent.invoke(question)
#print("Final Response:", response)
from langchain.schema import HumanMessage
def retriever(state: MessagesState, k: int = 4):
"""
Retrieves documents from the vector store using similarity scores,
applies a dynamic threshold filter, and returns updated message state.
Args:
state (MessagesState): Current message state including the user's query.
k (int): Number of top results to retrieve from the vector store.
Returns:
dict: Updated messages state including relevant documents or fallback message.
"""
query = state["messages"][0].content.strip()
results = vector_store.similarity_search_with_score(query, k=k)
# Determine dynamic similarity threshold
if any(keyword in query.lower() for keyword in ["who", "what", "where", "when", "why", "how"]):
threshold = 0.75
else:
threshold = 0.8
filtered = [doc for doc, score in results if score < threshold]
if not filtered:
response_msg = HumanMessage(content="No relevant documents found.")
else:
content = "\n\n".join(doc.page_content for doc in filtered)
response_msg = HumanMessage(content=f"Here are relevant reference documents:\n\n{content}")
return {"messages": [sys_msg] + state["messages"] + [response_msg]}
# ----------------------------------------------------------------
# LLM Loader
# ----------------------------------------------------------------
def get_llm(provider: str, config: dict):
if provider == "google":
from langchain_google_genai import ChatGoogleGenerativeAI
return ChatGoogleGenerativeAI(
model=config.get("model"),
temperature=config.get("temperature", 0.7),
google_api_key=config.get("api_key") # Optional: if needed
)
elif provider == "groq":
from langchain_groq import ChatGroq
return ChatGroq(
model=config.get("model"),
temperature=config.get("temperature", 0.7),
groq_api_key=config.get("api_key") # Optional: if needed
)
elif provider == "huggingface":
from langchain_huggingface import ChatHuggingFace
from langchain_huggingface import HuggingFaceEndpoint
return ChatHuggingFace(
llm=HuggingFaceEndpoint(
endpoint_url=config.get("url"),
temperature=config.get("temperature", 0.7),
huggingfacehub_api_token=config.get("api_key") # Optional
)
)
else:
raise ValueError(f"Invalid provider: {provider}")
# ----------------------------------------------------------------
# Planning & Execution Logic
# ----------------------------------------------------------------
def planner(question: str, tools: list) -> tuple:
"""
Select the best-matching tool(s) for a question based on keyword-based intent detection and tool metadata.
Returns the detected intent and matched tools.
"""
question = question.lower().strip()
# Define intent-based keywords
intent_keywords = {
"math": ["calculate", "evaluate", "add", "subtract", "multiply", "divide", "modulus", "plus", "minus", "times"],
"wiki_search": ["who is", "what is", "define", "explain", "tell me about", "overview of"],
"web_search": ["search", "find", "look up", "google", "latest news", "current info"],
"arxiv_search": ["arxiv", "research paper", "scientific paper", "preprint"],
"get_youtube_transcript": ["youtube", "watch", "play video", "show me a video"],
"extract_video_id": ["analyze video", "summarize video", "video content"],
"data_analysis": ["analyze", "plot", "graph", "data", "visualize"],
"wikidata_query": ["wikidata", "sparql", "run sparql", "query wikidata"],
"default": ["why", "how", "difference between", "compare", "what happens", "reason for", "cause of", "effect of"]
}
# Step 1: Identify intent
detected_intent = None
for intent, keywords in intent_keywords.items():
if any(keyword in question for keyword in keywords):
detected_intent = intent
break
# Step 2: Match tools by intent
matched_tools = []
if detected_intent:
for tool in tools:
name = getattr(tool, "name", "").lower()
description = getattr(tool, "description", "").lower()
if detected_intent in name or detected_intent in description:
matched_tools.append(tool)
# Step 3: Fallback to general-purpose/default tools if no match found
if not matched_tools:
matched_tools = [
tool for tool in tools
if "default" in getattr(tool, "name", "").lower()
or "qa" in getattr(tool, "description", "").lower()
]
return detected_intent, matched_tools if matched_tools else [tools[0]]
def task_classifier(question: str) -> str:
"""
Classifies the question into one of the predefined task categories.
"""
question = question.lower().strip()
# Context-aware intent patterns
if any(phrase in question for phrase in [
"calculate", "how much is", "what is the result of", "evaluate", "solve"
]) or any(op in question for op in ["add", "subtract", "multiply", "divide", "modulus", "plus", "minus", "times"]):
return "math"
elif any(phrase in question for phrase in [
"who is", "what is", "define", "explain", "tell me about", "give me an overview of"
]):
return "wiki_search"
elif any(phrase in question for phrase in [
"search", "find", "look up", "google", "get the latest", "current news", "trending"
]):
return "web_search"
elif any(phrase in question for phrase in [
"arxiv", "latest research", "scientific paper", "research paper", "preprint"
]):
return "arxiv_search"
elif any(phrase in question for phrase in [
"youtube", "watch", "play the video", "show me a video"
]):
return "get_youtube_transcript"
elif any(phrase in question for phrase in [
"analyze video", "summarize video", "what happens in the video", "video content"
]):
return "video_analysis"
elif any(phrase in question for phrase in [
"analyze", "visualize", "plot", "graph", "inspect data", "explore dataset"
]):
return "data_analysis"
elif any(phrase in question for phrase in [
"sparql", "wikidata", "query wikidata", "run sparql", "wikidata query"
]):
return "wikidata_query"
return "default"
def select_tool_and_run(question: str, tools: dict):
# Step 1: Classify intent
intent = task_classifier(question) # assuming task_classifier maps the question to intent
# Map intent to tool names
intent_tool_map = {
"math": "calculator", # maps to tools["math"] โ calculator
"wiki_search": "wiki_search", # โ wiki_search
"web_search": "web_search", # โ web_search
"arxiv_search": "arxiv_search", # โ arxiv_search (spelling fixed)
"get_youtube_transcript": "get_youtube_transcript", # โ get_youtube_transcript
"extract_video_id": "extract_video_id", # adjust based on your tools
"analyze_attachment": "analyze_attachment", # assuming analyze_attachment handles this
"wikidata_query": "wikidata_query", # โ wikidata_query
"default": "default" # โ default_tool
}
# Get the corresponding tool name
tool_name = intent_tool_map.get(intent, "default") # Default to "default" if no match
# Retrieve the tool from the tools dictionary
tool_func = tools.get(tool_name)
if not tool_func:
return f"Tool not found for intent '{intent}'"
# Step 2: Run the tool
try:
# If the tool needs JSON or structured data
try:
parsed_input = json.loads(question)
except json.JSONDecodeError:
parsed_input = question # fallback to raw input if not JSON
# Run the selected tool
print(f"Running tool: {tool_name} with input: {parsed_input}") # log the tool name and input
return tool_func(parsed_input)
except Exception as e:
return f"Error while running tool '{tool_name}': {str(e)}"
# Function to extract math operation from the question
def extract_math_from_question(question: str):
question = question.lower()
# Map natural language to symbols
ops = {
"add": "+", "plus": "+",
"subtract": "-", "minus": "-",
"multiply": "*", "times": "*",
"divide": "/", "divided by": "/",
"modulus": "%", "mod": "%"
}
for word, symbol in ops.items():
question = re.sub(rf"\b{word}\b", symbol, question)
# Extract math expression like "12 + 5"
match = re.search(r'(\d+)\s*([\+\-\*/%])\s*(\d+)', question)
if match:
num1 = int(match.group(1))
operator = match.group(2)
num2 = int(match.group(3))
return {
"a": num1,
"b": num2,
"operation": {
"+": "add",
"-": "subtract",
"*": "multiply",
"/": "divide",
"%": "modulus"
}[operator]
}
return None
# Example tool set (adjust these to match your actual tool names)
intent_tool_map = {
"math": "math", # maps to tools["math"] โ calculator
"wiki_search": "wiki_search", # โ wiki_search
"web_search": "web_search", # โ web_search
"arxiv_search": "arxiv_search", # โ arxiv_search (spelling fixed)
"get_youtube_transcript": "get_youtube_transcript", # โ get_youtube_transcript
"extract_video_id": "extract_video_id", # adjust based on your tools
"analyze_attachment": "analyze_attachment", # assuming analyze_attachment handles this
"wikidata_query": "wikidata_query", # โ wikidata_query
"default": "default" # โ default_tool
}
# The task order can also include the tools for each task
priority_order = [
{"task": "math", "tool": "math"},
{"task": "wiki_search", "tool": "wiki_search"},
{"task": "web_search", "tool": "web_search"},
{"task": "arxiv_search", "tool": "arxiv_search"},
{"task": "wikidata_query", "tool": "wikidata_query"},
{"task": "retriever", "tool": "retriever"},
{"task": "get_youtube_transcript", "tool": "get_youtube_transcript"},
{"task": "extract_video_id", "tool": "extract_video_id"},
{"task": "analyze_attachment", "tool": "analyze_attachment"},
{"task": "default", "tool": "default"} # Fallback
]
def decide_task(state: dict) -> str:
"""Decides which task to perform based on the current state."""
# Get the list of tasks from the planner
tasks = planner(state["question"])
print(f"Available tasks: {tasks}") # Debugging: show all possible tasks
# Check if the tasks list is empty or invalid
if not tasks:
print("โ No valid tasks were returned from the planner.")
return "default" # Return a default task if no tasks were generated
# If there are multiple tasks, we can prioritize based on certain conditions
task = tasks[0] # Default to the first task in the list
if len(tasks) > 1:
print(f"โ ๏ธ Multiple tasks found. Deciding based on priority.")
# Example logic to prioritize tasks, adjust based on your use case
task = prioritize_tasks(tasks)
print(f"Decided on task: {task}") # Debugging: show the final task
return task
def prioritize_tasks(tasks: list) -> str:
"""Prioritize tasks based on certain conditions or criteria, including tools."""
# Sort tasks based on priority_order mapping
for priority in priority_order:
# Check if any task matches the priority task type
for task in tasks:
if priority["task"] in task:
print(f"โ
Prioritizing task: {task} with tool: {priority['tool']}") # Debugging: show the chosen task and tool
# Assign the correct tool based on the task
tool = tools.get(priority["tool"], tools["default"]) # Default to 'default_tool' if not found
return task, tool
# If no priority task is found, return the first task with its default tool
return tasks[0], tools["default"]
def process_question(question: str):
"""Process the question and route it to the appropriate tool."""
# Get the tasks from the planner
tasks = planner(question)
print(f"Tasks to perform: {tasks}")
task_type, tool = decide_task({"question": question})
print(f"Next task: {task_type} with tool: {tool}")
if node_skipper({"question": question}):
print(f"Skipping task: {task_type}")
return "Task skipped."
try:
# Execute the corresponding tool for the task type
if task_type == "wiki_search":
response = tool.run(question) # Assuming tool is wiki_tool
elif task_type == "math":
response = tool.run(question) # Assuming tool is calc_tool
elif task_type == "retriever":
response = tool.run(question) # Assuming tool is retriever_tool
else:
response = tool.run(question) # Default tool
return generate_final_answer({"question": question}, {task_type: response})
except Exception as e:
print(f"โ Error: {e}")
return f"Sorry, I encountered an error: {str(e)}"
def call_llm(state):
messages = state["messages"]
response = llm.invoke(messages)
return {"messages": messages + [response]}
from langchain.schema import AIMessage
from typing import TypedDict, List, Optional
from langchain_core.messages import BaseMessage
class AgentState(TypedDict):
messages: List[BaseMessage] # Chat history
input: str # Original input
intent: str # Derived or predicted intent
result: Optional[str] # Optional result
def tool_dispatcher(state: AgentState) -> AgentState:
last_msg = state["messages"][-1]
# Make sure it's an AI message with tool_calls
if isinstance(last_msg, AIMessage) and last_msg.tool_calls:
tool_call = last_msg.tool_calls[0]
tool_name = tool_call["name"]
tool_input = tool_call["args"] # Adjust based on your actual schema
tool_func = tool_map.get(tool_name, default_tool)
# If args is a dict and your tool expects unpacked values:
if isinstance(tool_input, dict):
result = tool_func.invoke(tool_input) if hasattr(tool_func, "invoke") else tool_func(**tool_input)
else:
result = tool_func.invoke(tool_input) if hasattr(tool_func, "invoke") else tool_func(tool_input)
# You can choose to append this to messages, or just save result
return {
**state,
"result": result,
# Optionally add: "messages": state["messages"] + [ToolMessage(...)]
}
# No tool call detected, return state unchanged
return state
# Decide what to do next: if tool call โ call_tool, else โ end
def should_call_tool(state):
last_msg = state["messages"][-1]
if isinstance(last_msg, AIMessage) and last_msg.tool_calls:
return "call_tool"
return "end"
from typing import TypedDict, List, Optional, Union
from langchain.schema import BaseMessage
class AgentState(TypedDict):
messages: List[BaseMessage] # Chat history
input: str # Original input
intent: str # Derived or predicted intent
result: Optional[str] # Final or intermediate result
# To store previously asked questions and timestamps (simulating state persistence)
recent_questions = {}
def node_skipper(state: dict) -> bool:
"""
Determines whether to skip the task based on the state.
This could include:
1. Repeated or similar questions
2. Irrelevant or empty questions
3. Tasks that have already been processed recently
"""
question = state.get("question", "").strip()
if not question:
print("โ Skipping: Empty or invalid question.")
return True # Skip if no valid question
# 1. Skip if the question has already been asked recently (within a given time window)
# Here, we're using a simple example with a 5-minute window (300 seconds).
if question in recent_questions:
last_asked_time = recent_questions[question]
time_since_last_ask = time.time() - last_asked_time
if time_since_last_ask < 300: # 5-minute threshold
print(f"โ Skipping: The question has been asked recently. Time since last ask: {time_since_last_ask:.2f} seconds.")
return True # Skip if the question was asked within the last 5 minutes
# 2. Skip if the question is irrelevant or not meaningful enough
irrelevant_keywords = ["blah", "nothing", "invalid", "nonsense"]
if any(keyword in question.lower() for keyword in irrelevant_keywords):
print("โ Skipping: Irrelevant or nonsense question.")
return True # Skip if the question contains irrelevant keywords
# 3. Skip if the task has already been completed for this question (based on a unique task identifier)
if "last_response" in state and state["last_response"]:
print("โ Skipping: Task has already been processed recently.")
return True # Skip if a response has already been given
# 4. Skip based on a condition related to the task itself
# Example: Skip math-related tasks if the result is already known or trivial
if "math" in state.get("question", "").lower():
# If math is trivial (like "What is 2+2?")
trivial_math = ["2 + 2", "1 + 1", "3 + 3"]
if any(trivial_question in question for trivial_question in trivial_math):
print(f"โ Skipping trivial math question: {question}")
return True # Skip if the math question is trivial
# 5. Skip based on external factors (e.g., current time, system load, etc.)
# Example: Avoid processing tasks at night if that's part of the business logic
current_hour = time.localtime().tm_hour
if current_hour >= 22 or current_hour < 6:
print("โ Skipping: It's night time, not processing tasks.")
return True # Skip tasks during night time (e.g., between 10 PM and 6 AM)
# If none of the conditions matched, don't skip the task
return False
# Update recent questions (for simulating repeated question check)
def update_recent_questions(question: str):
"""Update the recent questions dictionary with the current timestamp."""
recent_questions[question] = time.time()
def generate_final_answer(state: dict, task_results: dict) -> str:
"""Generate a final answer based on the results of the task."""
if "wiki_search" in task_results:
return f"๐ Wiki Summary:\n{task_results['wiki_search']}"
elif "math" in task_results:
return f"๐งฎ Math Result: {task_results['math']}"
elif "retriever" in task_results:
return f"๐ Retrieved Info: {task_results['retriever']}"
else:
return "๐ค Unable to generate a specific answer."
def answer_question(question: str) -> str:
"""Process a single question and return the answer."""
print(f"Processing question: {question[:50]}...") # Debugging: show first 50 chars
# Wrap the question in a HumanMessage from langchain_core (assuming langchain is used)
messages = [HumanMessage(content=question)]
response = graph.invoke({"messages": messages}) # Assuming `graph` is defined elsewhere
# Extract the answer from the response
answer = response['messages'][-1].content
return answer[14:] # Assuming 'answer[14:]' is correct based on your example
def process_all_tasks(tasks: list):
"""Process a list of tasks."""
results = {}
for task in tasks:
question = task.get("question", "").strip()
if not question:
print(f"Skipping task with missing or empty 'question': {task}")
continue
print(f"\n๐ข Processing Task: {task['task_id']} - Question: {question}")
# Call the existing process_question logic
response = process_question(question)
print(f"โ
Response: {response}")
results[task['task_id']] = response
return results
## Langgraph
# Build graph function
vector_store = vector_store.save_local("faiss_index")
provider = "huggingface"
model_config = {
"repo_id": "HuggingFaceH4/zephyr-7b-beta",
"task": "text-generation",
"temperature": 0.7,
"max_new_tokens": 512,
"huggingfacehub_api_token": os.getenv("HF_TOKEN")
}
# Get LLM
def get_llm(provider: str, config: dict):
if provider == "huggingface":
from langchain_huggingface import HuggingFaceEndpoint
return HuggingFaceEndpoint(
repo_id=config["repo_id"],
task=config["task"],
huggingfacehub_api_token=config["huggingfacehub_api_token"],
temperature=config["temperature"],
max_new_tokens=config["max_new_tokens"]
)
else:
raise ValueError(f"Unsupported provider: {provider}")
def assistant(state: dict):
return {
"messages": [llm_with_tools.invoke(state["messages"])]
}
def tools_condition(state: dict) -> str:
if "use tool" in state["messages"][-1].content.lower():
return "tools"
else:
return "END"
from langgraph.graph import StateGraph
from langchain_core.messages import SystemMessage
from langchain_core.runnables import RunnableLambda
def build_graph(vector_store, provider: str, model_config: dict) -> StateGraph:
# Get LLM
llm = get_llm(provider, model_config)
# Define available tools
tools = [
wiki_search, calculator, web_search, arxiv_search,
get_youtube_transcript, extract_video_id, analyze_attachment, wikidata_query
]
# Tool mapping (global if needed elsewhere)
global tool_map
tool_map = {t.name: t for t in tools}
# Bind tools only if LLM supports it
if hasattr(llm, "bind_tools"):
llm_with_tools = llm.bind_tools(tools)
else:
llm_with_tools = llm # fallback for non-tool-aware models
sys_msg = SystemMessage(content="You are a helpful assistant.")
# Define nodes as runnables
retriever = RunnableLambda(lambda state: {
**state,
"retrieved_docs": vector_store.similarity_search(state["input"])
})
assistant = RunnableLambda(lambda state: {
**state,
"messages": [sys_msg] + state["messages"]
})
call_llm = llm_with_tools # already configured
# Start building the graph
builder = StateGraph(AgentState)
builder.add_node("retriever", retriever)
builder.add_node("assistant", assistant)
builder.add_node("call_llm", call_llm)
builder.add_node("call_tool", tool_dispatcher)
builder.add_node("end", lambda state: state) # Add explicit end node
# Define graph flow
builder.set_entry_point("retriever")
builder.add_edge("retriever", "assistant")
builder.add_edge("assistant", "call_llm")
builder.add_conditional_edges("call_llm", should_call_tool, {
"call_tool": "call_tool",
"end": "end" # โ
fixed: must point to actual "end" node
})
builder.add_edge("call_tool", "call_llm") # loop back after tool call
return builder.compile()
|