Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
fixed custom_graph, graph_builder and trulens_evaluator
Perinimb5479729681a
diff --git a/examples/graph_examples/custom_graph_example.py b/examples/graph_examples/custom_graph_example.pyindex 4dfbb92b..63779521 100644--- a/examples/graph_examples/custom_graph_example.py+++ b/examples/graph_examples/custom_graph_example.py@@ -6,74 +6,64 @@ import osfrom dotenv import load_dotenvfrom scrapegraphai.models import OpenAIfrom scrapegraphai.graphs import BaseGraph-from scrapegraphai.nodes import FetchHTMLNode, ParseNode, RAGNode, GenerateAnswerNode+from scrapegraphai.nodes import FetchNode, ParseNode, RAGNode, GenerateAnswerNodeload_dotenv()--# Define the configuration for the language modelopenai_key = os.getenv("OPENAI_APIKEY")-llm_config = {- "api_key": openai_key,- "model_name": "gpt-3.5-turbo",- "temperature": 0,- "streaming": True++# Define the configuration for the graph+graph_config = {+ "llm": {+ "api_key": openai_key,+ "model": "gpt-3.5-turbo",+ "temperature": 0,+ "streaming": True+ },}-model = OpenAI(llm_config)-# fetch_html_node = FetchNode(-# input="url | local_dir",-# output=["doc"],-# node_name="fetch_html"-# )-# parse_document_node = ParseNode(-# input="doc",-# output=["parsed_doc"],-# node_name="parse_document"-# )-# split_chunks_node = SplitChunksNode(-# input="parsed_doc | doc",-# output=["doc_chunks"],-# node_name="split_chunks"-# )-# rag_node = RAGNode(-# input="user_prompt & (doc_chunks | parsed_doc | doc)",-# output=["relevant_doc_chunks"],-# model=model,-# node_name="rag"-# )-# generate_answer_node = GenerateAnswerNode(-# input="user_prompt & (relevant_doc_chunks | doc_chunks | parsed_doc | doc)",-# output=["answer"],-# model=model,-# node_name="generate_answer"-# )+llm_model = OpenAI(graph_config["llm"])# define the nodes for the graph-fetch_html_node = FetchHTMLNode("fetch_html")-parse_document_node = ParseNode(doc_type="html", chunks_size=4000, node_name="parse_document")-rag_node = RAGNode(model, "rag")-generate_answer_node = GenerateAnswerNode(model, "generate_answer")+fetch_node = FetchNode(+ input="url | local_dir",+ output=["doc"],+ )+parse_node = ParseNode(+ input="doc",+ output=["parsed_doc"],+ )+rag_node = RAGNode(+ input="user_prompt & (parsed_doc | doc)",+ output=["relevant_chunks"],+ model_config={"llm_model": llm_model},+ )+generate_answer_node = GenerateAnswerNode(+ input="user_prompt & (relevant_chunks | parsed_doc | doc)",+ output=["answer"],+ model_config={"llm_model": llm_model},+ )-# create the graph+# create the graph by defining the nodes and their connectionsgraph = BaseGraph(nodes={- fetch_html_node,- parse_document_node,+ fetch_node,+ parse_node,rag_node,- generate_answer_node+ generate_answer_node,},edges={- (fetch_html_node, parse_document_node),- (parse_document_node, rag_node),+ (fetch_node, parse_node),+ (parse_node, rag_node),(rag_node, generate_answer_node)},- entry_point=fetch_html_node+ entry_point=fetch_node)# execute the graph-inputs = {"user_input": "List me the projects with their description",- "url": "https://perinim.github.io/projects/"}-result = graph.execute(inputs)+result = graph.execute({+ "user_prompt": "List me the projects with their description",+ "url": "https://perinim.github.io/projects/"+ })# get the answer from the resultanswer = result.get("answer", "No answer found.")diff --git a/examples/graph_examples/graph_builder_example.py b/examples/graph_examples/graph_builder_example.pyindex ac586bd3..53956e09 100644--- a/examples/graph_examples/graph_builder_example.py+++ b/examples/graph_examples/graph_builder_example.py@@ -6,19 +6,22 @@ from dotenv import load_dotenvfrom scrapegraphai.builders import GraphBuilderload_dotenv()--# Define the configuration for the language modelopenai_key = os.getenv("OPENAI_APIKEY")-llm_config = {- "api_key": openai_key,- "model_name": "gpt-3.5-turbo",- "temperature": 0,- "streaming": True++# Define the configuration for the graph+graph_config = {+ "llm": {+ "api_key": openai_key,+ "model": "gpt-3.5-turbo",+ },}# Example usage of GraphBuilder-USER_PROMPT = "Extract the news and generate a text summary with a voiceover."-graph_builder = GraphBuilder(USER_PROMPT, llm_config)+graph_builder = GraphBuilder(+ user_prompt="Extract the news and generate a text summary with a voiceover.",+ config=graph_config+)+graph_json = graph_builder.build_graph()# Convert the resulting JSON to Graphviz formatdiff --git a/examples/graph_examples/graph_evaluation_example.py b/examples/graph_examples/graph_evaluation_example.pyindex b73e688b..f5970de7 100644--- a/examples/graph_examples/graph_evaluation_example.py+++ b/examples/graph_examples/graph_evaluation_example.py@@ -6,27 +6,38 @@ from dotenv import load_dotenvfrom scrapegraphai.evaluators import TrulensEvaluatorload_dotenv()--# Define the configuration for the language modelopenai_key = os.getenv("OPENAI_APIKEY")-llm_config = {- "api_key": openai_key,- "model_name": "gpt-3.5-turbo",+# Define the configuration for the graph+graph_config = {+ "llm": {+ "api_key": openai_key,+ "model": "gpt-3.5-turbo",+ },}list_of_inputs = [- ("List me all the titles and project descriptions",- "https://perinim.github.io/projects/", llm_config),- # ("Who is the author of the project?",- # "https://perinim.github.io/projects/", llm_config),- # ("What is the project about?", "https://perinim.github.io/projects/", llm_config),+ (+ "List me all the titles and project descriptions",+ "https://perinim.github.io/projects/",+ graph_config+ ),+ (+ "Who is the author of the project?",+ "https://perinim.github.io/projects/",+ graph_config+ ),+ (+ "What are the projects about?",+ "https://perinim.github.io/projects/",+ graph_config+ ),]# Create the TrulensEvaluator instance-trulens_evaluator = TrulensEvaluator(openai_key)+trulens_evaluator = TrulensEvaluator(graph_config["llm"]["api_key"])# Evaluate SmartScraperGraph on the list of inputs(results_df, answer) = trulens_evaluator.evaluate(- list_of_inputs, dashboard=False)+ list_of_inputs, dashboard=True)print(answer)diff --git a/scrapegraphai/builders/graph_builder.py b/scrapegraphai/builders/graph_builder.pyindex 1da4c928..2f26e447 100644--- a/scrapegraphai/builders/graph_builder.py+++ b/scrapegraphai/builders/graph_builder.py@@ -1,7 +1,7 @@"""Module for making the graph building"""-import graphviz+from langchain_core.prompts import ChatPromptTemplatefrom langchain.chains import create_extraction_chainfrom ..models import OpenAI@@ -39,17 +39,17 @@ class GraphBuilder:ValueError: If 'api_key' is not included in llm_config."""- def __init__(self, user_prompt: str, llm_config: dict):+ def __init__(self, user_prompt: str, config: dict):"""Initializes the GraphBuilder with a user prompt and language model configuration."""self.user_prompt = user_prompt- self.llm_config = llm_config- self.llm = self._create_llm()+ self.config = config+ self.llm = self._create_llm(config["llm"])self.nodes_description = self._generate_nodes_description()self.chain = self._create_extraction_chain()- def _create_llm(self):+ def _create_llm(self, llm_config: dict):"""Creates an instance of the OpenAI class with the provided language model configuration.@@ -60,12 +60,11 @@ class GraphBuilder:ValueError: If 'api_key' is not provided in llm_config."""llm_defaults = {- "model_name": "gpt-3.5-turbo","temperature": 0,"streaming": True}# Update defaults with any LLM parameters that were provided- llm_params = {**llm_defaults, **self.llm_config}+ llm_params = {**llm_defaults, **llm_config}if "api_key" not in llm_params:raise ValueError("LLM configuration must include an 'api_key'.")return OpenAI(llm_params)@@ -127,6 +126,11 @@ class GraphBuilder:Returns:graphviz.Digraph: A Graphviz object representing the graph configuration."""+ try:+ import graphviz+ except ImportError:+ raise ImportError("The 'graphviz' library is required for this functionality. "+ "Please install it from 'https://graphviz.org/download/'.")graph = graphviz.Digraph(comment='ScrapeGraphAI Generated Graph', format=format,node_attr={'color': 'lightblue2', 'style': 'filled'})diff --git a/scrapegraphai/evaluators/trulens_evaluator.py b/scrapegraphai/evaluators/trulens_evaluator.pyindex febe2980..6dc875a5 100644--- a/scrapegraphai/evaluators/trulens_evaluator.py+++ b/scrapegraphai/evaluators/trulens_evaluator.py@@ -52,10 +52,11 @@ class TrulensEvaluator:output = SmartScraperGraph(*params).run()self.tru_llm_standalone_recorder.app(params[0], output)self.graph_output.append(output)+if dashboard:self.tru.run_dashboard()- else:- return (self.tru.get_records_and_feedback(app_ids=[])[0], self.graph_output)++ return (self.tru.get_records_and_feedback(app_ids=[])[0], self.graph_output)def llm_standalone(self, prompt, response):"""