diff --git a/examples/openai/custom_graph_openai.py b/examples/openai/custom_graph_openai.py index 5744669b..14dd99bd 100644 --- a/examples/openai/custom_graph_openai.py +++ b/examples/openai/custom_graph_openai.py @@ -4,6 +4,8 @@ import os from dotenv import load_dotenv + +from langchain_openai import OpenAIEmbeddings from scrapegraphai.models import OpenAI from scrapegraphai.graphs import BaseGraph from scrapegraphai.nodes import FetchNode, ParseNode, RAGNode, GenerateAnswerNode, RobotsNode @@ -20,7 +22,7 @@ "api_key": openai_key, "model": "gpt-3.5-turbo", "temperature": 0, - "streaming": True + "streaming": False }, } @@ -29,33 +31,50 @@ # ************************************************ llm_model = OpenAI(graph_config["llm"]) +embedder = OpenAIEmbeddings(api_key=llm_model.openai_api_key) # define the nodes for the graph robot_node = RobotsNode( input="url", output=["is_scrapable"], - node_config={"llm_model": llm_model} + node_config={ + "llm_model": llm_model, + "verbose": True, + } ) fetch_node = FetchNode( input="url | local_dir", output=["doc"], - node_config={"headless": True, "verbose": True} + node_config={ + "verbose": True, + "headless": True, + } ) parse_node = ParseNode( input="doc", output=["parsed_doc"], - node_config={"chunk_size": 4096} + node_config={ + "chunk_size": 4096, + "verbose": True, + } ) rag_node = RAGNode( input="user_prompt & (parsed_doc | doc)", output=["relevant_chunks"], - node_config={"llm_model": llm_model}, + node_config={ + "llm_model": llm_model, + "embedder_model": embedder, + "verbose": True, + } ) generate_answer_node = GenerateAnswerNode( input="user_prompt & (relevant_chunks | parsed_doc | doc)", output=["answer"], - node_config={"llm_model": llm_model}, + node_config={ + "llm_model": llm_model, + "verbose": True, + } ) # ************************************************ diff --git a/examples/openai/search_graph_multi.py b/examples/openai/search_graph_multi.py new file mode 100644 index 00000000..962397c7 --- /dev/null +++ b/examples/openai/search_graph_multi.py @@ -0,0 +1,98 @@ +""" +Example of custom graph using existing nodes +""" + +import os +from dotenv import load_dotenv +from langchain_openai import OpenAIEmbeddings +from scrapegraphai.models import OpenAI +from scrapegraphai.graphs import BaseGraph, SmartScraperGraph +from scrapegraphai.nodes import SearchInternetNode, GraphIteratorNode, MergeAnswersNode +load_dotenv() + +# ************************************************ +# Define the configuration for the graph +# ************************************************ + +openai_key = os.getenv("OPENAI_APIKEY") + +graph_config = { + "llm": { + "api_key": openai_key, + "model": "gpt-3.5-turbo", + }, +} + +# ************************************************ +# Create a SmartScraperGraph instance +# ************************************************ + +smart_scraper_graph = SmartScraperGraph( + prompt="", + source="", + config=graph_config +) + +# ************************************************ +# Define the graph nodes +# ************************************************ + +llm_model = OpenAI(graph_config["llm"]) +embedder = OpenAIEmbeddings(api_key=llm_model.openai_api_key) + +search_internet_node = SearchInternetNode( + input="user_prompt", + output=["urls"], + node_config={ + "llm_model": llm_model, + "max_results": 5, # num of search results to fetch + "verbose": True, + } +) + +graph_iterator_node = GraphIteratorNode( + input="user_prompt & urls", + output=["results"], + node_config={ + "graph_instance": smart_scraper_graph, + "verbose": True, + } +) + +merge_answers_node = MergeAnswersNode( + input="user_prompt & results", + output=["answer"], + node_config={ + "llm_model": llm_model, + "verbose": True, + } +) + +# ************************************************ +# Create the graph by defining the connections +# ************************************************ + +graph = BaseGraph( + nodes=[ + search_internet_node, + graph_iterator_node, + merge_answers_node + ], + edges=[ + (search_internet_node, graph_iterator_node), + (graph_iterator_node, merge_answers_node) + ], + entry_point=search_internet_node +) + +# ************************************************ +# Execute the graph +# ************************************************ + +result, execution_info = graph.execute({ + "user_prompt": "List me all the typical Chioggia dishes." +}) + +# get the answer from the result +result = result.get("answer", "No answer found.") +print(result) diff --git a/examples/openai/search_graph_openai.py b/examples/openai/search_graph_openai.py index 0e0ca28d..486d9a62 100644 --- a/examples/openai/search_graph_openai.py +++ b/examples/openai/search_graph_openai.py @@ -19,6 +19,8 @@ "api_key": openai_key, "model": "gpt-3.5-turbo", }, + "max_results": 5, + "verbose": True, } # ************************************************ @@ -26,7 +28,7 @@ # ************************************************ search_graph = SearchGraph( - prompt="List me top 5 eyeliner products for a gift.", + prompt="List me the best escursions near Trento", config=graph_config ) diff --git a/examples/openai/smart_scraper_openai.py b/examples/openai/smart_scraper_openai.py index 32a1942b..610e6697 100644 --- a/examples/openai/smart_scraper_openai.py +++ b/examples/openai/smart_scraper_openai.py @@ -21,7 +21,7 @@ "api_key": openai_key, "model": "gpt-3.5-turbo", }, - "verbose": True, + "verbose": False, } # ************************************************ diff --git a/scrapegraphai/graphs/__init__.py b/scrapegraphai/graphs/__init__.py index 9c736b66..64b8241c 100644 --- a/scrapegraphai/graphs/__init__.py +++ b/scrapegraphai/graphs/__init__.py @@ -2,6 +2,7 @@ __init__.py file for graphs folder """ +from .abstract_graph import AbstractGraph from .base_graph import BaseGraph from .smart_scraper_graph import SmartScraperGraph from .speech_graph import SpeechGraph diff --git a/scrapegraphai/graphs/abstract_graph.py b/scrapegraphai/graphs/abstract_graph.py index 650ed988..089b0f95 100644 --- a/scrapegraphai/graphs/abstract_graph.py +++ b/scrapegraphai/graphs/abstract_graph.py @@ -56,7 +56,7 @@ def __init__(self, prompt: str, config: dict, source: Optional[str] = None): self.execution_info = None # Set common configuration parameters - self.verbose = True if config is None else config.get("verbose", False) + self.verbose = False if config is None else config.get("verbose", False) self.headless = True if config is None else config.get( "headless", True) common_params = {"headless": self.headless, diff --git a/scrapegraphai/graphs/search_graph.py b/scrapegraphai/graphs/search_graph.py index 9c463e1a..75d0d304 100644 --- a/scrapegraphai/graphs/search_graph.py +++ b/scrapegraphai/graphs/search_graph.py @@ -5,12 +5,11 @@ from .base_graph import BaseGraph from ..nodes import ( SearchInternetNode, - FetchNode, - ParseNode, - RAGNode, - GenerateAnswerNode + GraphIteratorNode, + MergeAnswersNode ) from .abstract_graph import AbstractGraph +from .smart_scraper_graph import SmartScraperGraph class SearchGraph(AbstractGraph): @@ -38,6 +37,11 @@ class SearchGraph(AbstractGraph): >>> result = search_graph.run() """ + def __init__(self, prompt: str, config: dict): + + self.max_results = config.get("max_results", 3) + super().__init__(prompt, config) + def _create_graph(self) -> BaseGraph: """ Creates the graph of nodes representing the workflow for web scraping and searching. @@ -46,53 +50,53 @@ def _create_graph(self) -> BaseGraph: BaseGraph: A graph instance representing the web scraping and searching workflow. """ + # ************************************************ + # Create a SmartScraperGraph instance + # ************************************************ + + smart_scraper_instance = SmartScraperGraph( + prompt="", + source="", + config=self.config + ) + + # ************************************************ + # Define the graph nodes + # ************************************************ + search_internet_node = SearchInternetNode( input="user_prompt", - output=["url"], - node_config={ - "llm_model": self.llm_model - } - ) - fetch_node = FetchNode( - input="url | local_dir", - output=["doc"] - ) - parse_node = ParseNode( - input="doc", - output=["parsed_doc"], + output=["urls"], node_config={ - "chunk_size": self.model_token + "llm_model": self.llm_model, + "max_results": self.max_results } ) - rag_node = RAGNode( - input="user_prompt & (parsed_doc | doc)", - output=["relevant_chunks"], + graph_iterator_node = GraphIteratorNode( + input="user_prompt & urls", + output=["results"], node_config={ - "llm_model": self.llm_model, - "embedder_model": self.embedder_model + "graph_instance": smart_scraper_instance, } ) - generate_answer_node = GenerateAnswerNode( - input="user_prompt & (relevant_chunks | parsed_doc | doc)", + + merge_answers_node = MergeAnswersNode( + input="user_prompt & results", output=["answer"], node_config={ - "llm_model": self.llm_model + "llm_model": self.llm_model, } ) return BaseGraph( nodes=[ search_internet_node, - fetch_node, - parse_node, - rag_node, - generate_answer_node, + graph_iterator_node, + merge_answers_node ], edges=[ - (search_internet_node, fetch_node), - (fetch_node, parse_node), - (parse_node, rag_node), - (rag_node, generate_answer_node) + (search_internet_node, graph_iterator_node), + (graph_iterator_node, merge_answers_node) ], entry_point=search_internet_node ) diff --git a/scrapegraphai/nodes/__init__.py b/scrapegraphai/nodes/__init__.py index 4804017e..87bc086b 100644 --- a/scrapegraphai/nodes/__init__.py +++ b/scrapegraphai/nodes/__init__.py @@ -17,3 +17,5 @@ from .robots_node import RobotsNode from .generate_answer_csv_node import GenerateAnswerCSVNode from .generate_answer_pdf_node import GenerateAnswerPDFNode +from .graph_iterator_node import GraphIteratorNode +from .merge_answers_node import MergeAnswersNode \ No newline at end of file diff --git a/scrapegraphai/nodes/generate_answer_csv_node.py b/scrapegraphai/nodes/generate_answer_csv_node.py index 6d2b84fc..b068f405 100644 --- a/scrapegraphai/nodes/generate_answer_csv_node.py +++ b/scrapegraphai/nodes/generate_answer_csv_node.py @@ -2,7 +2,7 @@ Module for generating the answer node """ # Imports from standard library -from typing import List +from typing import List, Optional from tqdm import tqdm # Imports from Langchain @@ -39,7 +39,7 @@ class GenerateAnswerCSVNode(BaseNode): updating the state with the generated answer under the 'answer' key. """ - def __init__(self, input: str, output: List[str], node_config: dict, + def __init__(self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "GenerateAnswer"): """ Initializes the GenerateAnswerNodeCsv with a language model client and a node name. diff --git a/scrapegraphai/nodes/generate_answer_node.py b/scrapegraphai/nodes/generate_answer_node.py index df3078ef..49a2d87b 100644 --- a/scrapegraphai/nodes/generate_answer_node.py +++ b/scrapegraphai/nodes/generate_answer_node.py @@ -3,7 +3,7 @@ """ # Imports from standard library -from typing import List +from typing import List, Optional from tqdm import tqdm # Imports from Langchain @@ -33,7 +33,7 @@ class GenerateAnswerNode(BaseNode): node_name (str): The unique identifier name for the node, defaulting to "GenerateAnswer". """ - def __init__(self, input: str, output: List[str], node_config: dict, + def __init__(self, input: str, output: List[str], node_config: Optional[dict]=None, node_name: str = "GenerateAnswer"): super().__init__(node_name, "node", input, output, 2, node_config) diff --git a/scrapegraphai/nodes/generate_answer_node_csv.py b/scrapegraphai/nodes/generate_answer_node_csv.py index 6d2b84fc..b068f405 100644 --- a/scrapegraphai/nodes/generate_answer_node_csv.py +++ b/scrapegraphai/nodes/generate_answer_node_csv.py @@ -2,7 +2,7 @@ Module for generating the answer node """ # Imports from standard library -from typing import List +from typing import List, Optional from tqdm import tqdm # Imports from Langchain @@ -39,7 +39,7 @@ class GenerateAnswerCSVNode(BaseNode): updating the state with the generated answer under the 'answer' key. """ - def __init__(self, input: str, output: List[str], node_config: dict, + def __init__(self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "GenerateAnswer"): """ Initializes the GenerateAnswerNodeCsv with a language model client and a node name. diff --git a/scrapegraphai/nodes/generate_answer_pdf_node.py b/scrapegraphai/nodes/generate_answer_pdf_node.py index b5bfae79..688ff47f 100644 --- a/scrapegraphai/nodes/generate_answer_pdf_node.py +++ b/scrapegraphai/nodes/generate_answer_pdf_node.py @@ -2,7 +2,7 @@ Module for generating the answer node """ # Imports from standard library -from typing import List +from typing import List, Optional from tqdm import tqdm # Imports from Langchain @@ -39,7 +39,7 @@ class GenerateAnswerPDFNode(BaseNode): updating the state with the generated answer under the 'answer' key. """ - def __init__(self, input: str, output: List[str], node_config: dict, + def __init__(self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "GenerateAnswer"): """ Initializes the GenerateAnswerNodePDF with a language model client and a node name. diff --git a/scrapegraphai/nodes/generate_scraper_node.py b/scrapegraphai/nodes/generate_scraper_node.py index 2e1f959e..f0f6469d 100644 --- a/scrapegraphai/nodes/generate_scraper_node.py +++ b/scrapegraphai/nodes/generate_scraper_node.py @@ -3,7 +3,7 @@ """ # Imports from standard library -from typing import List +from typing import List, Optional from tqdm import tqdm # Imports from Langchain @@ -36,8 +36,8 @@ class GenerateScraperNode(BaseNode): """ - def __init__(self, input: str, output: List[str], node_config: dict, - library: str, website: str, node_name: str = "GenerateAnswer"): + def __init__(self, input: str, output: List[str], library: str, website: str, + node_config: Optional[dict]=None, node_name: str = "GenerateAnswer"): super().__init__(node_name, "node", input, output, 2, node_config) self.llm_model = node_config["llm_model"] diff --git a/scrapegraphai/nodes/get_probable_tags_node.py b/scrapegraphai/nodes/get_probable_tags_node.py index 11977c62..e970c285 100644 --- a/scrapegraphai/nodes/get_probable_tags_node.py +++ b/scrapegraphai/nodes/get_probable_tags_node.py @@ -2,7 +2,7 @@ GetProbableTagsNode Module """ -from typing import List +from typing import List, Optional from langchain.output_parsers import CommaSeparatedListOutputParser from langchain.prompts import PromptTemplate from .base_node import BaseNode diff --git a/scrapegraphai/nodes/graph_iterator_node.py b/scrapegraphai/nodes/graph_iterator_node.py new file mode 100644 index 00000000..663adc62 --- /dev/null +++ b/scrapegraphai/nodes/graph_iterator_node.py @@ -0,0 +1,79 @@ +""" +GraphIterator Module +""" + +from typing import List, Optional +import copy +from tqdm import tqdm +from .base_node import BaseNode + + +class GraphIteratorNode(BaseNode): + """ + A node responsible for instantiating and running multiple graph instances in parallel. + It creates as many graph instances as the number of elements in the input list. + + Attributes: + verbose (bool): A flag indicating whether to show print statements during execution. + + Args: + input (str): Boolean expression defining the input keys needed from the state. + output (List[str]): List of output keys to be updated in the state. + node_config (dict): Additional configuration for the node. + node_name (str): The unique identifier name for the node, defaulting to "Parse". + """ + + def __init__(self, input: str, output: List[str], node_config: Optional[dict]=None, node_name: str = "GraphIterator"): + super().__init__(node_name, "node", input, output, 2, node_config) + + self.verbose = False if node_config is None else node_config.get("verbose", False) + + def execute(self, state: dict) -> dict: + """ + Executes the node's logic to instantiate and run multiple graph instances in parallel. + + Args: + state (dict): The current state of the graph. The input keys will be used to fetch + the correct data from the state. + + Returns: + dict: The updated state with the output key containing the results of the graph instances. + + Raises: + KeyError: If the input keys are not found in the state, indicating that the + necessary information for running the graph instances is missing. + """ + + if self.verbose: + print(f"--- Executing {self.node_name} Node ---") + + # Interpret input keys based on the provided input expression + input_keys = self.get_input_keys(state) + + # Fetching data from the state based on the input keys + input_data = [state[key] for key in input_keys] + + user_prompt = input_data[0] + urls = input_data[1] + + graph_instance = self.node_config.get("graph_instance", None) + if graph_instance is None: + raise ValueError("Graph instance is required for graph iteration.") + + # set the prompt and source for each url + graph_instance.prompt = user_prompt + graphs_instances = [] + for url in urls: + # make a copy of the graph instance + copy_graph_instance = copy.copy(graph_instance) + copy_graph_instance.source = url + graphs_instances.append(copy_graph_instance) + + # run the graph for each url and use tqdm for progress bar + graphs_answers = [] + for graph in tqdm(graphs_instances, desc="Processing Graph Instances", disable=not self.verbose): + result = graph.run() + graphs_answers.append(result) + + state.update({self.output[0]: graphs_answers}) + return state diff --git a/scrapegraphai/nodes/image_to_text_node.py b/scrapegraphai/nodes/image_to_text_node.py index d9d4f1cc..0e4221c7 100644 --- a/scrapegraphai/nodes/image_to_text_node.py +++ b/scrapegraphai/nodes/image_to_text_node.py @@ -2,7 +2,7 @@ ImageToTextNode Module """ -from typing import List +from typing import List, Optional from .base_node import BaseNode @@ -21,7 +21,7 @@ class ImageToTextNode(BaseNode): node_name (str): The unique identifier name for the node, defaulting to "ImageToText". """ - def __init__(self, input: str, output: List[str], node_config: dict, + def __init__(self, input: str, output: List[str], node_config: Optional[dict]=None, node_name: str = "ImageToText"): super().__init__(node_name, "node", input, output, 1, node_config) diff --git a/scrapegraphai/nodes/merge_answers_node.py b/scrapegraphai/nodes/merge_answers_node.py new file mode 100644 index 00000000..2d6bf560 --- /dev/null +++ b/scrapegraphai/nodes/merge_answers_node.py @@ -0,0 +1,100 @@ +""" +MergeAnswersNode Module +""" + +# Imports from standard library +from typing import List, Optional +from tqdm import tqdm + +# Imports from Langchain +from langchain.prompts import PromptTemplate +from langchain_core.output_parsers import JsonOutputParser + +# Imports from the library +from .base_node import BaseNode + + +class MergeAnswersNode(BaseNode): + """ + A node responsible for merging the answers from multiple graph instances into a single answer. + + Attributes: + llm_model: An instance of a language model client, configured for generating answers. + verbose (bool): A flag indicating whether to show print statements during execution. + + Args: + input (str): Boolean expression defining the input keys needed from the state. + output (List[str]): List of output keys to be updated in the state. + node_config (dict): Additional configuration for the node. + node_name (str): The unique identifier name for the node, defaulting to "GenerateAnswer". + """ + + def __init__(self, input: str, output: List[str], node_config: Optional[dict] = None, + node_name: str = "MergeAnswers"): + super().__init__(node_name, "node", input, output, 2, node_config) + + self.llm_model = node_config["llm_model"] + self.verbose = True if node_config is None else node_config.get( + "verbose", False) + + def execute(self, state: dict) -> dict: + """ + Executes the node's logic to merge the answers from multiple graph instances into a single answer. + + Args: + state (dict): The current state of the graph. The input keys will be used + to fetch the correct data from the state. + + Returns: + dict: The updated state with the output key containing the generated answer. + + Raises: + KeyError: If the input keys are not found in the state, indicating + that the necessary information for generating an answer is missing. + """ + + if self.verbose: + print(f"--- Executing {self.node_name} Node ---") + + # Interpret input keys based on the provided input expression + input_keys = self.get_input_keys(state) + + # Fetching data from the state based on the input keys + input_data = [state[key] for key in input_keys] + + user_prompt = input_data[0] + answers = input_data[1] + + # merge the answers in one string + answers_str = "" + for i, answer in enumerate(answers): + answers_str += f"CONTENT WEBSITE {i+1}: {answer}\n" + + output_parser = JsonOutputParser() + format_instructions = output_parser.get_format_instructions() + + template_merge = """ + You are a website scraper and you have just scraped some content from multiple websites.\n + You are now asked to provide an answer to a USER PROMPT based on the content you have scraped.\n + You need to merge the content from the different websites into a single answer without repetitions (if there are any). \n + The scraped contents are in a JSON format and you need to merge them based on the context and providing a correct JSON structure.\n + OUTPUT INSTRUCTIONS: {format_instructions}\n + USER PROMPT: {user_prompt}\n + WEBSITE CONTENT: {website_content} + """ + + prompt_template = PromptTemplate( + template=template_merge, + input_variables=["user_prompt"], + partial_variables={ + "format_instructions": format_instructions, + "website_content": answers_str, + }, + ) + + merge_chain = prompt_template | self.llm_model | output_parser + answer = merge_chain.invoke({"user_prompt": user_prompt}) + + # Update the state with the generated answer + state.update({self.output[0]: answer}) + return state diff --git a/scrapegraphai/nodes/parse_node.py b/scrapegraphai/nodes/parse_node.py index b552ece4..34602340 100644 --- a/scrapegraphai/nodes/parse_node.py +++ b/scrapegraphai/nodes/parse_node.py @@ -2,7 +2,7 @@ ParseNode Module """ -from typing import List +from typing import List, Optional from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_community.document_transformers import Html2TextTransformer from .base_node import BaseNode @@ -26,7 +26,7 @@ class ParseNode(BaseNode): node_name (str): The unique identifier name for the node, defaulting to "Parse". """ - def __init__(self, input: str, output: List[str], node_config: dict, node_name: str = "Parse"): + def __init__(self, input: str, output: List[str], node_config: Optional[dict]=None, node_name: str = "Parse"): super().__init__(node_name, "node", input, output, 1, node_config) self.verbose = True if node_config is None else node_config.get("verbose", False) diff --git a/scrapegraphai/nodes/rag_node.py b/scrapegraphai/nodes/rag_node.py index 8c692ec8..d9dbc83b 100644 --- a/scrapegraphai/nodes/rag_node.py +++ b/scrapegraphai/nodes/rag_node.py @@ -2,7 +2,7 @@ RAGNode Module """ -from typing import List +from typing import List, Optional from langchain.docstore.document import Document from langchain.retrievers import ContextualCompressionRetriever from langchain.retrievers.document_compressors import EmbeddingsFilter, DocumentCompressorPipeline @@ -31,7 +31,7 @@ class RAGNode(BaseNode): node_name (str): The unique identifier name for the node, defaulting to "Parse". """ - def __init__(self, input: str, output: List[str], node_config: dict, node_name: str = "RAG"): + def __init__(self, input: str, output: List[str], node_config: Optional[dict]=None, node_name: str = "RAG"): super().__init__(node_name, "node", input, output, 2, node_config) self.llm_model = node_config["llm_model"] diff --git a/scrapegraphai/nodes/robots_node.py b/scrapegraphai/nodes/robots_node.py index 8c341183..e56a95d1 100644 --- a/scrapegraphai/nodes/robots_node.py +++ b/scrapegraphai/nodes/robots_node.py @@ -2,9 +2,9 @@ RobotsNode Module """ -from typing import List +from typing import List, Optional from urllib.parse import urlparse -from langchain_community.document_loaders import AsyncHtmlLoader +from langchain_community.document_loaders import AsyncChromiumLoader from langchain.prompts import PromptTemplate from langchain.output_parsers import CommaSeparatedListOutputParser from .base_node import BaseNode @@ -34,7 +34,7 @@ class RobotsNode(BaseNode): node_name (str): The unique identifier name for the node, defaulting to "Robots". """ - def __init__(self, input: str, output: List[str], node_config: dict, force_scraping=True, + def __init__(self, input: str, output: List[str], node_config: Optional[dict]=None, force_scraping=True, node_name: str = "Robots"): super().__init__(node_name, "node", input, output, 1) @@ -93,11 +93,11 @@ def execute(self, state: dict) -> dict: else: parsed_url = urlparse(source) base_url = f"{parsed_url.scheme}://{parsed_url.netloc}" - loader = AsyncHtmlLoader(f"{base_url}/robots.txt") + loader = AsyncChromiumLoader(f"{base_url}/robots.txt") document = loader.load() - if "ollama" in self.llm_model.model: - self.llm_model.model = self.llm_model.model.split("/")[-1] - model = self.llm_model.model.split("/")[-1] + if "ollama" in self.llm_model.model_name: + self.llm_model.model_name = self.llm_model.model_name.split("/")[-1] + model = self.llm_model.model_name.split("/")[-1] else: model = self.llm_model.model_name diff --git a/scrapegraphai/nodes/search_internet_node.py b/scrapegraphai/nodes/search_internet_node.py index 01095ef8..f38e16e4 100644 --- a/scrapegraphai/nodes/search_internet_node.py +++ b/scrapegraphai/nodes/search_internet_node.py @@ -2,7 +2,7 @@ SearchInternetNode Module """ -from typing import List +from typing import List, Optional from langchain.output_parsers import CommaSeparatedListOutputParser from langchain.prompts import PromptTemplate from ..utils.research_web import search_on_web @@ -27,12 +27,13 @@ class SearchInternetNode(BaseNode): node_name (str): The unique identifier name for the node, defaulting to "SearchInternet". """ - def __init__(self, input: str, output: List[str], node_config: dict, + def __init__(self, input: str, output: List[str], node_config: Optional[dict]=None, node_name: str = "SearchInternet"): super().__init__(node_name, "node", input, output, 1, node_config) self.llm_model = node_config["llm_model"] self.verbose = True if node_config is None else node_config.get("verbose", False) + self.max_results = node_config.get("max_results", 3) def execute(self, state: dict) -> dict: """ @@ -85,8 +86,11 @@ def execute(self, state: dict) -> dict: if self.verbose: print(f"Search Query: {search_query}") - # TODO: handle multiple URLs - answer = search_on_web(query=search_query, max_results=1)[0] + answer = search_on_web(query=search_query, max_results=self.max_results) + + if len(answer) == 0: + # raise an exception if no answer is found + raise ValueError("Zero results found for the search query.") # Update the state with the generated answer state.update({self.output[0]: answer}) diff --git a/scrapegraphai/nodes/search_link_node.py b/scrapegraphai/nodes/search_link_node.py index 037b862e..5029d0d7 100644 --- a/scrapegraphai/nodes/search_link_node.py +++ b/scrapegraphai/nodes/search_link_node.py @@ -3,7 +3,7 @@ """ # Imports from standard library -from typing import List +from typing import List, Optional from tqdm import tqdm from bs4 import BeautifulSoup @@ -33,7 +33,7 @@ class SearchLinkNode(BaseNode): node_name (str): The unique identifier name for the node, defaulting to "GenerateAnswer". """ - def __init__(self, input: str, output: List[str], node_config: dict, + def __init__(self, input: str, output: List[str], node_config: Optional[dict]=None, node_name: str = "GenerateLinks"): super().__init__(node_name, "node", input, output, 1, node_config) diff --git a/scrapegraphai/nodes/text_to_speech_node.py b/scrapegraphai/nodes/text_to_speech_node.py index 53da713a..80ab998f 100644 --- a/scrapegraphai/nodes/text_to_speech_node.py +++ b/scrapegraphai/nodes/text_to_speech_node.py @@ -2,7 +2,7 @@ TextToSpeechNode Module """ -from typing import List +from typing import List, Optional from .base_node import BaseNode @@ -22,7 +22,7 @@ class TextToSpeechNode(BaseNode): """ def __init__(self, input: str, output: List[str], - node_config: dict, node_name: str = "TextToSpeech"): + node_config: Optional[dict]=None, node_name: str = "TextToSpeech"): super().__init__(node_name, "node", input, output, 1, node_config) self.tts_model = node_config["tts_model"]