a
    dgˡ                     @   s:  d dl Z d dlZd dlmZmZmZmZmZmZm	Z	m
Z
mZ d dlmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZmZmZ d d	lmZ d d
lmZm Z m!Z! dZ"dddddddddddddddddddddddddddddddddddgZ#dZ$dPe%ed!d"d#Z&e%e%d$d%d&Z'dQee
ee% eee%e%e%f  f  e%e%ee% ee% eed(d)d*Z(G d+d, d,eZ)G d-d. d.eZ*dReee%  ee
ee% eee%e%e%f  f  ee% ee% ed/d0d1Z+dSeee%  ee
ee% eee%e%e%f  f  e
e,ee% f ee% e
e,ee% f ee% e	e) d3d4d5Z-eed6d7d8Z.eed9d:d;Z/ee%ef eee ee f d<d=d>Z0ee ee d?d@dAZ1ee ee dBdCdDZ2e%e%dEdFdGZ3eeef eee ee f dHdIdJZ4e
ee% eee%e%e%f  f eee%  ee% dKdLdMZ5G dNdO dOZ6dS )T    N)	AnyDictListOptionalSequenceTupleTypeUnioncast)GraphDocumentNodeRelationship)Document)BaseLanguageModel)SystemMessage)JsonOutputParser)ChatPromptTemplateHumanMessagePromptTemplatePromptTemplate)RunnableConfig)	BaseModelFieldcreate_modelr   zeAdam is a software engineer in Microsoft since 2009, and last year he got an award as the Best TalentZAdamZPersonZ	WORKS_FOR	MicrosoftZCompany)texthead	head_typerelationtail	tail_typeZ	HAS_AWARDzBest TalentZAwardzPMicrosoft is a tech company that provide several products such as Microsoft WordzMicrosoft WordZProductZPRODUCED_BYz;Microsoft Word is a lightweight app that accessible offlineZHAS_CHARACTERISTICzlightweight appZCharacteristiczaccessible offlinea  # Knowledge Graph Instructions for GPT-4
## 1. Overview
You are a top-tier algorithm designed for extracting information in structured formats to build a knowledge graph.
Try to capture as much information from the text as possible without sacrificing accuracy. Do not add any information that is not explicitly mentioned in the text.
- **Nodes** represent entities and concepts.
- The aim is to achieve simplicity and clarity in the knowledge graph, making it
accessible for a vast audience.
## 2. Labeling Nodes
- **Consistency**: Ensure you use available types for node labels.
Ensure you use basic or elementary types for node labels.
- For example, when you identify an entity representing a person, always label it as **'person'**. Avoid using more specific terms like 'mathematician' or 'scientist'.- **Node IDs**: Never utilize integers as node IDs. Node IDs should be names or human-readable identifiers found in the text.
- **Relationships** represent connections between entities or concepts.
Ensure consistency and generality in relationship types when constructing knowledge graphs. Instead of using specific and momentary types such as 'BECAME_PROFESSOR', use more general and timeless relationship types like 'PROFESSOR'. Make sure to use general and timeless relationship types!
## 3. Coreference Resolution
- **Maintain Entity Consistency**: When extracting entities, it's vital to ensure consistency.
If an entity, such as "John Doe", is mentioned multiple times in the text but is referred to by different names or pronouns (e.g., "Joe", "he"),always use the most complete identifier for that entity throughout the knowledge graph. In this example, use "John Doe" as the entity ID.
Remember, the knowledge graph should be coherent and easily understandable, so maintaining consistency in entity references is crucial.
## 4. Strict Compliance
Adhere to the rules strictly. Non-compliance will result in termination. )additional_instructionsreturnc                 C   s   t dtfd| d fgS )NsystemZhumanz Tip: Make sure to answer in the correct format and do not include any explanations. Use the given format to extract information from the following input: {input})r   from_messagessystem_prompt)r!    r&   {/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_experimental/graph_transformers/llm.pyget_default_promptn   s    r(   )
input_typer"   c                 C   s8   | dvrt d| dkrdS | dkr(dS | dkr4dS dS )	N)noderelationshippropertyz8input_type must be 'node', 'relationship', or 'property'r*   zEnsure you use basic or elementary types for node labels.
For example, when you identify an entity representing a person, always label it as **'Person'**. Avoid using more specific terms like 'Mathematician' or 'Scientist'r+   zInstead of using specific and momentary types such as 'BECAME_PROFESSOR', use more general and timeless relationship types like 'PROFESSOR'. However, do not sacrifice any accuracy for generalityr,   r    )
ValueError)r)   r&   r&   r'   _get_additional_info   s    r.   r*   )enum_valuesdescriptionr)   llm_typerelationship_typefield_kwargsr"   c                 K   s   | }|dkrt dd | D }| rH|dkrHtd
|| d| d|S | rhtdd| d| i|S t|}tdd|| i|S d	S )zIUtility function to conditionally create a field with an enum constraint.tuplec                 S   s   h | ]}|d  qS    r&   .0elr&   r&   r'   	<setcomp>       z&optional_enum_field.<locals>.<setcomp>zopenai-chat.z. Available options are )enumr0   r0   N).).).)listr   r.   )r/   r0   r)   r1   r2   r3   Zparsed_enum_valuesZadditional_infor&   r&   r'   optional_enum_field   s,    	  r>   c                   @   s&   e Zd ZU ee ed< ee ed< dS )_GraphnodesrelationshipsN)__name__
__module____qualname__r   r   __annotations__r&   r&   r&   r'   r?      s   
r?   c                   @   sh   e Zd ZU eddZeed< eddZeed< eddZeed< eddZ	eed	< ed
dZ
eed< dS )UnstructuredRelationz]extracted head entity like Microsoft, Apple, John. Must use human-readable unique identifier.r0   r   z;type of the extracted head entity like Person, Company, etcr   z/relation between the head and the tail entitiesr   z]extracted tail entity like Microsoft, Apple, John. Must use human-readable unique identifier.r   z;type of the extracted tail entity like Person, Company, etcr   N)rB   rC   rD   r   r   strrE   r   r   r   r   r&   r&   r&   r'   rF      s   
rF   )node_labels	rel_typesr2   r!   r"   c                 C   s:  | rt | nd}|r>|dkr4t tdd |D }qBt |}nd}d| rTd| dnd|rfd| dnd| rxd	| dnd|dkrd
| nddd|g}dtd |}t|d}ttd}	d| rdnd|rdnd|dkrd
| ndd|dg}
dtd |
}t|dg|	 | |t	dd}t
|d}t||g}|S )Nr    r4   c                 S   s   h | ]}|d  qS r5   r&   r8   itemr&   r&   r'   r:      r;   z-create_unstructured_prompt.<locals>.<setcomp>a  You are a top-tier algorithm designed for extracting information in structured formats to build a knowledge graph. Your task is to identify the entities and relations requested with the user prompt from a given text. You must generate the output in a JSON format containing a list with JSON objects. Each object should have the keys: "head", "head_type", "relation", "tail", and "tail_type". The "head" key must contain the text of the extracted entity with one of the types from the provided list in the user prompt.zlThe "head_type" key must contain the type of the extracted head entity, which must be one of the types from .zThe "relation" key must contain the type of relation between the "head" and the "tail", which must be one of the relations from zThe "tail" key must represent the text of an extracted entity which is the tail of the relation, and the "tail_type" key must contain the type of the tail entity from   Your task is to extract relationships from text strictly adhering to the provided schema. The relationships can only appear between specific node types are presented in the schema format like: (Entity1Type, RELATIONSHIP_TYPE, Entity2Type) /nProvided schema is a  Attempt to extract as many entities and relations as you can. Maintain Entity Consistency: When extracting entities, it's vital to ensure consistency. If an entity, such as "John Doe", is mentioned multiple times in the text but is referred to by different names or pronouns (e.g., "Joe", "he"), always use the most complete identifier for that entity. The knowledge graph should be coherent and easily understandable, so maintaining consistency in entity references is crucial.z7IMPORTANT NOTES:
- Don't add any explanation and text. 
)content)Zpydantic_objectzXBased on the following example, extract entities and relations from the provided text.

zmUse the following entity types, don't use other entity that is not defined below:# ENTITY TYPES:{node_labels}zqUse the following relation types, don't use other relation that is not defined below:# RELATION TYPES:{rel_types}zaBelow are a number of examples of text and their extracted entities and relationships.{examples}
zuFor the following text, extract entities and relations as in the provided example.{format_instructions}
Text: {input}input)Zformat_instructionsrI   rJ   examples)templateZinput_variablesZpartial_variables)prompt)rH   r=   joinfilterr   r   rF   r   Zget_format_instructionsrR   r   r   r$   )rI   rJ   r2   r!   Znode_labels_strZrel_types_strZbase_string_partsr%   Zsystem_messageparserZhuman_string_partsZhuman_prompt_stringZhuman_promptZhuman_message_promptZchat_promptr&   r&   r'   create_unstructured_prompt   s    

(


rX   F)rI   rJ   node_propertiesr1   relationship_propertiesr2   r"   c                    s  t tdddft t| dddfd}|rt|trDd|v rDtd	|d
u rPg n|G fdddt}tt|  tdddf|d< t	d"i | t tdddft t| dddft tdddft t| dddft t|dd|dfd}|rVt|trd|v rtd|d
u r g n|G fdddt}	tt|	  tdddf|d< t	d#i ||dkrzd| _
G  fd d!d!t}
|
S )$a  
    Create a simple graph model with optional constraints on node
    and relationship types.

    Args:
        node_labels (Optional[List[str]]): Specifies the allowed node types.
            Defaults to None, allowing all node types.
        rel_types (Optional[List[str]]): Specifies the allowed relationship types.
            Defaults to None, allowing all relationship types.
        node_properties (Union[bool, List[str]]): Specifies if node properties should
            be included. If a list is provided, only properties with keys in the list
            will be included. If True, all properties are included. Defaults to False.
        relationship_properties (Union[bool, List[str]]): Specifies if relationship
            properties should be included. If a list is provided, only properties with
            keys in the list will be included. If True, all properties are included.
            Defaults to False.
        llm_type (Optional[str]): The type of the language model. Defaults to None.
            Only openai supports enum param: openai-chat.

    Returns:
        Type[_Graph]: A graph model with the specified constraints.

    Raises:
        ValueError: If 'id' is included in the node or relationship properties list.
    .z)Name or human-readable unique identifier.rG   zThe type or label of the node.r*   r0   r)   r1   idtyper]   z6The node property 'id' is reserved and cannot be used.Tc                       s>   e Zd ZU dZedd dZeed< edddZ	eed	< d
S )z%create_simple_model.<locals>.Property-A single property consisting of key and valueProperty key.r,   r[   key.BExtracted value. Any date value should be formatted as yyyy-mm-dd.rG   valueN
rB   rC   rD   __doc__r>   ra   rH   rE   r   rc   r&   )r1   node_properties_mappedr&   r'   Property{  s   
rg   NzList of node properties
properties
SimpleNodez7Name or human-readable unique identifier of source nodez%The type or label of the source node.z7Name or human-readable unique identifier of target nodez%The type or label of the target node.zThe type of the relationship.r+   )r0   r)   r1   r2   )source_node_idsource_node_typetarget_node_idtarget_node_typer^   z>The relationship property 'id' is reserved and cannot be used.c                       s>   e Zd ZU dZedd dZeed< edddZ	eed	< d
S )z1create_simple_model.<locals>.RelationshipPropertyr_   r`   r,   r[   ra   .rb   rG   rc   Nrd   r&   )r1   relationship_properties_mappedr&   r'   RelationshipProperty  s   
ro   zList of relationship propertiesSimpleRelationshipr4   rN   c                       sF   e Zd ZU dZeddZee   ed< eddZ	ee  ed< dS )z)create_simple_model.<locals>.DynamicGraphzBRepresents a graph document consisting of nodes and relationships.zList of nodesrG   r@   zList of relationshipsrA   N)
rB   rC   rD   re   r   r@   r   r   rE   rA   r&   )ri   rp   r&   r'   DynamicGraph  s
   
rq   )ri   )rp   )rH   r   r>   
isinstancer=   r-   r   r   r   r   re   r?   )rI   rJ   rY   r1   rZ   r2   Znode_fieldsrg   Zrelationship_fieldsro   rq   r&   )ri   rp   r1   rf   rn   r'   create_simple_modelA  s    $




,


rs   )r*   r"   c                 C   sB   i }t | dr0| jr0| jD ]}|j|t|j< qt| j| j|dS )z$Map the SimpleNode to the base Node.rh   r]   r^   rh   )hasattrrh   rc   format_property_keyra   r   r]   r^   )r*   rh   pr&   r&   r'   map_to_base_node  s
    
rx   )relr"   c                 C   sb   t | j| jd}t | j| jd}i }t| drP| jrP| jD ]}|j|t|j	< q:t
||| j|dS )z4Map the SimpleRelationship to the base Relationship.r\   rh   sourcetargetr^   rh   )r   rj   rk   rl   rm   ru   rh   rc   rv   ra   r   r^   )ry   r{   r|   rh   rw   r&   r&   r'   map_to_base_relationship  s    

r}   )argument_jsonr"   c           	   	      s  g }| d D ]f}| dsqi }d|v rR|d rR|d D ]}|d |t|d < q8|t|d | dt|d qg }| d D ]6   d	r  d
r  dsq  dsz" fdd| d D d  d< W n ty   t d< Y n0   ds:z" fdd| d D d  d< W n ty8   t d< Y n0 i }d v rv d rv d D ]}|d |t|d < qZt d	  d d}t d
  d d}|t|| d |d q||fS )Nr@   r]   rh   rc   ra   r^   rt   rA   rj   rl   rk   c                    s&   g | ]}|d   d kr| dqS )r]   rj   r^   getr7   ry   r&   r'   
<listcomp>+  s   z)_parse_and_clean_json.<locals>.<listcomp>r   rm   c                    s&   g | ]}|d   d kr| dqS )r]   rl   r^   r   r7   r   r&   r'   r   4  s   r\   rz   )r   rv   appendr   DEFAULT_NODE_TYPE
IndexErrorr   )	r~   r@   r*   rY   rw   rA   Zrel_propertiessource_nodetarget_noder&   r   r'   _parse_and_clean_json  s~    




r   )r@   r"   c                 C   s   dd | D S )Nc                 S   sD   g | ]<}t t|jtr |j n|j|jr4|j nt|jd qS )rt   )	r   rr   r]   rH   titler^   
capitalizer   rh   r7   r&   r&   r'   r   U  s   z!_format_nodes.<locals>.<listcomp>r&   )r@   r&   r&   r'   _format_nodesT  s    r   )relsr"   c                 C   s   dd | D S )Nc              	   S   sD   g | ]<}t t|jgd  t|jgd  |jdd |jdqS )r    _rz   )r   r   r{   r|   r^   replaceupperrh   r7   r&   r&   r'   r   b  s   z)_format_relationships.<locals>.<listcomp>r&   )r   r&   r&   r'   _format_relationshipsa  s    r   )sr"   c                 C   sB   |   }|s| S |d  }dd |dd  D }d|g| S )Nr   c                 S   s   g | ]}|  qS r&   )r   )r8   wordr&   r&   r'   r   r  r;   z'format_property_key.<locals>.<listcomp>r6   r    )splitlowerrU   )r   wordsZ
first_wordZcapitalized_wordsr&   r&   r'   rv   m  s    rv   )
raw_schemar"   c                 C   s@  | d szz$t | d jd d d d }W n ty   zt | d jd d }W nd ty   | d jd d }t|d	 trt |d	 |d	< t|d
 trt |d
 |d
< Y n0 Y n0 t|\}}W n ty   g g f Y S 0 n@| d }|jrdd |jD ng }|j	r,dd |j	D ng }t
|t|fS )Nparsedraw
tool_callsr   function	argumentsZfunction_callargsr@   rA   c                 S   s   g | ]}|j rt|qS r&   )r]   rx   r8   r*   r&   r&   r'   r     r;   z._convert_to_graph_document.<locals>.<listcomp>c                 S   s&   g | ]}|j r|jr|jrt|qS r&   )r^   rj   rl   r}   r8   ry   r&   r&   r'   r     s   )jsonloadsZadditional_kwargs	Exceptionr   rr   rH   r   r@   rA   r   r   )r   r~   r@   rA   Zparsed_schemar&   r&   r'   _convert_to_graph_documentv  sL    

r   )allowed_relationshipsallowed_nodesr"   c                    sZ   | rt | tstd| sd S tdd | D r4dS t fdd| D rNdS tdd S )Nz1`allowed_relationships` attribute must be a list.c                 s   s   | ]}t |tV  qd S Nrr   rH   rK   r&   r&   r'   	<genexpr>  r;   z5validate_and_get_relationship_type.<locals>.<genexpr>stringc                 3   sN   | ]F}t |toDt|d koDtdd |D oD|d  v oD|d  v V  qdS )   c                 s   s   | ]}t |tV  qd S r   r   )r8   subitemr&   r&   r'   r     r;   z?validate_and_get_relationship_type.<locals>.<genexpr>.<genexpr>r      N)rr   r4   lenallrK   r   r&   r'   r     s   


r4   z`allowed_relationships` must be list of strings or a list of 3-item tuples. For tuples, the first and last elements must be in the `allowed_nodes` list.)rr   r=   r-   r   )r   r   r&   r   r'   "validate_and_get_relationship_type  s    	r   c                   @   s   e Zd ZdZg g ddddddfeee eee eeeeef  f e	e
 eeeee f eeee f eedd
ddZdee	e ed	d
dZdee e	e ee dddZdee	e ed	ddZdee e	e ee dddZdS )LLMGraphTransformeraD
  Transform documents into graph-based documents using a LLM.

    It allows specifying constraints on the types of nodes and relationships to include
    in the output graph. The class supports extracting properties for both nodes and
    relationships.

    Args:
        llm (BaseLanguageModel): An instance of a language model supporting structured
          output.
        allowed_nodes (List[str], optional): Specifies which node types are
          allowed in the graph. Defaults to an empty list, allowing all node types.
        allowed_relationships (List[str], optional): Specifies which relationship types
          are allowed in the graph. Defaults to an empty list, allowing all relationship
          types.
        prompt (Optional[ChatPromptTemplate], optional): The prompt to pass to
          the LLM with additional instructions.
        strict_mode (bool, optional): Determines whether the transformer should apply
          filtering to strictly adhere to `allowed_nodes` and `allowed_relationships`.
          Defaults to True.
        node_properties (Union[bool, List[str]]): If True, the LLM can extract any
          node properties from text. Alternatively, a list of valid properties can
          be provided for the LLM to extract, restricting extraction to those specified.
        relationship_properties (Union[bool, List[str]]): If True, the LLM can extract
          any relationship properties from text. Alternatively, a list of valid
          properties can be provided for the LLM to extract, restricting extraction to
          those specified.
        ignore_tool_usage (bool): Indicates whether the transformer should
          bypass the use of structured output functionality of the language model.
          If set to True, the transformer will not use the language model's native
          function calling capabilities to handle structured output. Defaults to False.
        additional_instructions (str): Allows you to add additional instructions
          to the prompt without having to change the whole prompt.

    Example:
        .. code-block:: python
            from langchain_experimental.graph_transformers import LLMGraphTransformer
            from langchain_core.documents import Document
            from langchain_openai import ChatOpenAI

            llm=ChatOpenAI(temperature=0)
            transformer = LLMGraphTransformer(
                llm=llm,
                allowed_nodes=["Person", "Organization"])

            doc = Document(page_content="Elon Musk is suing OpenAI")
            graph_documents = transformer.convert_to_graph_documents([doc])
    NTFr    )
llmr   r   rT   strict_moderY   rZ   ignore_tool_usager!   r"   c
                 C   s  t ||| _|| _|| _|| _| | _| jrTz|t W n tyR   d| _Y n0 | js|sb|rjt	dzdd l
}
|
| _
W n ty   tdY n0 |pt||| j|	}||B | _n\z
|j}W n ty   d }Y n0 t|||||| j}|j|dd}|pt|	}||B | _d S )NFzThe 'node_properties' and 'relationship_properties' parameters cannot be used in combination with a LLM that doesn't support native function calling.r   z^Could not import json_repair python package. Please install it with `pip install json-repair`.T)Zinclude_raw)r   _relationship_typer   r   r   _function_callZwith_structured_outputr?   NotImplementedErrorr-   json_repairImportErrorrX   chainZ	_llm_typeAttributeErrorrs   r(   )selfr   r   r   rT   r   rY   rZ   r   r!   r   r1   ZschemaZstructured_llmr&   r&   r'   __init__  s\    



zLLMGraphTransformer.__init__)documentconfigr"   c                    s  |j }jjd|i|d}jr@ttttf |}t|\}}nt }g }t	|t
sZ|j}j|}t	|trv|g}|D ]}	t	|	trz|	drz|	drz|	dsqz||	d |	dtf ||	d |	dtf t|	d |	dtd}
t|	d |	dtd}|t|
||	d d	 qzd
d t|D }jrƈjsPjrƈjrdd jD   fdd|D } fdd|D }jrƈjdkrfdd|D }nfdd|D }t|||dS )z
        Processes a single document, transforming it into a graph document using
        an LLM based on the model's schema and constraints.
        rQ   r   r   r   r   r   r   r\   r{   r|   r^   c                 S   s    g | ]}t |d  |d dqS r   r6   r\   r   r7   r&   r&   r'   r   m  r;   z8LLMGraphTransformer.process_response.<locals>.<listcomp>c                 S   s   g | ]}|  qS r&   r   r7   r&   r&   r'   r   r  r;   c                    s   g | ]}|j   v r|qS r&   r^   r   r   lower_allowed_nodesr&   r'   r   s  s   c                    s0   g | ](}|j j  v r|jj  v r|qS r&   r{   r^   r   r|   r   r   r&   r'   r   v  s   r4   c                    s@   g | ]8}|j j |j |jj fd d  jD v r|qS )c                 S   s(   g | ] \}}}|  |  |  fqS r&   r   r8   Zs_tZr_tZt_tr&   r&   r'   r     s   CLLMGraphTransformer.process_response.<locals>.<listcomp>.<listcomp>r{   r^   r   r|   r   r   r   r&   r'   r     s   

c                    s*   g | ]"}|j  d d  jD v r|qS )c                 S   s   g | ]}|  qS r&   r   r7   r&   r&   r'   r     r;   r   r^   r   r   r   r   r&   r'   r     s
   r@   rA   r{   )page_contentr   Zinvoker   r
   r   r   r   setrr   rH   rP   r   r   dictr   addr   r   r   r   r=   r   r   r   r   r   r   r   r   r   r   r@   rA   Z	nodes_setZparsed_jsonry   r   r   r&   r   r   r'   process_response?  sl    






z$LLMGraphTransformer.process_response)	documentsr   r"   c                    s    fdd|D S )a  Convert a sequence of documents into graph documents.

        Args:
            documents (Sequence[Document]): The original documents.
            kwargs: Additional keyword arguments.

        Returns:
            Sequence[GraphDocument]: The transformed documents as graphs.
        c                    s   g | ]} | qS r&   )r   r8   r   r   r   r&   r'   r     r;   zBLLMGraphTransformer.convert_to_graph_documents.<locals>.<listcomp>r&   )r   r   r   r&   r   r'   convert_to_graph_documents  s    z.LLMGraphTransformer.convert_to_graph_documentsc                    s  |j }jjd|i|dI dH }jrFttttf |}t|\}}nt }g }t	|t
s`|j}j|}t	|tr||g}|D ]}	|	dr|	dr|	dsq||	d |	dtf ||	d |	dtf t|	d |	dtd	}
t|	d |	dtd	}|t|
||	d d
 qdd t|D }jrjsLjrjrdd jD   fdd|D } fdd|D }jrjdkrfdd|D }nfdd|D }t|||dS )zl
        Asynchronously processes a single document, transforming it into a
        graph document.
        rQ   r   Nr   r   r   r   r   r\   r   c                 S   s    g | ]}t |d  |d dqS r   r   r7   r&   r&   r'   r     r;   z9LLMGraphTransformer.aprocess_response.<locals>.<listcomp>c                 S   s   g | ]}|  qS r&   r   r7   r&   r&   r'   r     r;   c                    s   g | ]}|j   v r|qS r&   r   r   r   r&   r'   r     s   c                    s0   g | ](}|j j  v r|jj  v r|qS r&   r   r   r   r&   r'   r     s   r4   c                    s@   g | ]8}|j j |j |jj fd d  jD v r|qS )c                 S   s(   g | ] \}}}|  |  |  fqS r&   r   r   r&   r&   r'   r     s   DLLMGraphTransformer.aprocess_response.<locals>.<listcomp>.<listcomp>r   r   r   r&   r'   r     s   

c                    s*   g | ]"}|j  d d  jD v r|qS )c                 S   s   g | ]}|  qS r&   r   r7   r&   r&   r'   r     r;   r   r   r   r   r&   r'   r     s
   r   )r   r   Zainvoker   r
   r   r   r   r   rr   rH   rP   r   r   r   r   r   r   r   r   r   r=   r   r   r   r   r   r   r&   r   r'   aprocess_response  sh    






z%LLMGraphTransformer.aprocess_responsec                    s(    fdd|D }t j| I dH }|S )zV
        Asynchronously convert a sequence of documents into graph documents.
        c                    s   g | ]}t | qS r&   )asynciocreate_taskr   r   r   r&   r'   r     s   zCLLMGraphTransformer.aconvert_to_graph_documents.<locals>.<listcomp>N)r   gather)r   r   r   tasksresultsr&   r   r'   aconvert_to_graph_documents  s
    z/LLMGraphTransformer.aconvert_to_graph_documents)N)N)N)N)rB   rC   rD   re   r   r   rH   r	   r   r   r   boolr   r   r   r   r   r   r   r   r   r&   r&   r&   r'   r     sR   3E Z  X r   )r    )Nr    r*   NN)NNNr    )NNFNFN)7r   r   typingr   r   r   r   r   r   r   r	   r
   Z)langchain_community.graphs.graph_documentr   r   r   Zlangchain_core.documentsr   Zlangchain_core.language_modelsr   Zlangchain_core.messagesr   Zlangchain_core.output_parsersr   Zlangchain_core.promptsr   r   r   Zlangchain_core.runnablesr   Zpydanticr   r   r   r   rR   r%   rH   r(   r.   r>   r?   rF   rX   r   rs   rx   r}   r   r   r   rv   r   r   r   r&   r&   r&   r'   <module>   s   ,	5'       !    
 n      
  6	
H

4
!