instructor
103 строки · 3.2 Кб
1from openai import OpenAI2import instructor3
4from graphviz import Digraph5from typing import Optional6
7from pydantic import BaseModel, Field8
9client = instructor.from_openai(OpenAI())10
11
12class Node(BaseModel):13id: int14label: str15color: str16
17def __hash__(self) -> int:18return hash((id, self.label))19
20
21class Edge(BaseModel):22source: int23target: int24label: str25color: str = "black"26
27def __hash__(self) -> int:28return hash((self.source, self.target, self.label))29
30
31class KnowledgeGraph(BaseModel):32nodes: Optional[list[Node]] = Field(..., default_factory=list)33edges: Optional[list[Edge]] = Field(..., default_factory=list)34
35def update(self, other: "KnowledgeGraph") -> "KnowledgeGraph":36"""Updates the current graph with the other graph, deduplicating nodes and edges."""37return KnowledgeGraph(38nodes=list(set(self.nodes + other.nodes)),39edges=list(set(self.edges + other.edges)),40)41
42def draw(self, prefix: str = None):43dot = Digraph(comment="Knowledge Graph")44
45# Add nodes46for node in self.nodes:47dot.node(str(node.id), node.label, color=node.color)48
49# Add edges50for edge in self.edges:51dot.edge(52str(edge.source), str(edge.target), label=edge.label, color=edge.color53)54dot.render(prefix, format="png", view=True)55
56
57def generate_graph(input: list[str]) -> KnowledgeGraph:58cur_state = KnowledgeGraph()59num_iterations = len(input)60for i, inp in enumerate(input):61new_updates = client.chat.completions.create(62model="gpt-3.5-turbo-16k",63messages=[64{65"role": "system",66"content": """You are an iterative knowledge graph builder.67You are given the current state of the graph, and you must append the nodes and edges
68to it Do not procide any duplcates and try to reuse nodes as much as possible.""",69},70{71"role": "user",72"content": f"""Extract any new nodes and edges from the following:73# Part {i}/{num_iterations} of the input:74
75{inp}""",76},77{78"role": "user",79"content": f"""Here is the current state of the graph:80{cur_state.model_dump_json(indent=2)}""",81},82],83response_model=KnowledgeGraph,84) # type: ignore85
86# Update the current state87cur_state = cur_state.update(new_updates)88cur_state.draw(prefix=f"iteration_{i}")89return cur_state90
91
92# here we assume that we have to process the text in chunks
93# one at a time since they may not fit in the prompt otherwise
94text_chunks = [95"Jason knows a lot about quantum mechanics. He is a physicist. He is a professor",96"Professors are smart.",97"Sarah knows Jason and is a student of his.",98"Sarah is a student at the University of Toronto. and UofT is in Canada.",99]
100
101graph: KnowledgeGraph = generate_graph(text_chunks)102
103graph.draw(prefix="final")104