An LLM-powered knowledge curation system that researches a topic and generates a full-length report with citations.
Python agentic-ragdeep-researchemnlp2024knowledge-curationlarge-language-modelsnaaclnlpreport-generationretrieval-augmented-generation
refactor interfaces of dataclasses, encoder, retriever, logging wrapper, to support datatype sharing between storm and co-storm
Yucheng-Jiang4f4aab9b1b06
diff --git a/knowledge_storm/dataclass.py b/knowledge_storm/dataclass.pynew file mode 100644index 0000000..1ec1a8c--- /dev/null+++ b/knowledge_storm/dataclass.py@@ -0,0 +1,831 @@+import dspy+import numpy as np+import re+import threading+from typing import Set, Dict, List, Optional, Union, Tuple++from .encoder import get_text_embeddings+from .interface import Information+++class ConversationTurn:+ """+ A class to represent a turn in a conversation.++ Attributes:+ role (str): A short phrase of the role of the speaker for the current conversation turn.+ raw_utterance (str): The response generated by the LM model without polished style and tone.+ utterance_type (str): The type of utterance (e.g., statement, question).+ claim_to_make (Optional[str]): The point that this utterance tries to make. Should be empty if the utterance type is questioning.+ utterance (Optional[str]): The response generated by the model with polished style and tone. Defaults to raw_utterance if not provided.+ queries (List[str]): The queries used to gather information to have a grounded answer.+ raw_retrieved_info (List['Information']): A list of Information type that is retrieved.+ cited_info (Dict[int, 'Information']): A dictionary where the key is the citation index and the value is Information type.+ role_description (Optional[str]): A few sentences description of the role. Defaults to an empty string if not provided.+ """++ def __init__(+ self,+ role: str,+ raw_utterance: str,+ utterance_type: str,+ claim_to_make: Optional[str] = None,+ utterance: Optional[str] = None,+ queries: Optional[List[str]] = None,+ raw_retrieved_info: Optional[List[Information]] = None,+ cited_info: Optional[List[Information]] = None,+ ):+ self.utterance = utterance if utterance is not None else raw_utterance+ self.raw_utterance = raw_utterance+ self.role = role if ":" not in role else role.split(":")[0]+ self.role_description = "" if ":" not in role else role.split(":")[1]+ self.queries = queries if queries is not None else []+ self.raw_retrieved_info = (+ raw_retrieved_info if raw_retrieved_info is not None else []+ )+ self.cited_info = cited_info if cited_info is not None else {}+ self.utterance_type = utterance_type+ self.claim_to_make = claim_to_make if claim_to_make is not None else ""++ def get_all_citation_index(self):+ citation_pattern = re.compile(r"\[(\d+)\]")+ return list(map(int, citation_pattern.findall(self.utterance)))++ def to_dict(self):+ raw_retrieved_info = [info.to_dict() for info in self.raw_retrieved_info]+ return {+ "utterance": self.utterance,+ "raw_utterance": self.raw_utterance,+ "role": self.role,+ "role_description": self.role_description,+ "queries": self.queries,+ "utterance_type": self.utterance_type,+ "claim_to_make": self.claim_to_make,+ "raw_retrieved_info": raw_retrieved_info,+ "cited_info": None,+ }++ @classmethod+ def from_dict(cls, conv_turn_dict: Dict):+ raw_retrieved_info = [+ Information.from_dict(info) for info in conv_turn_dict["raw_retrieved_info"]+ ]++ return cls(+ utterance=conv_turn_dict["utterance"],+ raw_utterance=conv_turn_dict["raw_utterance"],+ role=f"{conv_turn_dict['role']}: {conv_turn_dict['role_description']}",+ queries=conv_turn_dict["queries"],+ raw_retrieved_info=raw_retrieved_info,+ cited_info=None,+ utterance_type=conv_turn_dict["utterance_type"],+ claim_to_make=conv_turn_dict["claim_to_make"],+ )+++class KnowledgeNode:+ """+ Class representing a node in the knowledge base.++ Attributes:+ name (str): The name of the node.+ content (list): A list of Information instances.+ children (list): A list of child KnowledgeNode instances.+ parent (KnowledgeNode): The parent node of the current node.+ """++ def __init__(+ self,+ name: str,+ content: Optional[str] = None,+ parent: Optional["KnowledgeNode"] = None,+ children: Optional[List["KnowledgeNode"]] = None,+ synthesize_output: Optional[str] = None,+ need_regenerate_synthesize_output: bool = True,+ ):+ """+ Initializes a KnowledgeNode instance.++ Args:+ name (str): The name of the node.+ content (list, optional): A list of information uuid. Defaults to None.+ parent (KnowledgeNode, optional): The parent node of the current node. Defaults to None.+ """+ self.name = name+ self.content: Set[int] = set(content) if content is not None else set()+ self.children = [] if children is None else children+ self.parent = parent+ self.synthesize_output = synthesize_output+ self.need_regenerate_synthesize_output = need_regenerate_synthesize_output++ def collect_all_content(self):+ """+ Collects all content from the current node and its descendants.++ Returns:+ Set[int]: A set containing all content from the current node and its descendants.+ """+ all_content = set(self.content)+ for child in self.children:+ all_content.update(child.collect_all_content())+ return all_content++ def has_child(self, child_node_name: str):+ """+ Check if the node has the child of given name.+ """+ return child_node_name in [child.name for child in self.children]++ def add_child(self, child_node_name: str, duplicate_handling: str = "skip"):+ """+ Adds a child node to the current node.+ duplicate_handling (str): How to handle duplicate nodes. Options are "skip", "none", and "raise error".+ """+ if self.has_child(child_node_name):+ if duplicate_handling == "skip":+ for child in self.children:+ if child.name == child_node_name:+ return child+ elif duplicate_handling == "raise error":+ raise Exception(+ f"Insert node error. Node {child_node_name} already exists under its parent node {self.name}."+ )+ child_node = KnowledgeNode(name=child_node_name, parent=self)+ self.children.append(child_node)+ return child_node++ def get_parent(self):+ """+ Returns the parent node of the current node.++ Returns:+ KnowledgeNode: The parent node of the current node.+ """+ return self.parent++ def get_children(self):+ """+ Returns the children of the current node.++ Returns:+ list: A list of child KnowledgeNode instances.+ """+ return self.children++ def get_children_names(self):+ """+ Returns a list of children names.+ """+ return [child.name for child in self.children]++ def __repr__(self):+ """+ Returns a string representation of the KnowledgeNode instance.++ Returns:+ str: String representation of the KnowledgeNode instance.+ """+ return f"KnowledgeNode(name={self.name}, content={self.content}, children={len(self.children)})"++ def get_path_from_root(self, root: Optional["KnowledgeNode"] = None):+ """+ Get a list of names from the root to this node.++ Returns:+ List[str]: A list of node names from the root to this node.+ """+ path = []+ current_node = self+ while current_node:+ path.append(current_node.name)+ if root is not None and current_node.name == root.name:+ break+ current_node = current_node.parent+ return path[::-1]++ def insert_information(self, information_index: int):+ if information_index not in self.content:+ self.need_regenerate_synthesize_output = True+ self.content.add(information_index)++ def get_all_descendents(self) -> List["KnowledgeNode"]:+ """+ Get a list of all descendant nodes.++ Returns:+ List[KnowledgeNode]: A list of all descendant nodes.+ """+ descendents = []++ def collect_descendents(node):+ for child in node.children:+ descendents.append(child)+ collect_descendents(child)++ collect_descendents(self)+ return descendents++ def get_all_predecessors(self) -> List["KnowledgeNode"]:+ """+ Get a list of all predecessor nodes (from current node to root).++ Returns:+ List[KnowledgeNode]: A list of all predecessor nodes.+ """+ predecessors = []+ current_node = self.parent+ while current_node is not None:+ predecessors.append(current_node)+ current_node = current_node.parent+ return predecessors++ def to_dict(self):+ """+ Converts the KnowledgeNode instance to a dictionary representation.++ Returns:+ dict: The dictionary representation of the KnowledgeNode.+ """+ return {+ "name": self.name,+ "content": list(self.content),+ "children": [child.to_dict() for child in self.children],+ "parent": self.parent.name if self.parent else None,+ "synthesize_output": self.synthesize_output,+ "need_regenerate_synthesize_output": self.need_regenerate_synthesize_output,+ }++ @classmethod+ def from_dict(cls, data):+ """+ Constructs a KnowledgeNode instance from a dictionary representation.++ Args:+ data (dict): The dictionary representation of the KnowledgeNode.++ Returns:+ KnowledgeNode: The constructed KnowledgeNode instance.+ """++ def helper(cls, data, parent_node=None):+ if parent_node is not None:+ assert data["parent"] is not None and data["parent"] == parent_node.name+ node = cls(+ name=data["name"],+ content=data["content"],+ parent=parent_node,+ children=None,+ synthesize_output=data.get("synthesize_output", None),+ need_regenerate_synthesize_output=data.get(+ "need_regenerate_synthesize_output", True+ ),+ )+ for child_data in data["children"]:+ child_node = helper(cls, child_data, parent_node=node)+ node.children.append(child_node)+ return node++ return helper(cls, data)+++class KnowledgeBase:+ """+ Class representing the knowledge base.++ Attributes:+ root (KnowledgeNode): The root node of the knowledge base.+ """++ def __init__(+ self,+ topic: str,+ knowledge_base_lm: Union[dspy.dsp.LM, dspy.dsp.HFModel],+ node_expansion_trigger_count: int,+ ):+ """+ Initializes a KnowledgeBase instance.++ Args:+ topic (str): The topic of the knowledge base+ expand_node_module (dspy.Module): The module that organize knowledge base in place.+ The module should accept knowledge base as param. E.g. expand_node_module(self)+ article_generation_module (dspy.Module): The module that generate report from knowledge base.+ The module should return string. E.g. report = article_generation_module(self)+ """+ from .collaborative_storm.modules.article_generation import (+ ArticleGenerationModule,+ )+ from .collaborative_storm.modules.information_insertion_module import (+ InsertInformationModule,+ ExpandNodeModule,+ )+ from .collaborative_storm.modules.knowledge_base_summary import (+ KnowledgeBaseSummaryModule,+ )++ self.topic: str = topic++ self.information_insert_module = InsertInformationModule(+ engine=knowledge_base_lm+ )+ self.expand_node_module = ExpandNodeModule(+ engine=knowledge_base_lm,+ information_insert_module=self.information_insert_module,+ node_expansion_trigger_count=node_expansion_trigger_count,+ )+ self.article_generation_module = ArticleGenerationModule(+ engine=knowledge_base_lm+ )+ self.gen_summary_module = KnowledgeBaseSummaryModule(engine=knowledge_base_lm)++ self.root: KnowledgeNode = KnowledgeNode(name="root")+ self.kb_embedding = {+ "hash": hash(""),+ "encoded_structure": np.array([[]]),+ "structure_string": "",+ }+ self.embedding_cache: Dict[str, np.ndarray] = {}+ self.info_uuid_to_info_dict: Dict[int, Information] = {}+ self.info_hash_to_uuid_dict: Dict[int, int] = {}+ self._lock = threading.Lock()++ def to_dict(self):+ info_uuid_to_info_dict = {+ key: value.to_dict() for key, value in self.info_uuid_to_info_dict.items()+ }+ return {+ "topic": self.topic,+ "tree": self.root.to_dict(),+ "info_uuid_to_info_dict": info_uuid_to_info_dict,+ "info_hash_to_uuid_dict": self.info_hash_to_uuid_dict,+ }++ @classmethod+ def from_dict(+ cls,+ data: Dict,+ knowledge_base_lm: Union[dspy.dsp.LM, dspy.dsp.HFModel],+ node_expansion_trigger_count: int,+ ):+ knowledge_base = cls(+ topic=data["topic"],+ knowledge_base_lm=knowledge_base_lm,+ node_expansion_trigger_count=node_expansion_trigger_count,+ )+ knowledge_base.root = KnowledgeNode.from_dict(data["tree"])+ knowledge_base.info_hash_to_uuid_dict = {+ int(key): int(value)+ for key, value in data["info_hash_to_uuid_dict"].items()+ }+ info_uuid_to_info_dict = {+ int(key): Information.from_dict(value)+ for key, value in data["info_uuid_to_info_dict"].items()+ }+ knowledge_base.info_uuid_to_info_dict = info_uuid_to_info_dict+ return knowledge_base++ def get_knowledge_base_structure_embedding(+ self, root: Optional[KnowledgeNode] = None+ ) -> Tuple[np.ndarray, List[str]]:+ outline_string = self.get_node_hierarchy_string(+ include_indent=False,+ include_full_path=True,+ include_hash_tag=False,+ root=root,+ )+ outline_string_hash = hash(outline_string)+ if outline_string_hash != self.kb_embedding["hash"]:+ outline_strings: List[str] = outline_string.split("\n")+ cleaned_outline_strings = [+ outline.replace(" -> ", ", ") for outline in outline_strings+ ]+ encoded_outline, _ = get_text_embeddings(+ cleaned_outline_strings, embedding_cache=self.embedding_cache+ )+ self.kb_embedding = {+ "hash": outline_string_hash,+ "encoded_structure": encoded_outline,+ "structure_string": outline_strings,+ }+ return (+ self.kb_embedding["encoded_structure"],+ self.kb_embedding["structure_string"],+ )++ def traverse_down(self, node):+ """+ Traverses the tree downward from the given node.++ Args:+ node (KnowledgeNode): The node to start the traversal from.++ Returns:+ list: A list of KnowledgeNode instances in the order they were visited.+ """+ nodes = []++ def _traverse(current_node):+ nodes.append(current_node)+ for child in current_node.get_children():+ _traverse(child)++ _traverse(node)+ return nodes++ def traverse_up(self, node):+ """+ Traverses the tree upward from the given node.++ Args:+ node (KnowledgeNode): The node to start the traversal from.++ Returns:+ list: A list of KnowledgeNode instances in the order they were visited.+ """+ nodes = []+ while node is not None:+ nodes.append(node)+ node = node.get_parent()+ return nodes++ def collect_all_nodes(self):+ nodes = []++ def _collect(node):+ nodes.append(node)+ for child in node.children:+ _collect(child)++ _collect(self.root)+ return nodes++ def insert_node(+ self,+ new_node_name,+ parent_node: Optional[KnowledgeNode] = None,+ duplicate_handling="skip",+ ):+ """+ Inserts a new node into the knowledge base under the specified parent node.++ Args:+ new_node_name (str): The name of the new node.+ parent_node_name (str): The name of the parent node. If None, the new node is inserted under the root.+ duplicate_handling (str): How to handle duplicate nodes. Options are "skip", "none", and "raise error".+ """+ if parent_node is None:+ return self.root.add_child(+ new_node_name, duplicate_handling=duplicate_handling+ )+ else:+ return parent_node.add_child(+ new_node_name, duplicate_handling=duplicate_handling+ )++ def find_node(self, current_node, node_name):+ """+ Finds a node by name in the knowledge base.++ Args:+ current_node (KnowledgeNode): The node to start the search from.+ node_name (str): The name of the node to find.++ Returns:+ KnowledgeNode: The node with the specified name, or None if not found.+ """+ if current_node.name == node_name:+ return current_node+ for child in current_node.get_children():+ result = self.find_node(child, node_name)+ if result is not None:+ return result+ return None++ def insert_from_outline_string(self, outline_string, duplicate_handling="skip"):+ """+ Creates and inserts nodes into the knowledge base from a string outline.++ Args:+ outline_string (str): The outline string where each line starts with '#' denoting the level.+ duplicate_handling (str): How to handle duplicate nodes. Options are "skip", "none", and "raise error".+ """+ last_node_at_level = {}+ for line in outline_string.split("\n"):+ level = line.count("#")+ if level > 0:+ title = line.strip("# ").strip()+ if title.lower() in ["overview", "summary", "introduction"]:+ continue+ parent_node = None if level == 1 else last_node_at_level.get(level - 1)+ new_node = self.insert_node(+ new_node_name=title,+ parent_node=parent_node,+ duplicate_handling=duplicate_handling,+ )+ last_node_at_level[level] = new_node+ for deeper_level in list(last_node_at_level.keys()):+ if deeper_level > level:+ del last_node_at_level[deeper_level]++ def get_node_hierarchy_string(+ self,+ include_indent=False,+ include_full_path=False,+ include_hash_tag=True,+ include_node_content_count=False,+ cited_indices: Optional[List[int]] = None,+ root: Optional[KnowledgeNode] = None,+ ) -> str:++ def find_node_contain_index(node, index):+ """+ Traverses the tree downward from the given node.++ Args:+ node (KnowledgeNode): The node to start the traversal from.++ Returns:+ list: A list of KnowledgeNode instances in the order they were visited.+ """+ nodes = []++ def _traverse(current_node):+ if current_node is not None and index in current_node.content:+ nodes.append(current_node)+ for child in current_node.get_children():+ _traverse(child)++ _traverse(node)+ return nodes++ paths_to_highlight = set()+ nodes_to_include = set()+ if cited_indices is not None:+ for index in cited_indices:+ for cur_node in find_node_contain_index(self.root, index):+ paths_to_highlight.add(" -> ".join(cur_node.get_path_from_root()))+ nodes_to_include.add(cur_node)+ nodes_to_include.update(cur_node.get_all_descendents())+ predecessors = cur_node.get_all_predecessors()+ for predecessor in predecessors:+ nodes_to_include.update(predecessor.children)+ nodes_to_include.update(predecessors)++ def should_include_node(node):+ if cited_indices is None:+ return True+ return node in nodes_to_include++ def should_omit_child_nodes(node):+ if cited_indices is None:+ return False+ for child in node.children:+ if should_include_node(child):+ return False+ return True++ def helper(cur_root, level):+ to_return = []+ if cur_root is not None:+ should_include_current_node = should_include_node(cur_root)++ indent = "" if not include_indent else "\t" * (level - 1)+ full_path = " -> ".join(cur_root.get_path_from_root(root=root))+ node_info = cur_root.name if not include_full_path else full_path+ hash_tag = "#" * level + " " if include_hash_tag else ""+ content_count = (+ f" ({len(cur_root.content)})" if include_node_content_count else ""+ )+ special_note = (+ ""+ if cited_indices is None or full_path not in paths_to_highlight+ else " ⭐"+ )++ if should_include_current_node:+ to_return.append(+ f"{indent}{hash_tag}{node_info}{content_count}{special_note}"+ )+ if should_omit_child_nodes(cur_root):+ if len(cur_root.children) > 0:+ child_indent = indent = (+ "" if not include_indent else "\t" * (level)+ )+ to_return.append(f"{child_indent}...")+ else:+ for child in cur_root.children:+ to_return.extend(helper(child, level + 1))+ return to_return++ to_return = []+ if root is None and self.root is not None:+ for child in self.root.children:+ to_return.extend(helper(child, level=1))+ else:+ to_return.extend(helper(root, level=1))++ return "\n".join(to_return)++ def find_node_by_path(+ self,+ path: str,+ missing_node_handling="abort",+ root: Optional[KnowledgeNode] = None,+ ):+ """+ Returns the target node given a path string.++ Args:+ path (str): The path to the node, with node names connected by " -> ".+ missing_node_handling (str): How to handle missing nodes. Options are "abort", "create", and "raise error".++ Returns:+ KnowledgeNode: The target node.+ """+ node_names = path.split(" -> ")+ current_node = self.root if root is None else root++ for name in node_names[1:]:+ found_node = next(+ (child for child in current_node.children if child.name == name), None+ )+ if found_node is None:+ if missing_node_handling == "abort":+ return+ elif missing_node_handling == "create":+ new_node = current_node.add_child(child_node_name=name)+ current_node = new_node+ elif missing_node_handling == "raise error":+ structure = self.get_node_hierarchy_string(+ include_indent=True,+ include_full_path=False,+ include_hash_tag=True,+ )+ raise Exception(+ f"Insert information error. Unable to find node {{{name}}} under {{{current_node.name}}}\n{structure}"+ )+ else:+ current_node = found_node+ return current_node++ def insert_information(+ self,+ path: str,+ information: Information,+ missing_node_handling="abort",+ root: Optional[KnowledgeNode] = None,+ ):+ """+ Inserts information into the knowledge base at the specified path.++ Args:+ path (str): The placement path string, connected by " -> " linking the name of nodes.+ information (Information): The information to insert.+ missing_node_handling (str): How to handle missing nodes. Options are "abort", "create", and "raise error".+ Return:+ uuid of insertion information+ """+ with self._lock:+ target_node: KnowledgeNode = self.find_node_by_path(+ path=path, missing_node_handling=missing_node_handling, root=root+ )+ information_hash = hash(information)+ if information.citation_uuid == -1:+ info_citation_uuid = self.info_hash_to_uuid_dict.get(+ information_hash, len(self.info_hash_to_uuid_dict) + 1+ )+ information.citation_uuid = info_citation_uuid+ self.info_hash_to_uuid_dict[information_hash] = info_citation_uuid+ self.info_uuid_to_info_dict[info_citation_uuid] = information+ if target_node is not None:+ self.info_uuid_to_info_dict[information.citation_uuid].meta[+ "placement"+ ] = " -> ".join(target_node.get_path_from_root())+ target_node.insert_information(information.citation_uuid)++ def trim_empty_leaf_nodes(self):+ """+ Trims all leaf nodes that do not have any content. Iteratively does it until all leaf nodes have at least one content.+ """++ def trim_node(node):+ if not node.children and not node.content:+ return True+ node.children = [child for child in node.children if not trim_node(child)]+ return not node.children and not node.content++ # Start the trimming process from the root+ while True:+ before_trim = len(self.get_all_leaf_nodes())+ trim_node(self.root)+ after_trim = len(self.get_all_leaf_nodes())+ if before_trim == after_trim:+ break++ def get_all_leaf_nodes(self):+ """+ Helper function to get all leaf nodes.++ Returns:+ List[KnowledgeNode]: A list of all leaf nodes in the knowledge base.+ """+ leaf_nodes = []++ def find_leaf_nodes(node):+ if not node.children:+ leaf_nodes.append(node)+ for child in node.children:+ find_leaf_nodes(child)++ find_leaf_nodes(self.root)+ return leaf_nodes++ def merge_single_child_nodes(self):+ """+ Merges content of a node with its single child and removes the child node.+ Iteratively does this from leaf nodes back to the root.+ """++ def merge_node(node):+ # Recursively merge children first+ for child in node.children:+ merge_node(child)++ # If the node has exactly one child, merge its content with the child and remove the child+ if len(node.children) == 1:+ single_child = node.children[0]+ node.content.update(single_child.content)+ node.children = single_child.children+ for grandchild in node.children:+ grandchild.parent = node++ merge_node(self.root)++ def update_all_info_path(self):+ def _helper(node):+ for citation_idx in node.content:+ self.info_uuid_to_info_dict[citation_idx].meta["placement"] = (+ " -> ".join(node.get_path_from_root())+ )+ for child in node.children:+ _helper(child)++ _helper(self.root)++ def update_from_conv_turn(+ self,+ conv_turn: ConversationTurn,+ allow_create_new_node: bool = False,+ insert_under_root: bool = False,+ ):+ if conv_turn is None:+ return+ info_to_insert = list(conv_turn.cited_info.values())+ if insert_under_root:+ for info in info_to_insert:+ self.insert_information(path=self.root.name, information=info)+ else:+ self.information_insert_module(+ knowledge_base=self,+ information=info_to_insert,+ allow_create_new_node=allow_create_new_node,+ )+ old_to_new_citation_idx_mapping = {+ old_idx: info.citation_uuid+ for old_idx, info in conv_turn.cited_info.items()+ }++ for old_idx, new_idx in old_to_new_citation_idx_mapping.items():+ conv_turn.utterance = conv_turn.utterance.replace(+ f"[{old_idx}]", f"[_{new_idx}_]"+ )+ conv_turn.raw_utterance = conv_turn.raw_utterance.replace(+ f"[{old_idx}]", f"[_{new_idx}_]"+ )+ for _, new_idx in old_to_new_citation_idx_mapping.items():+ conv_turn.utterance = conv_turn.utterance.replace(+ f"[_{new_idx}_]", f"[{new_idx}]"+ )+ conv_turn.utterance.replace("[-1]", "")+ conv_turn.raw_utterance = conv_turn.raw_utterance.replace(+ f"[_{new_idx}_]", f"[{new_idx}]"+ )+ conv_turn.raw_utterance.replace("[-1]", "")+ conv_turn.cited_info = None++ def get_knowledge_base_summary(self):+ return self.gen_summary_module(self)++ def reogranize(self):+ # pre-processing+ self.trim_empty_leaf_nodes()+ self.merge_single_child_nodes()+ # expand nodes+ self.expand_node_module(knowledge_base=self)+ # clean up+ self.trim_empty_leaf_nodes()+ self.merge_single_child_nodes()+ self.update_all_info_path()++ def to_report(self):+ return self.article_generation_module(knowledge_base=self)diff --git a/knowledge_storm/encoder.py b/knowledge_storm/encoder.pynew file mode 100644index 0000000..3d14e63--- /dev/null+++ b/knowledge_storm/encoder.py@@ -0,0 +1,169 @@+import requests+import os+from typing import List, Tuple, Union, Optional, Dict, Literal+import numpy as np++from concurrent.futures import ThreadPoolExecutor, as_completed+++class EmbeddingModel:+ def __init__():+ pass++ def get_embedding(self, text: str) -> Tuple[np.ndarray, int]:+ raise Exception("Not implemented")+++class OpenAIEmbeddingModel(EmbeddingModel):+ def __init__(self, model: str = "text-embedding-3-small", api_key: str = None):+ if not api_key:+ self.api_key = os.getenv("OPENAI_API_KEY")++ self.url = "https://api.openai.com/v1/embeddings"+ self.headers = {+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.api_key}",+ }+ self.model = model++ def get_embedding(self, text: str) -> Tuple[np.ndarray, int]:+ data = {"input": text, "model": "text-embedding-3-small"}++ response = requests.post(self.url, headers=self.headers, json=data)+ if response.status_code == 200:+ data = response.json()+ embedding = np.array(data["data"][0]["embedding"])+ token = data["usage"]["prompt_tokens"]+ return embedding, token+ else:+ response.raise_for_status()+++class OpenAIEmbeddingModel(EmbeddingModel):+ def __init__(self, model: str = "text-embedding-3-small", api_key: str = None):+ if not api_key:+ api_key = os.getenv("OPENAI_API_KEY")++ self.url = "https://api.openai.com/v1/embeddings"+ self.headers = {+ "Content-Type": "application/json",+ "Authorization": f"Bearer {api_key}",+ }+ self.model = model++ def get_embedding(self, text: str) -> Tuple[np.ndarray, int]:+ data = {"input": text, "model": self.model}++ response = requests.post(self.url, headers=self.headers, json=data)+ if response.status_code == 200:+ data = response.json()+ embedding = np.array(data["data"][0]["embedding"])+ token = data["usage"]["prompt_tokens"]+ return embedding, token+ else:+ response.raise_for_status()+++class TogetherEmbeddingModel:+ def __init__(self, model: str = "BAAI/bge-large-en-v1.5", api_key: str = None):+ import together++ self.model = model+ if not api_key:+ api_key = os.getenv("TOGETHER_API_KEY")+ self.together_client = together.Together(api_key=api_key)++ def get_embedding(self, text: str) -> Tuple[np.ndarray, int]:+ response = self.together_client.embeddings.create(input=text, model=self.model)+ return response.data[0].embedding, -1+++class AzureOpenAIEmbeddingModel:+ def __init__(self, model: str = "text-embedding-3-small", api_key: str = None):+ from openai import AzureOpenAI++ self.model = model+ if not api_key:+ api_key = os.getenv("AZURE_API_KEY")++ self.client = AzureOpenAI(+ api_key=api_key,+ api_version=os.getenv("AZURE_API_VERSION"),+ azure_endpoint=os.getenv("AZURE_API_BASE"),+ )++ def get_embedding(self, text: str) -> Tuple[np.ndarray, int]:+ response = self.client.embeddings.create(input=text, model=self.model)++ embedding = np.array(response.data[0].embedding)+ token = response.usage.prompt_tokens+ return embedding, token+++def get_text_embeddings(+ texts: Union[str, List[str]],+ max_workers: int = 5,+ embedding_cache: Optional[Dict[str, np.ndarray]] = None,+) -> Tuple[np.ndarray, int]:+ """+ Get text embeddings using OpenAI's text-embedding-3-small model.++ Args:+ texts (Union[str, List[str]]): A single text string or a list of text strings to embed.+ max_workers (int): The maximum number of workers for parallel processing.+ api_key (str): The API key for accessing OpenAI's services.+ embedding_cache (Optional[Dict[str, np.ndarray]]): A cache to store previously computed embeddings.++ Returns:+ Tuple[np.ndarray, int]: The 2D array of embeddings and the total token usage.+ """+ embedding_model = None+ encoder_type = os.getenv("ENCODER_API_TYPE")+ if encoder_type and encoder_type == "openai":+ embedding_model = OpenAIEmbeddingModel()+ elif encoder_type and encoder_type == "azure":+ embedding_model = AzureOpenAIEmbeddingModel()+ elif encoder_type == encoder_type == "together":+ embedding_model = TogetherEmbeddingModel()+ else:+ raise Exception(+ "No valid encoder type is provided. Check <repo root>/secrets.toml for the field ENCODER_API_TYPE"+ )++ def fetch_embedding(text: str) -> Tuple[str, np.ndarray, int]:+ if embedding_cache is not None and text in embedding_cache:+ return (+ text,+ embedding_cache[text],+ 0,+ ) # Returning 0 tokens since no API call is made+ embedding, token_usage = embedding_model.get_embedding(text)+ return text, embedding, token_usage++ if isinstance(texts, str):+ _, embedding, tokens = fetch_embedding(texts)+ return np.array(embedding), tokens++ embeddings = []+ total_tokens = 0++ with ThreadPoolExecutor(max_workers=max_workers) as executor:+ futures = {executor.submit(fetch_embedding, text): text for text in texts}++ for future in as_completed(futures):+ try:+ text, embedding, tokens = future.result()+ embeddings.append((text, embedding, tokens))+ total_tokens += tokens+ except Exception as e:+ print(f"An error occurred for text: {futures[future]}")+ print(e)++ # Sort results to match the order of the input texts+ embeddings.sort(key=lambda x: texts.index(x[0]))+ if embedding_cache is not None:+ for text, embedding, _ in embeddings:+ embedding_cache[text] = embedding+ embeddings = [result[1] for result in embeddings]++ return np.array(embeddings), total_tokensdiff --git a/knowledge_storm/interface.py b/knowledge_storm/interface.pyindex f6c11bd..f50ebbe 100644--- a/knowledge_storm/interface.py+++ b/knowledge_storm/interface.py@@ -1,27 +1,23 @@+import concurrent.futures+import dspyimport functools+import hashlib+import jsonimport loggingimport timefrom abc import ABC, abstractmethodfrom collections import OrderedDict-from typing import Dict, List, Optional, Union+from typing import Dict, List, Optional, Union, TYPE_CHECKING++from .utils import ArticleTextProcessinglogging.basicConfig(level=logging.INFO, format="%(name)s : %(levelname)-8s : %(message)s")logger = logging.getLogger(__name__)--class Information(ABC):- """Abstract base class to represent basic information.-- Attributes:- uuid (str): The unique identifier for the information.- meta (dict): The meta information associated with the information.- """-- def __init__(self, uuid, meta={}):- self.uuid = uuid- self.meta = meta+if TYPE_CHECKING:+ from .logging_wrapper import LoggingWrapperclass InformationTable(ABC):@@ -42,6 +38,101 @@ class InformationTable(ABC):pass+class Information:+ """Class to represent detailed information.++ Inherits from Information to include a unique identifier (URL), and extends+ it with a description, snippets, and title of the storm information.++ Attributes:+ description (str): Brief description.+ snippets (list): List of brief excerpts or snippets.+ title (str): The title or headline of the information.+ url (str): The unique URL (serving as UUID) of the information.+ """++ def __init__(self, url, description, snippets, title, meta=None):+ """Initialize the Information object with detailed attributes.++ Args:+ url (str): The unique URL serving as the identifier for the information.+ description (str): Detailed description.+ snippets (list): List of brief excerpts or snippet.+ title (str): The title or headline of the information.+ """+ self.description = description+ self.snippets = snippets+ self.title = title+ self.url = url+ self.meta = meta if meta is not None else {}+ self.citation_uuid = -1++ def __hash__(self):+ return hash(+ (+ self.url,+ tuple(sorted(self.snippets)),+ )+ )++ def __eq__(self, other):+ if not isinstance(other, Information):+ return False+ return (+ self.url == other.url+ and set(self.snippets) == set(other.snippets)+ and self._meta_str() == other._meta_str()+ )++ def __hash__(self):+ return int(+ self._md5_hash((self.url, tuple(sorted(self.snippets)), self._meta_str())),+ 16,+ )++ def _meta_str(self):+ """Generate a string representation of relevant meta information."""+ return f"Question: {self.meta.get('question', '')}, Query: {self.meta.get('query', '')}"++ def _md5_hash(self, value):+ """Generate an MD5 hash for a given value."""+ if isinstance(value, (dict, list, tuple)):+ value = json.dumps(value, sort_keys=True)+ return hashlib.md5(str(value).encode("utf-8")).hexdigest()++ @classmethod+ def from_dict(cls, info_dict):+ """Create a Information object from a dictionary.+ Usage: info = Information.from_dict(storm_info_dict)++ Args:+ info_dict (dict): A dictionary containing keys 'url', 'description',+ 'snippets', and 'title' corresponding to the object's attributes.++ Returns:+ Information: An instance of Information.+ """+ info = cls(+ url=info_dict["url"],+ description=info_dict["description"],+ snippets=info_dict["snippets"],+ title=info_dict["title"],+ meta=info_dict.get("meta", None),+ )+ info.citation_uuid = int(info_dict.get("citation_uuid", -1))+ return info++ def to_dict(self):+ return {+ "url": self.url,+ "description": self.description,+ "snippets": self.snippets,+ "title": self.title,+ "meta": self.meta,+ "citation_uuid": self.citation_uuid,+ }++class ArticleSectionNode:"""The ArticleSectionNode is the dataclass for handling the section of the article.@@ -166,7 +257,7 @@ class Article(ABC):return node-class Retriever(ABC):+class Retriever:"""An abstract base class for retriever modules. It provides a template for retrieving information based on a query.@@ -175,19 +266,14 @@ class Retriever(ABC):The retrieval model/search engine used for each part should be declared with a suffix '_rm' in the attribute name."""- def __init__(self, search_top_k):- self.search_top_k = search_top_k-- def update_search_top_k(self, k):- self.search_top_k = k+ def __init__(self, rm: dspy.Retrieve, max_thread: int = 1):+ self.max_thread = max_thread+ self.rm = rmdef collect_and_reset_rm_usage(self):combined_usage = []- for attr_name in self.__dict__:- if "_rm" in attr_name and hasattr(- getattr(self, attr_name), "get_usage_and_reset"- ):- combined_usage.append(getattr(self, attr_name).get_usage_and_reset())+ if hasattr(getattr(self, "rm"), "get_usage_and_reset"):+ combined_usage.append(getattr(self, "rm").get_usage_and_reset())name_to_usage = {}for usage in combined_usage:@@ -199,21 +285,38 @@ class Retriever(ABC):return name_to_usage- @abstractmethod- def retrieve(self, query: Union[str, List[str]], **kwargs) -> List[Information]:- """- Retrieves information based on a query.-- This method must be implemented by subclasses to specify how information is retrieved.-- Args:- query (Union[str, List[str]]): The query or list of queries to retrieve information for.- **kwargs: Additional keyword arguments that might be necessary for the retrieval process.-- Returns:- List[Information]: A list of Information objects retrieved based on the query.- """- pass+ def retrieve(+ self, query: Union[str, List[str]], exclude_urls: List[str] = []+ ) -> List[Information]:+ queries = query if isinstance(query, list) else [query]+ to_return = []++ def process_query(q):+ retrieved_data_list = self.rm(+ query_or_queries=[q], exclude_urls=exclude_urls+ )+ local_to_return = []+ for data in retrieved_data_list:+ for i in range(len(data["snippets"])):+ # STORM generate the article with citations. We do not consider multi-hop citations.+ # Remove citations in the source to avoid confusion.+ data["snippets"][i] = ArticleTextProcessing.remove_citations(+ data["snippets"][i]+ )+ storm_info = Information.from_dict(data)+ storm_info.meta["query"] = q+ local_to_return.append(storm_info)+ return local_to_return++ with concurrent.futures.ThreadPoolExecutor(+ max_workers=self.max_thread+ ) as executor:+ results = list(executor.map(process_query, queries))++ for result in results:+ to_return.extend(result)++ return to_returnclass KnowledgeCurationModule(ABC):@@ -458,3 +561,27 @@ class Engine(ABC):self.time = {}self.lm_cost = {}self.rm_cost = {}+++class Agent(ABC):+ from .dataclass import KnowledgeBase, ConversationTurn++ def __init__(self, topic: str, role_name: str, role_description: str):+ self.topic = topic+ self.role_name = role_name+ self.role_description = role_description++ def get_role_description(self):+ if self.role_description:+ return f"{self.role_name}: {self.role_description}"+ return self.role_name++ @abstractmethod+ def generate_utterance(+ self,+ knowledge_base: KnowledgeBase,+ conversation_history: List[ConversationTurn],+ logging_wrapper: "LoggingWrapper",+ **kwargs,+ ):+ passdiff --git a/knowledge_storm/lm.py b/knowledge_storm/lm.pyindex 2c0773d..0cae49b 100644--- a/knowledge_storm/lm.py+++ b/knowledge_storm/lm.py@@ -24,7 +24,7 @@ class OpenAIModel(dspy.OpenAI):def __init__(self,- model: str = "gpt-3.5-turbo-instruct",+ model: str = "gpt-4o-mini",api_key: Optional[str] = None,model_type: Literal["chat", "text"] = None,**kwargs,@@ -211,7 +211,7 @@ class AzureOpenAIModel(dspy.AzureOpenAI):self,api_base: Optional[str] = None,api_version: Optional[str] = None,- model: str = "gpt-3.5-turbo-instruct",+ model: str = "gpt-4o-mini",api_key: Optional[str] = None,model_type: Literal["chat", "text"] = "chat",**kwargs,@@ -674,21 +674,28 @@ class TogetherClient(dspy.HFModel):def __init__(self,model,+ api_key: Optional[str] = None,apply_tokenizer_chat_template=False,hf_tokenizer_name=None,+ model_type: Literal["chat", "text"] = "chat",**kwargs,):"""Copied from dspy/dsp/modules/hf_client.py with the support of applying tokenizer chat template."""super().__init__(model=model, is_client=True)self.session = requests.Session()- self.api_base = (- "https://api.together.xyz/v1/completions"- if os.getenv("TOGETHER_API_BASE") is None- else os.getenv("TOGETHER_API_BASE")+ self.api_key = api_key = (+ os.environ.get("TOGETHER_API_KEY") if api_key is None else api_key)- self.token = os.getenv("TOGETHER_API_KEY")self.model = model+ self.model_type = model_type+ if os.getenv("TOGETHER_API_BASE") is None:+ if self.model_type == "chat":+ self.api_base = "https://api.together.xyz/v1/chat/completions"+ else:+ self.api_base = "https://api.together.xyz/v1/completions"+ else:+ self.api_base = os.getenv("TOGETHER_API_BASE")# self.use_inst_template = False# if any(keyword in self.model.lower() for keyword in ["inst", "instruct"]):@@ -705,12 +712,12 @@ class TogetherClient(dspy.HFModel):stop_default = "\n\n---"self.kwargs = {- "temperature": 0.0,- "max_tokens": 512,- "top_p": 1,- "top_k": 20,+ "temperature": kwargs.get("temperature", 0.0),+ "max_tokens": min(kwargs.get("max_tokens", 4096), 4096),+ "top_p": kwargs.get("top_p", 1.0),+ "top_k": kwargs.get("top_k", 1),"repetition_penalty": 1,- "n": 1,+ "n": kwargs.pop("n", kwargs.pop("num_generations", 1)),"stop": stop_default if "stop" not in kwargs else kwargs["stop"],**kwargs,}@@ -745,9 +752,7 @@ class TogetherClient(dspy.HFModel):max_time=1000,on_backoff=backoff_hdlr,)- def _generate(self, prompt, use_chat_api=False, **kwargs):- url = f"{self.api_base}"-+ def _generate(self, prompt, **kwargs):kwargs = {**self.kwargs, **kwargs}stop = kwargs.get("stop")@@ -762,8 +767,7 @@ class TogetherClient(dspy.HFModel):)# prompt = f"[INST]{prompt}[/INST]" if self.use_inst_template else prompt- if use_chat_api:- url = f"{self.api_base}/chat/completions"+ if self.model_type == "chat":messages = [{"role": "system",@@ -793,13 +797,13 @@ class TogetherClient(dspy.HFModel):"stop": stop,}- headers = {"Authorization": f"Bearer {self.token}"}+ headers = {"Authorization": f"Bearer {self.api_key}"}- with self.session.post(url, headers=headers, json=body) as resp:+ with self.session.post(self.api_base, headers=headers, json=body) as resp:resp_json = resp.json()# Log the token usage from the Together API response.self.log_usage(resp_json)- if use_chat_api:+ if self.model_type == "chat":# completions = [resp_json['output'].get('choices', [])[0].get('message', {}).get('content', "")]completions = [resp_json.get("choices", [])[0]diff --git a/knowledge_storm/logging_wrapper.py b/knowledge_storm/logging_wrapper.pynew file mode 100644index 0000000..48d7e29--- /dev/null+++ b/knowledge_storm/logging_wrapper.py@@ -0,0 +1,212 @@+from contextlib import contextmanager+import time+import pytz+from datetime import datetime++# Define California timezone+CALIFORNIA_TZ = pytz.timezone("America/Los_Angeles")+++class EventLog:+ def __init__(self, event_name):+ self.event_name = event_name+ self.start_time = None+ self.end_time = None+ self.child_events = {}++ def record_start_time(self):+ self.start_time = datetime.now(+ pytz.utc+ ) # Store in UTC for consistent timezone conversion++ def record_end_time(self):+ self.end_time = datetime.now(+ pytz.utc+ ) # Store in UTC for consistent timezone conversion++ def get_total_time(self):+ if self.start_time and self.end_time:+ return (self.end_time - self.start_time).total_seconds()+ return 0++ def get_start_time(self):+ if self.start_time:+ # Format to milliseconds+ return self.start_time.astimezone(CALIFORNIA_TZ).strftime(+ "%Y-%m-%d %H:%M:%S.%f"+ )[:-3]+ return None++ def get_end_time(self):+ if self.end_time:+ # Format to milliseconds+ return self.end_time.astimezone(CALIFORNIA_TZ).strftime(+ "%Y-%m-%d %H:%M:%S.%f"+ )[:-3]+ return None++ def add_child_event(self, child_event):+ self.child_events[child_event.event_name] = child_event++ def get_child_events(self):+ return self.child_events+++class LoggingWrapper:+ def __init__(self, lm_config):+ self.logging_dict = {}+ self.lm_config = lm_config+ self.current_pipeline_stage = None+ self.event_stack = []+ self.pipeline_stage_active = False++ def _pipeline_stage_start(self, pipeline_stage: str):+ if self.pipeline_stage_active:+ raise RuntimeError(+ "A pipeline stage is already active. End the current stage before starting a new one."+ )++ self.current_pipeline_stage = pipeline_stage+ self.logging_dict[pipeline_stage] = {+ "time_usage": {},+ "lm_usage": {},+ "lm_history": [],+ "query_count": 0,+ }+ self.pipeline_stage_active = True++ def _event_start(self, event_name: str):+ if not self.pipeline_stage_active:+ raise RuntimeError("No pipeline stage is currently active.")++ if not self.event_stack and self.current_pipeline_stage:+ # Top-level event (directly under the pipeline stage)+ if (+ event_name+ not in self.logging_dict[self.current_pipeline_stage]["time_usage"]+ ):+ event = EventLog(event_name=event_name)+ event.record_start_time()+ self.logging_dict[self.current_pipeline_stage]["time_usage"][+ event_name+ ] = event+ self.event_stack.append(event)+ else:+ self.logging_dict[self.current_pipeline_stage]["time_usage"][+ event_name+ ].record_start_time()+ elif self.event_stack:+ # Nested event (under another event)+ parent_event = self.event_stack[-1]+ if event_name not in parent_event.get_child_events():+ event = EventLog(event_name=event_name)+ event.record_start_time()+ parent_event.add_child_event(event)+ self.logging_dict[self.current_pipeline_stage]["time_usage"][+ event_name+ ] = event+ self.event_stack.append(event)+ else:+ parent_event.get_child_events()[event_name].record_start_time()+ else:+ raise RuntimeError(+ "Cannot start an event without an active pipeline stage or parent event."+ )++ def _event_end(self, event_name: str):+ if not self.pipeline_stage_active:+ raise RuntimeError("No pipeline stage is currently active.")++ if not self.event_stack:+ raise RuntimeError("No parent event is currently active.")++ if self.event_stack:+ current_event_log = self.event_stack[-1]+ if event_name in current_event_log.get_child_events():+ current_event_log.get_child_events()[event_name].record_end_time()+ elif (+ event_name+ in self.logging_dict[self.current_pipeline_stage]["time_usage"]+ ):+ self.logging_dict[self.current_pipeline_stage]["time_usage"][+ event_name+ ].record_end_time()+ else:+ raise AssertionError(+ f"Failure to record end time for event {event_name}. Start time is not recorded."+ )+ if current_event_log.event_name == event_name:+ self.event_stack.pop()+ else:+ raise RuntimeError("Cannot end an event without an active parent event.")++ def _pipeline_stage_end(self):+ if not self.pipeline_stage_active:+ raise RuntimeError("No pipeline stage is currently active to end.")++ self.logging_dict[self.current_pipeline_stage][+ "lm_usage"+ ] = self.lm_config.collect_and_reset_lm_usage()+ self.logging_dict[self.current_pipeline_stage][+ "lm_history"+ ] = self.lm_config.collect_and_reset_lm_history()+ self.pipeline_stage_active = False++ def add_query_count(self, count):+ if not self.pipeline_stage_active:+ raise RuntimeError(+ "No pipeline stage is currently active to add query count."+ )++ self.logging_dict[self.current_pipeline_stage]["query_count"] += count++ @contextmanager+ def log_event(self, event_name):+ if not self.pipeline_stage_active:+ raise RuntimeError("No pipeline stage is currently active.")++ self._event_start(event_name)+ yield+ self._event_end(event_name)++ @contextmanager+ def log_pipeline_stage(self, pipeline_stage):+ if self.pipeline_stage_active:+ print(+ "A pipeline stage is already active, ending the current stage safely."+ )+ self._pipeline_stage_end()++ start_time = time.time()+ try:+ self._pipeline_stage_start(pipeline_stage)+ yield+ except Exception as e:+ print(f"Error occurred during pipeline stage '{pipeline_stage}': {e}")+ finally:+ self.logging_dict[self.current_pipeline_stage]["total_wall_time"] = (+ time.time() - start_time+ )+ self._pipeline_stage_end()++ def dump_logging_and_reset(self, reset_logging=True):+ log_dump = {}+ for pipeline_stage, pipeline_log in self.logging_dict.items():+ time_stamp_log = {+ event_name: {+ "total_time_seconds": event.get_total_time(),+ "start_time": event.get_start_time(),+ "end_time": event.get_end_time(),+ }+ for event_name, event in pipeline_log["time_usage"].items()+ }+ log_dump[pipeline_stage] = {+ "time_usage": time_stamp_log,+ "lm_usage": pipeline_log["lm_usage"],+ "lm_history": pipeline_log["lm_history"],+ "query_count": pipeline_log["query_count"],+ "total_wall_time": pipeline_log["total_wall_time"],+ }+ if reset_logging:+ self.logging_dict.clear()+ return log_dumpdiff --git a/knowledge_storm/rm.py b/knowledge_storm/rm.pyindex 80b8a38..d023d4a 100644--- a/knowledge_storm/rm.py+++ b/knowledge_storm/rm.py@@ -333,10 +333,77 @@ class VectorRM(dspy.Retrieve):return collected_results+class StanfordOvalArxivRM(dspy.Retrieve):+ def __init__(self, endpoint, k=3):+ super().__init__(k=k)+ self.endpoint = endpoint+ self.usage = 0++ def get_usage_and_reset(self):+ usage = self.usage+ self.usage = 0++ return {"CS224vArxivRM": usage}++ def _retrieve(self, query: str):+ payload = {"query": query, "num_blocks": self.k}++ response = requests.post(+ self.endpoint, json=payload, headers={"Content-Type": "application/json"}+ )++ # Check if the request was successful+ if response.status_code == 200:+ data = response.json()[0]+ results = []+ for i in range(len(data["title"])):+ result = {+ "title": data["title"][i],+ "url": data["title"][i],+ "snippets": [data["text"][i]],+ "description": "N/A",+ "meta": {"section_title": data["full_section_title"][i]},+ }+ results.append(result)++ return results+ else:+ raise Exception(+ f"Error: Unable to retrieve results. Status code: {response.status_code}"+ )++ def forward(+ self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = []+ ):+ collected_results = []+ queries = (+ [query_or_queries]+ if isinstance(query_or_queries, str)+ else query_or_queries+ )++ for query in queries:+ try:+ results = self._retrieve(query)+ collected_results.extend(results)+ except Exception as e:+ logging.error(f"Error occurs when searching query {query}: {e}")+ return collected_results++class SerperRM(dspy.Retrieve):"""Retrieve information from custom queries using Serper.dev."""- def __init__(self, serper_search_api_key=None, query_params=None):+ def __init__(+ self,+ serper_search_api_key=None,+ k=3,+ query_params=None,+ ENABLE_EXTRA_SNIPPET_EXTRACTION=False,+ min_char_count: int = 150,+ snippet_chunk_size: int = 1000,+ webpage_helper_max_threads=10,+ ):"""Args:serper_search_api_key str: API key to run serper, can be found by creating an account on https://serper.dev/query_params (dict or list of dict): parameters in dictionary or list of dictionaries that has a max size of 100 that will be used to query.@@ -355,9 +422,21 @@ class SerperRM(dspy.Retrieve):qdr:m str: Date time range for past month.qdr:y str: Date time range for past year."""- super().__init__()+ super().__init__(k=k)self.usage = 0- self.query_params = query_params+ self.query_params = None+ self.ENABLE_EXTRA_SNIPPET_EXTRACTION = ENABLE_EXTRA_SNIPPET_EXTRACTION+ self.webpage_helper = WebPageHelper(+ min_char_count=min_char_count,+ snippet_chunk_size=snippet_chunk_size,+ max_thread_num=webpage_helper_max_threads,+ )++ if query_params is None:+ self.query_params = {"num": k, "autocorrect": True, "page": 1}+ else:+ self.query_params = query_params+ self.query_params.update({"num": k})self.serper_search_api_key = serper_search_api_keyif not self.serper_search_api_key and not os.environ.get("SERPER_API_KEY"):raise RuntimeError(@@ -386,7 +465,7 @@ class SerperRM(dspy.Retrieve):if response == None:raise RuntimeError(- f"Error had occurred while running the search process.\n Error is {response.reason}, had failed with status code {response.status_code}"+ f"Error had occured while running the search process.\n Error is {response.reason}, had failed with status code {response.status_code}")return response.json()@@ -435,34 +514,41 @@ class SerperRM(dspy.Retrieve):# Array of dictionaries that will be used by Storm to create the jsonscollected_results = []+ if self.ENABLE_EXTRA_SNIPPET_EXTRACTION:+ urls = []+ for result in self.results:+ organic_results = result.get("organic", [])+ for organic in organic_results:+ url = organic.get("link")+ if url:+ urls.append(url)+ valid_url_to_snippets = self.webpage_helper.urls_to_snippets(urls)+ else:+ valid_url_to_snippets = {}+for result in self.results:try:# An array of dictionaries that contains the snippets, title of the document and url that will be used.organic_results = result.get("organic")-knowledge_graph = result.get("knowledgeGraph")for organic in organic_results:- snippets = []- snippets.append(organic.get("snippet"))- if knowledge_graph != None:- collected_results.append(- {- "snippets": snippets,- "title": organic.get("title"),- "url": organic.get("link"),- "description": knowledge_graph.get("description"),- }- )- else:- # Common for knowledge graph to be None, set description to empty string- collected_results.append(- {- "snippets": snippets,- "title": organic.get("title"),- "url": organic.get("link"),- "description": "",- }+ snippets = [organic.get("snippet")]+ if self.ENABLE_EXTRA_SNIPPET_EXTRACTION:+ snippets.extend(+ valid_url_to_snippets.get(url, {}).get("snippets", []))+ collected_results.append(+ {+ "snippets": snippets,+ "title": organic.get("title"),+ "url": organic.get("link"),+ "description": (+ knowledge_graph.get("description")+ if knowledge_graph is not None+ else ""+ ),+ }+ )except:continuediff --git a/knowledge_storm/storm_wiki/engine.py b/knowledge_storm/storm_wiki/engine.pyindex de9f5f1..62887a2 100644--- a/knowledge_storm/storm_wiki/engine.py+++ b/knowledge_storm/storm_wiki/engine.py@@ -12,10 +12,9 @@ from .modules.callback import BaseCallbackHandlerfrom .modules.knowledge_curation import StormKnowledgeCurationModulefrom .modules.outline_generation import StormOutlineGenerationModulefrom .modules.persona_generator import StormPersonaGenerator-from .modules.retriever import StormRetrieverfrom .modules.storm_dataclass import StormInformationTable, StormArticle-from ..interface import Engine, LMConfigs-from ..lm import OpenAIModel+from ..interface import Engine, LMConfigs, Retriever+from ..lm import OpenAIModel, AzureOpenAIModelfrom ..utils import FileIOHelper, makeStringRed, truncate_filename@@ -39,6 +38,7 @@ class STORMWikiLMConfigs(LMConfigs):def init_openai_model(self,openai_api_key: str,+ azure_api_key: str,openai_type: Literal["openai", "azure"],api_base: Optional[str] = None,api_version: Optional[str] = None,@@ -46,19 +46,27 @@ class STORMWikiLMConfigs(LMConfigs):top_p: Optional[float] = 0.9,):"""Legacy: Corresponding to the original setup in the NAACL'24 paper."""+ azure_kwargs = {+ "api_key": azure_api_key,+ "temperature": temperature,+ "top_p": top_p,+ "api_base": api_base,+ "api_version": api_version,+ }+openai_kwargs = {"api_key": openai_api_key,- "api_provider": openai_type,+ "api_provider": "openai","temperature": temperature,"top_p": top_p,"api_base": None,}if openai_type and openai_type == "openai":self.conv_simulator_lm = OpenAIModel(- model="gpt-3.5-turbo-instruct", max_tokens=500, **openai_kwargs+ model="gpt-4o-mini-2024-07-18", max_tokens=500, **openai_kwargs)self.question_asker_lm = OpenAIModel(- model="gpt-3.5-turbo", max_tokens=500, **openai_kwargs+ model="gpt-4o-mini-2024-07-18", max_tokens=500, **openai_kwargs)# 1/12/2024: Update gpt-4 to gpt-4-1106-preview. (Currently keep the original setup when using azure.)self.outline_gen_lm = OpenAIModel(@@ -70,6 +78,32 @@ class STORMWikiLMConfigs(LMConfigs):self.article_polish_lm = OpenAIModel(model="gpt-4o-2024-05-13", max_tokens=4000, **openai_kwargs)+ elif openai_type and openai_type == "azure":+ self.conv_simulator_lm = OpenAIModel(+ model="gpt-4o-mini-2024-07-18", max_tokens=500, **openai_kwargs+ )+ self.question_asker_lm = AzureOpenAIModel(+ model="gpt-4o-mini-2024-07-18",+ max_tokens=500,+ **azure_kwargs,+ model_type="chat",+ )+ # use combination of openai and azure-openai as azure-openai does not support gpt-4 in standard deployment+ self.outline_gen_lm = AzureOpenAIModel(+ model="gpt-4o", max_tokens=400, **azure_kwargs, model_type="chat"+ )+ self.article_gen_lm = AzureOpenAIModel(+ model="gpt-4o-mini-2024-07-18",+ max_tokens=700,+ **azure_kwargs,+ model_type="chat",+ )+ self.article_polish_lm = AzureOpenAIModel(+ model="gpt-4o-mini-2024-07-18",+ max_tokens=4000,+ **azure_kwargs,+ model_type="chat",+ )else:logging.warning("No valid OpenAI API provider is provided. Cannot use default LLM configurations."@@ -145,7 +179,7 @@ class STORMWikiRunner(Engine):self.args = argsself.lm_configs = lm_configs- self.retriever = StormRetriever(rm=rm, k=self.args.retrieve_top_k)+ self.retriever = Retriever(rm=rm, max_thread=self.args.max_thread_num)storm_persona_generator = StormPersonaGenerator(self.lm_configs.question_asker_lm)diff --git a/knowledge_storm/storm_wiki/modules/article_generation.py b/knowledge_storm/storm_wiki/modules/article_generation.pyindex 2e71146..a23b788 100644--- a/knowledge_storm/storm_wiki/modules/article_generation.py+++ b/knowledge_storm/storm_wiki/modules/article_generation.py@@ -7,8 +7,8 @@ from typing import List, Unionimport dspyfrom .callback import BaseCallbackHandler-from .storm_dataclass import StormInformationTable, StormArticle, StormInformation-from ...interface import ArticleGenerationModule+from .storm_dataclass import StormInformationTable, StormArticle+from ...interface import ArticleGenerationModule, Informationfrom ...utils import ArticleTextProcessing@@ -33,7 +33,7 @@ class StormArticleGenerationModule(ArticleGenerationModule):def generate_section(self, topic, section_name, information_table, section_outline, section_query):- collected_info: List[StormInformation] = []+ collected_info: List[Information] = []if information_table is not None:collected_info = information_table.retrieve_information(queries=section_query, search_top_k=self.retrieve_top_k@@ -143,11 +143,7 @@ class ConvToSection(dspy.Module):self.engine = enginedef forward(- self,- topic: str,- outline: str,- section: str,- collected_info: List[StormInformation],+ self, topic: str, outline: str, section: str, collected_info: List[Information]):info = ""for idx, storm_info in enumerate(collected_info):diff --git a/knowledge_storm/storm_wiki/modules/knowledge_curation.py b/knowledge_storm/storm_wiki/modules/knowledge_curation.pyindex bde2767..ca6377d 100644--- a/knowledge_storm/storm_wiki/modules/knowledge_curation.py+++ b/knowledge_storm/storm_wiki/modules/knowledge_curation.py@@ -8,8 +8,8 @@ import dspyfrom .callback import BaseCallbackHandlerfrom .persona_generator import StormPersonaGenerator-from .storm_dataclass import DialogueTurn, StormInformationTable, StormInformation-from ...interface import KnowledgeCurationModule, Retriever+from .storm_dataclass import DialogueTurn, StormInformationTable+from ...interface import KnowledgeCurationModule, Retriever, Informationfrom ...utils import ArticleTextProcessingtry:@@ -196,14 +196,13 @@ class TopicExpert(dspy.Module):super().__init__()self.generate_queries = dspy.Predict(QuestionToQuery)self.retriever = retriever- self.retriever.update_search_top_k(search_top_k)self.answer_question = dspy.Predict(AnswerQuestion)self.engine = engineself.max_search_queries = max_search_queriesself.search_top_k = search_top_kdef forward(self, topic: str, question: str, ground_truth_url: str):- with dspy.settings.context(lm=self.engine):+ with dspy.settings.context(lm=self.engine, show_guidelines=False):# Identify: Break down question into queries.queries = self.generate_queries(topic=topic, question=question).queriesqueries = [@@ -212,7 +211,7 @@ class TopicExpert(dspy.Module):]queries = queries[: self.max_search_queries]# Search- searched_results: List[StormInformation] = self.retriever.retrieve(+ searched_results: List[Information] = self.retriever.retrieve(list(set(queries)), exclude_urls=[ground_truth_url])if len(searched_results) > 0:diff --git a/knowledge_storm/storm_wiki/modules/retriever.py b/knowledge_storm/storm_wiki/modules/retriever.pyindex 85df63e..691382b 100644--- a/knowledge_storm/storm_wiki/modules/retriever.py+++ b/knowledge_storm/storm_wiki/modules/retriever.py@@ -3,7 +3,6 @@ from urllib.parse import urlparseimport dspy-from .storm_dataclass import StormInformationfrom ...interface import Retriever, Informationfrom ...utils import ArticleTextProcessing@@ -232,26 +231,3 @@ def is_valid_wikipedia_source(url):return Falsereturn True---class StormRetriever(Retriever):- def __init__(self, rm: dspy.Retrieve, k=3):- super().__init__(search_top_k=k)- self._rm = rm- if hasattr(rm, "is_valid_source"):- rm.is_valid_source = is_valid_wikipedia_source-- def retrieve(- self, query: Union[str, List[str]], exclude_urls: List[str] = []- ) -> List[Information]:- retrieved_data_list = self._rm(- query_or_queries=query, exclude_urls=exclude_urls- )- for data in retrieved_data_list:- for i in range(len(data["snippets"])):- # STORM generate the article with citations. We do not consider multi-hop citations.- # Remove citations in the source to avoid confusion.- data["snippets"][i] = ArticleTextProcessing.remove_citations(- data["snippets"][i]- )- return [StormInformation.from_dict(data) for data in retrieved_data_list]diff --git a/knowledge_storm/storm_wiki/modules/storm_dataclass.py b/knowledge_storm/storm_wiki/modules/storm_dataclass.pyindex 43826ec..75812d9 100644--- a/knowledge_storm/storm_wiki/modules/storm_dataclass.py+++ b/knowledge_storm/storm_wiki/modules/storm_dataclass.py@@ -11,69 +11,13 @@ from ...interface import Information, InformationTable, Article, ArticleSectionNfrom ...utils import ArticleTextProcessing, FileIOHelper-class StormInformation(Information):- """Class to represent detailed information.-- Inherits from Information to include a unique identifier (URL), and extends- it with a description, snippets, and title of the storm information.-- Attributes:- description (str): Brief description.- snippets (list): List of brief excerpts or snippets.- title (str): The title or headline of the information.- url (str): The unique URL (serving as UUID) of the information.- """-- def __init__(self, uuid, description, snippets, title):- """Initialize the StormInformation object with detailed attributes.-- Args:- uuid (str): The unique URL serving as the identifier for the information.- description (str): Detailed description.- snippets (list): List of brief excerpts or snippet.- title (str): The title or headline of the information.- """- super().__init__(uuid=uuid, meta={})- self.description = description- self.snippets = snippets- self.title = title- self.url = self.uuid-- @classmethod- def from_dict(cls, info_dict):- """Create a StormInformation object from a dictionary.- Usage: storm_info = StormInformation.from_dict(storm_info_dict)-- Args:- info_dict (dict): A dictionary containing keys 'uuid', 'description',- 'snippets', and 'title' corresponding to the object's attributes.-- Returns:- StormInformation: An instance of StormInformation.- """- return cls(- info_dict["url"],- info_dict["description"],- info_dict["snippets"],- info_dict["title"],- )-- def to_dict(self):- return {- "url": self.uuid,- "description": self.description,- "snippets": self.snippets,- "title": self.title,- }--class DialogueTurn:def __init__(self,agent_utterance: str = None,user_utterance: str = None,search_queries: Optional[List[str]] = None,- search_results: Optional[List[Union[StormInformation, Dict]]] = None,+ search_results: Optional[List[Union[Information, Dict]]] = None,):self.agent_utterance = agent_utteranceself.user_utterance = user_utterance@@ -83,7 +27,7 @@ class DialogueTurn:if self.search_results:for idx in range(len(self.search_results)):if type(self.search_results[idx]) == dict:- self.search_results[idx] = StormInformation.from_dict(+ self.search_results[idx] = Information.from_dict(self.search_results[idx])@@ -91,7 +35,6 @@ class DialogueTurn:"""Returns a json object that contains all information inside `self`"""-return OrderedDict({"agent_utterance": self.agent_utterance,@@ -115,14 +58,14 @@ class StormInformationTable(InformationTable):def __init__(self, conversations=List[Tuple[str, List[DialogueTurn]]]):super().__init__()self.conversations = conversations- self.url_to_info: Dict[str, StormInformation] = (+ self.url_to_info: Dict[str, Information] = (StormInformationTable.construct_url_to_info(self.conversations))@staticmethoddef construct_url_to_info(conversations: List[Tuple[str, List[DialogueTurn]]]- ) -> Dict[str, StormInformation]:+ ) -> Dict[str, Information]:url_to_info = {}for persona, conv in conversations:@@ -177,7 +120,7 @@ class StormInformationTable(InformationTable):def retrieve_information(self, queries: Union[List[str], str], search_top_k- ) -> List[StormInformation]:+ ) -> List[Information]:selected_urls = []selected_snippets = []if type(queries) is str:@@ -231,13 +174,13 @@ class StormArticle(Article):return Nonedef _merge_new_info_to_references(- self, new_info_list: List[StormInformation], index_to_keep=None+ self, new_info_list: List[Information], index_to_keep=None) -> Dict[int, int]:"""Merges new storm information into existing references and updates the citation index mapping.Args:- new_info_list (List[StormInformation]): A list of dictionaries representing new storm information.+ new_info_list (List[Information]): A list of dictionaries representing new storm information.index_to_keep (List[int]): A list of index of the new_info_list to keep. If none, keep all.Returns:@@ -308,7 +251,7 @@ class StormArticle(Article):def update_section(self,current_section_content: str,- current_section_info_list: List[StormInformation],+ current_section_info_list: List[Information],parent_section_name: Optional[str] = None,) -> Optional[ArticleSectionNode]:"""@@ -552,7 +495,7 @@ class StormArticle(Article):article = cls(topic_name=topic_name)article.insert_or_create_section(article_dict=article_dict)for url in list(references["url_to_info"]):- references["url_to_info"][url] = StormInformation.from_dict(+ references["url_to_info"][url] = Information.from_dict(references["url_to_info"][url])article.reference = references