<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ed Sandoval on Medium]]></title>
        <description><![CDATA[Stories by Ed Sandoval on Medium]]></description>
        <link>https://medium.com/@edward.sandoval.2000?source=rss-a636110c8d3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*crTWn7IfCEo7RRVkxHiZng.jpeg</url>
            <title>Stories by Ed Sandoval on Medium</title>
            <link>https://medium.com/@edward.sandoval.2000?source=rss-a636110c8d3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:15:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edward.sandoval.2000/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Evaluate Your Neo4j Aura Agent Using Comet Opik]]></title>
            <link>https://medium.com/neo4j/how-to-evaluate-your-neo4j-aura-agent-using-comets-opik-65a08787662d?source=rss-a636110c8d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/65a08787662d</guid>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agent-evaluation]]></category>
            <dc:creator><![CDATA[Ed Sandoval]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 11:53:43 GMT</pubDate>
            <atom:updated>2026-03-03T09:59:35.797Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://neo4j.com/blog/agentic-ai/neo4j-launches-aura-agent/"><strong>Neo4j Aura Agent</strong> </a>reached general availability less than two weeks ago, and teams are already seeing better explainability, richer context, and higher-quality answers. It’s early, but the momentum is real.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rApzMsEH3bng3xQ86uo6AQ.png" /></figure><p>Almost every conversation quickly lands on the same question: <strong><em>“</em></strong><em>How do I evaluate my Aura Agent?”</em></p><p>Aura Agent includes a testing facility within the Aura Console. It is great to explore how your agent reasons, which tools it calls, and which Cypher queries it runs. But evaluation remains manual and most importantly, it won’t surface regressions as prompts, tools, or graph data change.</p><p>In this post, I’ll walk you through the Python code to build a <strong>repeatable evaluation pipeline</strong> for an Aura Agent using <a href="https://www.comet.com/site/products/opik/">Comet’s Opik</a> — an open-source platform for evaluating, tracing, and comparing LLM and agent behavior. We’ll define a ground-truth question set, automatically score answers with predefined LLM-as-a-judge metrics, and capture full execution traces, so you can evaluate your Aura Agent every time something changes.</p><h3>The Aura Agent and Dataset We’re Evaluating</h3><p>For this walkthrough, we’re using the <a href="https://github.com/neo4j-product-examples/knowledge-graph-agent/blob/main/contract-review.md"><strong>Commercial Contract Review Agent</strong></a> — one of the examples available in the Neo4j Aura Agent tutorial. The knowledge graph behind it is built from <strong>CUAD</strong> (the Contract Understanding Atticus Dataset), a corpus of over 13,000 labels across 510 commercial legal contracts. You can learn more about CUAD at the <a href="https://www.atticusprojectai.org/cuad">Atticus Project page</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQGocqdTnxgIrxOXdMNpWQ.png" /></figure><p>To set up the agent and dataset yourself, follow the <a href="https://github.com/neo4j-product-examples/knowledge-graph-agent/blob/main/contract-review.md">Contract Review Agent tutorial</a> — it covers creating the Aura instance, loading CUAD dataset into a knowledge graph, and deploying the agent to a REST endpoint.</p><h3><strong>A Primer on Opik Evaluation Concepts</strong></h3><p>Before jumping into the code, it’s helpful to understand the core concepts behind <strong>Opik’s Agent Evaluation</strong> and how they apply to evaluating your <a href="https://neo4j.com/developer/genai-ecosystem/aura-agent/"><strong>Aura Agent</strong>.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJlcY30nEYqwz206UYmFcg.jpeg" /><figcaption>Aura Agent Evaluation in Comet Opik</figcaption></figure><p>A few Opik concepts:</p><ul><li><a href="https://www.comet.com/docs/opik/evaluation/concepts#datasets"><strong>Dataset</strong></a>: A reusable set of test questions (inputs) and expected answers (outputs).</li><li><a href="https://www.comet.com/docs/opik/evaluation/concepts#experiments"><strong>Experiment</strong></a>: One pass through the dataset — run the agent, score every agent answer (e.g. calculate multiple metrics) and generate experiment-level (aggregated) metrics.</li><li><a href="https://www.comet.com/docs/opik/evaluation/metrics/overview#llm-as-a-judge-metrics"><strong>Metrics</strong></a>: Scoring functions such as “Answer Relevance”. Opik offers a number of predefined LLM-as-a-judge metrics.</li><li><a href="https://www.comet.com/docs/opik/tracing/concepts#traces"><strong>Traces</strong></a><strong> and </strong><a href="https://www.comet.com/docs/opik/tracing/concepts#spans"><strong>Spans</strong></a>: A hierarchical record of what happened during a single Aura agent call — in this case your Aura Agent question, each agent thinking block and tool called with details of all inputs and outputs.</li><li><a href="https://www.comet.com/docs/opik/tracing/concepts#threads"><strong>Thread</strong></a>: A conversation-level grouping of all traces related to a conversation with the agent.</li><li><strong>Evaluation Task Function:</strong> This is the code that runs your agent and gets an answer for a given question in the Dataset. In our case, it is just a wrapper to send a question to your Aura Agent REST endpoint.</li></ul><p>Let’s get everything set up…</p><h4>Prerequisites</h4><p>Let’s make sure you have your Aura Agent and Opik set up.</p><ol><li><strong>Aura Agent:</strong> If you don’t already have the Contract Review Agent running, follow the <a href="https://github.com/neo4j-product-examples/knowledge-graph-agent/blob/main/contract-review.md">tutorial </a>. Once set up, you’ll have the CLIENT_ID, CLIENT_SECRET, and ENDPOINT_URL needed to to interact with your agent via the Aura API.</li><li><strong>Opik (localhost)</strong>: For this walkthrough, we’ll run Opik locally using Docker. This keeps everything on your machine and doesn’t require a Comet cloud account. You’ll need git and docker installed.</li><li><strong>OpenAI Key:</strong> Opik ships with a number of <strong>LLM-as-a-judge</strong> metrics out of the box — Answer Relevance, Hallucination, Usefulness, and others. These aren’t simple string comparisons; each metric has its own evaluation prompt that gets sent to an LLM, which then scores the agent’s answer. That means every dataset item you evaluate requires one or more LLM calls per metric. For this, You’ll need an OPENAI_API_KEY with available credits.</li></ol><p>The simplest way to get Opik running locally is</p><pre># Clone the Opik repository<br>git clone https://github.com/comet-ml/opik.git<br><br># Navigate to the opik folder<br>cd opik<br><br># Start the Opik platform<br>./opik.sh</pre><p>Once it’s running, Opik will be available at <a href="http://localhost:5173.">http://localhost:5173</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYtIiIwjBO8I_rSwq1prFQ.png" /><figcaption>Opik’s Home Page</figcaption></figure><h3>Your Ground Truth Dataset</h3><p>The key to a successful evaluation is assembling a set of questions paired with their <strong>expected answers</strong>. These answers represent the <strong>“gold standard”</strong> your agent is expected to meet.</p><p>Qualities such as <strong>tone, usefulness, helpfulness, completeness, and domain- or organization-specific nuance</strong> can only be evaluated when you have clear examples of what a <em>“good”</em> answer looks like for your specific use case.</p><p>The simplest way to create a Dataset in Opik is using the UI. Just give it a name (“Aura Agent Evaluation Dataset”) and then add each question-answer pair as a Dataset item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4hudWZRbMOdvlot82Is7g.png" /></figure><p>For simplicity here’s a dataset item.</p><pre>{<br>  &quot;input&quot;: [<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;How many contracts for VerticalNet in the database?&quot;<br>    }<br>  ],<br>  &quot;expected_output&quot;: &quot;There are 5 contracts for VerticalNet in the database.&quot;,<br>}</pre><p>You’ll notice that the <strong>question (</strong>input key<strong>) </strong>follows the standard format used by LLMs to represent a sequence of interactions between a user and an assistant.</p><p>This structure allows you to evaluate your agent not only on single-turn responses, but also on the <strong>usefulness and correctness of longer, multi-turn interactions</strong>. By passing multiple conversation turns in the input, you can assess how well the agent maintains context, reasons across turns, and produces helpful answers over time.</p><p><strong>On a side note:</strong> Opik allows you to programatically create, add/remove/delete datasets and dataset items. In addition, Opik automatically versions your datasets so you keep a history of all changes made.</p><p>The remainder of this blog post, we will walkthrough the code needed to evaluate your Aura Agent with Opik.</p><h3>The Opik Evaluation Python Script</h3><p>Let’s start by retrieving your Aura Agent connectivity and OpenAI key from the environment variables.</p><pre># Neo4j Aura Agent credentials<br>CLIENT_ID = os.getenv(&quot;CLIENT_ID&quot;)<br>CLIENT_SECRET = os.getenv(&quot;CLIENT_SECRET&quot;)<br>ENDPOINT_URL = os.getenv(&quot;ENDPOINT_URL&quot;)<br><br># OpenAI key (used by Opik&#39;s LLM-based scoring metrics)<br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)</pre><p>Before sending requests to your Aura Agent endpoint, you must obtain a BEARER_TOKEN for authenticating with the Aura API. The token is typically valid for up to <strong>one hour</strong>, so best practice is to <strong>reuse it for as long as it remains valid</strong> and request a new one only when it expires.</p><pre>def get_bearer_token() -&gt; str:<br>    &quot;&quot;&quot;Get OAuth bearer token from Neo4j.&quot;&quot;&quot;<br>    response = httpx.post(<br>        &quot;https://api.neo4j.io/oauth/token&quot;,<br>        auth=(CLIENT_ID, CLIENT_SECRET),<br>        headers={&quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;},<br>        data={&quot;grant_type&quot;: &quot;client_credentials&quot;},<br>        timeout=30.0,<br>    )<br>    response.raise_for_status()<br>    return response.json().get(&quot;access_token&quot;)<br><br>BEARER_TOKEN = get_bearer_token()</pre><p>And let’s get ready to interact with Opik</p><pre>client = Opik(api_key=OPENAI_API_KEY)</pre><h3>The Evaluation — “Task Function”</h3><p>As mentioned earlier, the <strong>task function</strong> is invoked by Opik during evaluation of <strong>each item in your dataset</strong>. Its responsibility is to take a dataset item, call your Aura Agent, and return the agent’s response text.</p><p>In the excerpt below, this logic is implemented in the call_contract_agent_with_trace function.</p><pre># One thread_id per dataset item so each question maps to one Opik Thread<br>def agent_evaluation_task(x: Dict[str, Any]) -&gt; Dict[str, str]:<br>  thread_id = str(uuid.uuid4())<br>  output_text = call_contract_agent_with_trace(<br>    messages=x[&quot;input&quot;],<br>    thread_id=thread_id,<br>    client=client,<br>  )<br>  return {&quot;output&quot;: output_text}</pre><p>Note that the thread_id parameter refers to the <strong>Opik Trace</strong> concept. Each question generates an Opik thread trace, making it possible to <strong>reconstruct the full user–agent interaction</strong> for a given evaluation item.</p><p>For example, an Opik Trace could look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6NSb8R-UAvfPEzWQ3K6iQ.png" /><figcaption>Opik Thread example</figcaption></figure><p>Now, let’s go into more details about the call_contract_agent_with_trace function.</p><h3>The call_contract_agent_with_trace Function</h3><p>Here’s where the Opik evaluation and traceability magic happens!</p><p>The task function is the execution layer of the evaluation pipeline. For each dataset item, it sends a conversation to the contract agent, safely handles retries and captures a <strong>fully traceable record</strong> of the interaction — including overall execution time (latency), inputs, outputs, reasoning steps, tool calls, and token usage. The result is a single, self-contained interaction that can be analyzed in depth in Opik.</p><h4>Parsing the Agent Response (JSON)</h4><p>The process_response_content function segments the agent response from a JSON doc with a flat array into a structured list of &quot;blocks&quot; — each block containing one agent thinking segment and any tool calls that follow it.</p><p>Here’s what the agent response looks like</p><pre>{<br>  &quot;content&quot;: [<br>    {<br>      &quot;type&quot;: &quot;thinking&quot;,<br>      &quot;thinking&quot;: &quot;The user is asking about termination conditions. I need to query the knowledge graph for the Acme Corp contract...&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;tool_use&quot;,<br>      &quot;name&quot;: &quot;cypher_template_tool&quot;,<br>      &quot;input&quot;: {&quot;query&quot;: &quot;MATCH (c:Contract {name: &#39;Acme Corp&#39;})-[:HAS_CLAUSE]-&gt;(cl:Clause {type: &#39;termination&#39;}) RETURN cl.text&quot;},<br>      &quot;output&quot;: {&quot;result&quot;: &quot;...&quot;}<br>    },<br>    {<br>      &quot;type&quot;: &quot;thinking&quot;,<br>      &quot;thinking&quot;: &quot;The query returned the termination clause. It states 30 days written notice...&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;text&quot;,<br>      &quot;text&quot;: &quot;The Acme Corp contract can be terminated with 30 days written notice...&quot;<br>    }<br>  ],<br>  &quot;usage&quot;: {<br>    &quot;request_tokens&quot;: 1250,<br>    &quot;response_tokens&quot;: 340,<br>    &quot;total_tokens&quot;: 1590<br>  }<br>}</pre><p>The process_response_content turns this relatively flat agent response into a set of thinking blocks and their associated tool calls. This gives us the structure we need to build a trace hierarchy in Opik.</p><p>The processed agent answer looks like this:</p><pre>contract-agent-query<br>├── thinking-block-0<br>│   ├── input: &quot;The user is asking about termination conditions...&quot;<br>│   └── tool-call-cypher_template_tool<br>│       ├── input: {&quot;query&quot;: &quot;MATCH (c:Contract)...&quot;}<br>│       └── output: {&quot;result&quot;: &quot;...&quot;}<br>├── thinking-block-1<br>│   └── input: &quot;The query returned the termination clause...&quot;<br>└── output: &quot;The Acme Corp contract can be terminated with...&quot;</pre><h4>The Opik Trace Hierarchy</h4><p>This is where the evaluation becomes genuinely useful. A Metric tells you <em>that</em> an answer scored poorly; Opik traces tell you <em>why</em>.</p><p>For every agent call, we build the following Opik trace hierarchy:</p><ol><li><strong>Root trace</strong> — the full request-to-response cycle, with input messages, final answer, and token usage.</li><li><strong>Thinking block spans</strong> — one per reasoning segment, nested under the root.</li><li><strong>Tool call spans</strong> — one per tool invocation, nested under the thinking block that triggered it.</li></ol><p>Here’s how the <strong>root trace</strong> is created:</p><pre> trace = client.trace(<br>        name=&quot;contract-agent-query&quot;,<br>        project_name=&quot;contract-agent-eval&quot;,<br>        start_time=start_time,<br>        end_time=end_time,<br>        input={&quot;messages&quot;: messages},<br>        output={&quot;answer&quot;: extracted_text},<br>        metadata={<br>            &quot;prompt_tokens&quot;: usage.get(&quot;request_tokens&quot;, 0),<br>            &quot;completion_tokens&quot;: usage.get(&quot;response_tokens&quot;, 0),<br>            &quot;total_tokens&quot;: usage.get(&quot;total_tokens&quot;, 0),<br>        },<br>        thread_id=thread_id,<br>    )</pre><p>Then we loop through the parsed response blocks and create child Spans. Each <strong>thinking block</strong> becomes a Span, and <strong>each tool call </strong>within that block becomes a “tool-call” span nested underneath:</p><pre>for i, block in enumerate(agent_response_blocks):<br>    thinking_span = trace.span(<br>        name=f&quot;thinking-block-{i}&quot;,<br>        type=&quot;general&quot;,<br>        start_time=start_time,<br>        end_time=end_time,<br>        input={&quot;thinking&quot;: block.get(&quot;thinking&quot;, &quot;&quot;)},<br>    )<br><br>    for tool_call in block.get(&quot;tool_calls&quot;, []):<br>        thinking_span.span(<br>            name=f&quot;tool-call-{tool_call.get(&#39;tool_name&#39;, &#39;&#39;)}&quot;,<br>            type=&quot;tool&quot;,<br>            provider=&quot;neo4j&quot;,<br>            model=&quot;neo4j-aura-agent&quot;,<br>            start_time=start_time,<br>            end_time=end_time,<br>            input={&quot;input&quot;: tool_call.get(&quot;input&quot;, {})},<br>            output={&quot;output&quot;: tool_call.get(&quot;output&quot;, {})},<br>        )<br><br>    thinking_span.end()<br><br>trace.end()</pre><h3>Running the Evaluation</h3><p>With the function task and all of the traces in place, we just need to specify the Metrics to evaluate. Let’s score agent responses in terms of their Relevance, Usefulness and level of Hallucination.</p><pre>#let&#39;s evaluate the agent responses using these OOTB Metris<br>answer_relevance_metric = AnswerRelevance()<br>usefulness_metric = Usefulness()<br>hallucination_metric = Hallucination()<br><br>evaluation = evaluate(<br>    dataset=dataset,<br>    task=agent_evaluation_task,<br>    scoring_metrics=[answer_relevance_metric],<br>    experiment_config={<br>        &quot;model&quot;: ENDPOINT_URL,<br>        &quot;prompt_version&quot;: &quot;v2.1&quot;,<br>        &quot;tools&quot;: [&quot;cypher_template_tool&quot;, &quot;contract_search_tool&quot;],<br>        &quot;description&quot;: &quot;Baseline run with CUAD dataset&quot;,<br>    },<br>    nb_samples=2,  # Start small, scale up once stable<br>    prompts=[prompt],<br>    project_name=&quot;contract-agent-eval&quot;,<br>    task_threads=16,<br>)<br><br>client.flush()</pre><p>A few things to note:</p><ul><li>nb_samples controls how many dataset items to evaluate. Start with 2–3 while debugging, then remove the limit for full runs.</li><li>task_threads=16 runs evaluations in parallel. Combined with the rate limiting in the task function, this gives you concurrency without overwhelming the Agent endpoint.</li><li>experiment_config stores metadata about this specific run — the endpoint, prompt version, available tools, and a description. This becomes essential when comparing multiple experiments (more on that below).</li></ul><p>You can run the evaluation script with</p><pre>#Run the evaluation script<br>uv run python agent-eval-trace.py</pre><h3>Evaluation Results in Opik</h3><p>Head back to <strong>Opik -&gt; Experiments.</strong> Click on the most recently completed experiment. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjSD3opqQWKp7NfyXt9UKg.png" /><figcaption>Opik Experiment showing evaluation scores for relevance, usefulness and hallucinations</figcaption></figure><p>At the dataset level, you can see that the Aura agent was used to <strong>generate answers </strong>(output) for <strong>two questions</strong> in the Dataset<strong> (</strong>see input &amp; expected output<strong>)</strong>. For each question, Opik reports individual evaluation scores for <strong>relevance</strong>, <strong>usefulness</strong>, and <strong>hallucination</strong>.</p><p>In addition, Opik provides <strong>aggregated metrics at the experiment level</strong>, summarizing overall agent performance. In this case, the average usefulness score is <strong>0.6</strong>, average relevance is <strong>0.9</strong>, and the average hallucination score is <strong>0.8</strong>.</p><p>To better understand the evaluation results, let’s examine why one of the answers. We’ll use see the <strong>Opik Trace Hierarchy</strong> generated by our code.</p><h3>Opik evaluation traces for a single question</h3><p>Click on the answer to the following question</p><blockquote>Find contracts with unlimited liability and no insurance clause</blockquote><p>Opik shows the dataset item, agent response (output) and the scores for this specific question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLYGRQMwfK7P5Kxeq73RrQ.png" /><figcaption>One question with invidivual scores for each metric</figcaption></figure><p>From here, <strong>click Trace.</strong></p><p>In the left-hand pane, you can see that <strong>12 traces</strong> were generated in total. The trace hierarchy is organized into <strong>two main levels</strong>: the <strong>agent evaluation task</strong> and the <strong>metrics calculation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PV5CqlowY3Og2ihP2eJE5w.png" /></figure><p>All traces produced during agent execution appear under the <strong>agent evaluation task</strong>. In particular, the call_contract_agent_with_trace trace acts as the <strong>root trace</strong>, with the traces beneath it representing the agent’s internal activity—such as <strong>thinking blocks</strong> and <strong>tool calls</strong>—that occurred while generating the answer.</p><p>The first <strong>thinking trace</strong> confirms which tool is required to answer the question — identify_contracts_with_and_without_specific_clause_types—and shows how the agent maps the original question into the correct tool parameters: <strong>with <em>Uncapped Liability</em></strong> and <strong>without <em>Insurance</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERjbcHasp9Aumdi6AZ62mw.png" /></figure><p>Directly beneath this thinking trace, you can inspect the _record_tool_call span, which captures both the <strong>input passed to the tool</strong> and the <strong>output produced by the tool</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OESscaB2VVIWls6sQB13CQ.png" /></figure><p>The final thinking span shows the inner working of agent to produce the final answer (output) from the output of the previous tool call</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kK7YcuWmbCxCOXRjtpR1kw.png" /><figcaption>The agent reasoning before generating the final answer to the original question</figcaption></figure><p>The second main level in the hierarchy is the <strong>metrics calculation task</strong>. This section contains the traces responsible for evaluating the agent’s response against each defined quality dimension. For every answer, Opik generates separate traces to score <strong>relevance</strong>, <strong>hallucination</strong>, and <strong>usefulness</strong>, making it easy to see how each metric was computed and where a score may have been impacted.</p><p>Below, you can see one of the traces generated to score <strong>answer relevance</strong>. In the <strong>Output</strong> section, the reason field provides Opik’s explanation for why that particular relevance score was assigned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7K7RdqRlr7nu3MLXkTzNBQ.png" /></figure><p>But wait…what exactly does <strong>relevance</strong> mean when using Opik out of the box?</p><p>To answer this, you can inspect the <strong>full prompt</strong> Opik submits to OpenAI when generating the relevance score. Simply open the <strong>gpt-4o span</strong> and review its <strong>Input</strong> section to see the precise definition being applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reFDKjUFqOG2PbiFQdwm6w.png" /></figure><p>Opik ships with built-in prompts for a set of <strong>common “LLM-as-a-Judge” metrics</strong>. In addition, it provides a convenient way to define <strong>metric ensemble</strong>, allowing you to combine multiple metrics — such as <strong>Relevance</strong> and <strong>Hallucination</strong> — into a single composite score calculated from the individual metric results.</p><p>Opik also allows you to define <strong>custom LLM-as-a-Judge metrics</strong>, enabling you to score answers against <strong>domain-specific or organization-specific criteria</strong>. To do this, you simply provide a detailed evaluation prompt that includes clear examples of <strong>high-scoring</strong> and <strong>low-scoring</strong> answers.</p><h3>Comparing Two Experiments</h3><p>The real value of evaluation lies in the ability to <strong>compare agents side by side</strong> — or even different versions of the same agent — each configured slightly differently. This could include changes to the prompt, tool descriptions, or the set of tools available to the agent.</p><p>Opik makes this comparison straightforward. Simply return to your experiment page, click <strong>Compare</strong>, select another experiment, and Opik automatically surfaces the metric differences for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aw0IH04tFTDFY9QjTpKMuw.png" /><figcaption>Opik Compare Experiments</figcaption></figure><h3>Tips</h3><p>I wanted to leave you with a few tips for you to continue your Aura Agent evaluation with Opik.</p><p><strong>Start small.</strong> Use nb_samples=2 and a handful of dataset items until the pipeline runs cleanly. Scale up once you trust the plumbing.</p><p><strong>Add more metrics.</strong> Answer Relevance is a good starting point, but consider adding custom scorers — for example, a metric that checks whether the agent cited specific clause numbers, or one that verifies factual consistency against your expected outputs.</p><p><strong>Automate it.</strong> Once the pipeline is stable, run it on a schedule or as part of your CI/CD pipeline. Regression detection becomes automatic.</p><p><strong>Explore Opik’s features.</strong> prompt versioning, online agent evaluation, human feedback and many other features.</p><h3>Wrapping Up</h3><p>Evaluating an Aura Agent isn’t just about checking if the answers “look right.” With Opik, you get a single place for ground-truth datasets, repeatable experiments, per-answer scoring, and detailed traces that show you exactly what your agent thought and did for every question. When an answer is wrong, you don’t have to guess — you open the trace, find the thinking block or tool call that went off the rails.</p><p>The full evaluation script is available in the <a href="https://github.com/neo4j-product-examples/knowledge-graph-agent/tree/main/code/contract-agent-eval">repository</a> (agent-eval-trace.py). I have added instructions for you to customize it and evaluate your own Aura Agent with your own dataset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65a08787662d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neo4j/how-to-evaluate-your-neo4j-aura-agent-using-comets-opik-65a08787662d">How to Evaluate Your Neo4j Aura Agent Using Comet Opik</a> was originally published in <a href="https://medium.com/neo4j">Neo4j Developer Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphRAG in Action: From Commercial Contracts to a Dynamic Q&A Agent]]></title>
            <link>https://medium.com/data-science/graphrag-in-action-from-commercial-contracts-to-a-dynamic-q-a-agent-7d4a6caa6eb5?source=rss-a636110c8d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d4a6caa6eb5</guid>
            <category><![CDATA[graphrag]]></category>
            <category><![CDATA[semantic-kernel]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[neo4j]]></category>
            <dc:creator><![CDATA[Ed Sandoval]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 08:06:02 GMT</pubDate>
            <atom:updated>2024-11-04T08:06:02.482Z</atom:updated>
            <content:encoded><![CDATA[<h4>A question-based extraction approach</h4><p>In this blog post, we introduce an approach that leverages a Graph Retrieval Augmented Generation (GraphRAG) method — to streamline the process of ingesting commercial contract data and building a Q&amp;A Agent.</p><p>This approach diverges from traditional RAG (Retrieval-Augmented Generation) by emphasizing efficiency in data extraction, rather than breaking down and vectorizing entire documents indiscriminately, which is the predominant RAG approach.</p><p>In conventional RAG, every document is split into chunks and vectorized for retrieval, which can result in a large volume of unnecessary data being split, chunked and stored in vector indexes. Here, however, the focus is on extracting only the most relevant information from every contract for a specifc use case, Commercial Contract Review. The data is then structured into a knowledge graph, which organizes key entities and relationships, allowing for more precise graph data retrieval through Cypher queries and vector search.</p><p>By minimizing the amount of vectorized content and focusing on highly relevant knowledge extracted, this method enhances the accuracy and performance of the Q&amp;A agent, making it suitable to handle complex and domain-specific questions.</p><p>The 4-stage approach includes: targeted information extraction (LLM + Prompt) to create a knowledge graph (LLM + Neo4J) and simple set of graph data retrieval functions (Cypher, Text to Cypher, Vector Search). Finally, a Q&amp;A agent leveraging the data retrieval functions is built with (<a href="https://learn.microsoft.com/en-us/semantic-kernel/overview/">Microsoft Semantic Kernel</a>)</p><p>The diagram below illustrates the approach</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfjAK7PXH-eRRE7q7o9tVg.png" /><figcaption>The 4-stage GraphRAG approach: From question-based extraction -&gt; knowledge graph model-&gt; GraphRAG retrieval -&gt; Q&amp;A Agent. Image by Sebastian Nilsson @ Neo4J, reproduced here with permission from its author.</figcaption></figure><p>But first, for those of us not familiar with commercial law, let’s start with a brief intro to the contract review problem.</p><h3>Contract Review and Large Language Models</h3><p>Commercial contract review is a labor-intensive process involving paralegals and junior lawyers meticulously identifying critical information in a contract.</p><blockquote>“Contract review is the process of thoroughly reading a contract to understand the rights and obligations of an individual or company signing it and assess the associated impact”. <br>Hendrycks, Burns et al, NeurIPS 2021, in <a href="https://arxiv.org/pdf/2103.06268">CUAD an Expert-Annotated NLP Dataset for Legal Contract Review</a></blockquote><p>The first stage of contract review involves reviewing hundreds of pages of contracts to find the relevant clauses or obligations. Contract reviewers must identify whether relevant clauses exist, what they say if they do exist, and keep track of where they are described.</p><blockquote>For example, They must determine whether the contract is a 3-year contract or a 1-year contract. They must determine the end date of a contract. They must determine whether a clause is, say, an Anti-assignment or an Exclusivity clause…”<br>Hendrycks, Burns et al, NeurIPS 2021, in <a href="https://arxiv.org/pdf/2103.06268">CUAD an Expert-Annotated NLP Dataset for Legal Contract Review</a></blockquote><p>It’s a task that demands thoroughness but often suffers from inefficiencies but it is suitable for a Large Language Model!</p><p>Once the first stage is completed, senior law practitioners can start to examine contracts for weaknesses and risks. This is an area where a Q&amp;A agent powered by an LLM and grounded by information stored in Knowledge Graph is a perfect Copilot for a legal expert.</p><h3>A 4-Step Approach to Build a Commercial Contract Review Agent with LLMs, Function Calling &amp; GraphRAG</h3><p>The remainder of this blog will describe each of the steps in this process. Along the way, I will use code snippets to illustrate the main ideas.</p><p>The four steps are:</p><ol><li><strong>Extracting Relevant Information from Contracts (LLM + Contract)</strong></li><li><strong>Storing information extracted into a Knowledge Graph (Neo4j)</strong></li><li><strong>Developing simple KG Data Retrieval Functions (Python)</strong></li><li><strong>Building a Q&amp;A Agent handling complex questions (Semantic Kernel, LLM, Neo4j)</strong></li></ol><h3>The Dataset:</h3><p>The<a href="https://www.atticusprojectai.org/cuad"> CUAD (Contract Understanding Atticus Dataset)</a> is a CC BY 4.0 licensed and publicly available dataset of over 13,000 expert-labeled clauses across 510 legal contracts, designed to help build AI models for contract review. It covers a wide range of important legal clauses, such as confidentiality, termination, and indemnity, which are critical for contract analysis.</p><p>We will use three contracts from this dataset to showcase how our approach to effectively extract and analyze key legal information, building a knowledge graph and leveraging it for precise, complex question answering.</p><p>The three contracts combined contain a total of 95 pages.</p><h3>Step 1: Extracting Relevant Information from Contracts</h3><p>It is relatively straightforward to prompt an LLM to extract precise information from contracts and generate a JSON output, representing the relevant information from the contract.</p><p>In commercial review, a prompt can be drafted to to locate each of the critical elements mentioned above — parties, dates, clauses — and summarize them neatly in a machine-readable (JSON) file.</p><p><strong>Extraction Prompt (simplified)</strong></p><blockquote>Answer the following questions using information exclusively on this contract<br>[Contract.pdf]</blockquote><blockquote>1) What type of contract is this?<br>2) Who are the parties and their roles? Where are they incorporated? Name state and country (use ISO 3166 Country name)<br>3) What is the Agreement Date?<br>4) What is the Effective date?</blockquote><blockquote>For each of the following types of contract clauses, extract two pieces of information:<br>a) A Yes/No that indicates if you think the clause is found in this contract<br>b) A list of excerpts that indicates this clause type exists.</blockquote><blockquote>Contract Clause types: Competitive Restriction Exception, Non-Compete Clause, Exclusivity, No-Solicit Of Customers, No-Solicit Of Employees, Non-Disparagement, Termination For Convenience, Rofr/Rofo/Rofn, Change Of Control, Anti-Assignment, Uncapped Liability, Cap On Liability</blockquote><blockquote>Provide your final answer in a JSON document.</blockquote><p>Please note that the above section shows a simplified version of the extraction prompt. A full version can be <a href="https://github.com/neo4j-product-examples/graphrag-contract-review/blob/main/prompts/contract_extraction_prompt.txt">seen here</a>. You will find that the the last part of the prompt specifies the desired format of the JSON document. This is useful in ensuring a consistent JSON schema output.</p><p>This task is relatively simple in Python. The main()function below is designed to process a set of PDF contract files by extracting relevant legal information (extraction_prompt), using <strong>OpenAI gpt-4o </strong>and saving the results in JSON format.</p><pre>def main():<br>    pdf_files = [filename for filename in os.listdir(&#39;./data/input/&#39;) if filename.endswith(&#39;.pdf&#39;)]<br>    <br>    for pdf_filename in pdf_files:<br>        print(&#39;Processing &#39; + pdf_filename + &#39;...&#39;)    <br>        # Extract content from PDF using the assistant<br>        complete_response = process_pdf(&#39;./data/input/&#39; + pdf_filename)<br>        # Log the complete response to debug<br>        save_json_string_to_file(complete_response, &#39;./data/debug/complete_response_&#39; + pdf_filename + &#39;.json&#39;)<br></pre><p>The “<strong><em>process_pdf</em></strong>” function uses “<strong>OpenAI gpt-4o</strong>” to perform knowledge extraction from the contract with an “extraction prompt”.</p><pre>def process_pdf(pdf_filename):<br>    # Create OpenAI message thread<br>    thread = client.beta.threads.create()<br>    # Upload PDF file to the thread<br>    file = client.files.create(file=open(pdf_filename, &quot;rb&quot;), purpose=&quot;assistants&quot;)<br>    # Create message with contract as attachment and extraction_prompt<br>    client.beta.threads.messages.create(thread_id=thread.id,role=&quot;user&quot;,<br>        attachments=[<br>            Attachment(<br>                file_id=file.id, tools=[AttachmentToolFileSearch(type=&quot;file_search&quot;)])<br>        ],<br>        content=extraction_prompt,<br>    )<br>    # Run the message thread<br>    run = client.beta.threads.runs.create_and_poll(<br>        thread_id=thread.id, assistant_id=pdf_assistant.id, timeout=1000)<br>    # Retrieve messages<br>    messages_cursor = client.beta.threads.messages.list(thread_id=thread.id)<br>    messages = [message for message in messages_cursor]<br>    # Return last message in Thread <br>    return messages[0].content[0].text.value</pre><p>For each contract, the message returned by <strong>“process_pdf”</strong> looks like</p><pre>{<br>    &quot;agreement&quot;: {<br>        &quot;agreement_name&quot;: &quot;Marketing Affiliate Agreement&quot;,<br>        &quot;agreement_type&quot;: &quot;Marketing Affiliate Agreement&quot;,<br>        &quot;effective_date&quot;: &quot;May 8, 2014&quot;,<br>        &quot;expiration_date&quot;: &quot;December 31, 2014&quot;,<br>        &quot;renewal_term&quot;: &quot;1 year&quot;,<br>        &quot;Notice_period_to_Terminate_Renewal&quot;: &quot;30 days&quot;,<br>        &quot;parties&quot;: [<br>            {<br>                &quot;role&quot;: &quot;Company&quot;,<br>                &quot;name&quot;: &quot;Birch First Global Investments Inc.&quot;,<br>                &quot;incorporation_country&quot;: &quot;United States Virgin Islands&quot;,<br>                &quot;incorporation_state&quot;: &quot;N/A&quot;<br>            },<br>            {<br>                &quot;role&quot;: &quot;Marketing Affiliate&quot;,<br>                &quot;name&quot;: &quot;Mount Knowledge Holdings Inc.&quot;,<br>                &quot;incorporation_country&quot;: &quot;United States&quot;,<br>                &quot;incorporation_state&quot;: &quot;Nevada&quot;<br>            }<br>        ],<br>        &quot;governing_law&quot;: {<br>            &quot;country&quot;: &quot;United States&quot;,<br>            &quot;state&quot;: &quot;Nevada&quot;,<br>            &quot;most_favored_country&quot;: &quot;United States&quot;<br>        },<br>        &quot;clauses&quot;: [<br>            {<br>                &quot;clause_type&quot;: &quot;Competitive Restriction Exception&quot;,<br>                &quot;exists&quot;: false,<br>                &quot;excerpts&quot;: []<br>            },<br>            {<br>                &quot;clause_type&quot;: &quot;Exclusivity&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;Company hereby grants to MA the right to advertise, market and sell to corporate users, government agencies and educational facilities for their own internal purposes only, not for remarketing or redistribution.&quot;<br>                ]<br>            },<br>            {<br>                &quot;clause_type&quot;: &quot;Non-Disparagement&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;MA agrees to conduct business in a manner that reflects favorably at all times on the Technology sold and the good name, goodwill and reputation of Company.&quot;<br>                ]<br>            },<br>            {<br>                &quot;clause_type&quot;: &quot;Termination For Convenience&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;This Agreement may be terminated by either party at the expiration of its term or any renewal term upon thirty (30) days written notice to the other party.&quot;<br>                ]<br>            },<br>            {<br>                &quot;clause_type&quot;: &quot;Anti-Assignment&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;MA may not assign, sell, lease or otherwise transfer in whole or in part any of the rights granted pursuant to this Agreement without prior written approval of Company.&quot;<br>                ]<br>            },<br>            <br>            {<br>                &quot;clause_type&quot;: &quot;Price Restrictions&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;Company reserves the right to change its prices and/or fees, from time to time, in its sole and absolute discretion.&quot;<br>                ]<br>            },<br>            {<br>                &quot;clause_type&quot;: &quot;Minimum Commitment&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;MA commits to purchase a minimum of 100 Units in aggregate within the Territory within the first six months of term of this Agreement.&quot;<br>                ]<br>            },<br>            <br>            {<br>                &quot;clause_type&quot;: &quot;IP Ownership Assignment&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;Title to the Technology and all copyrights in Technology shall remain with Company and/or its Affiliates.&quot;<br>                ]<br>            },<br>            <br>            {<br>                &quot;clause_type&quot;: &quot;License grant&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;Company hereby grants to MA the right to advertise, market and sell the Technology listed in Schedule A of this Agreement.&quot;<br>                ]<br>            },<br>            {<br>                &quot;clause_type&quot;: &quot;Non-Transferable License&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;MA acknowledges that MA and its Clients receive no title to the Technology contained on the Technology.&quot;<br>                ]<br>            },<br>            {<br>                &quot;clause_type&quot;: &quot;Cap On Liability&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;In no event shall Company be liable to MA, its Clients, or any third party for any tort or contract damages or indirect, special, general, incidental or consequential damages.&quot;<br>                ]<br>            },<br>            <br>            {<br>                &quot;clause_type&quot;: &quot;Warranty Duration&quot;,<br>                &quot;exists&quot;: true,<br>                &quot;excerpts&quot;: [<br>                    &quot;Company&#39;s sole and exclusive liability for the warranty provided shall be to correct the Technology to operate in substantial accordance with its then current specifications.&quot;<br>                ]<br>            }<br>            <br>            <br>        ]<br>    }<br>}</pre><h3>Step 2: Creating a Knowledge Graph</h3><p>With each contract now as a JSON file, the next step is to create a Knowledge Graph in Neo4J.</p><p>At this point is useful to spend some time designing the data model. You need to consider some key questions:</p><ul><li>What do nodes and relationships in this graph represent?</li><li>What are the main properties for each node and relationship?,</li><li>Should there be any properties indexed?</li><li>Which properties need vector embeddings to enable semantic similarity search on them?</li></ul><p>In our case, a suitable design (schema) includes the main entities: Agreements (contracts), their clauses, the organizations who are parties to the agreement and the relationships amongst them.</p><p>A visual representation of the schema is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pLCoA53cwIpGtm-YLwY_g.png" /><figcaption>Image by the Author</figcaption></figure><pre><br>Node properties:<br>Agreement {agreement_type: STRING, contract_id: INTEGER,<br>          effective_date: STRING, expiration_date: STRING,<br>          renewal_term: STRING, name: STRING}<br>ContractClause {name: STRING, type: STRING}<br>ClauseType {name: STRING}<br>Country {name: STRING}<br>Excerpt {text: STRING}<br>Organization {name: STRING}<br><br>Relationship properties:<br>IS_PARTY_TO {role: STRING}<br>GOVERNED_BY_LAW {state: STRING}<br>HAS_CLAUSE {type: STRING}<br>INCORPORATED_IN {state: STRING}<br><br></pre><p>Only the “Excerpts” — the short text pieces identified by the LLM in Step 1 — require text embeddings. This approach dramatically reduces the number of vectors and the size of the vector index needed to represent each contract, making the process more efficient and scalable.</p><p>A simplified version of a python script loading each JSON into a Knowledge Graph with the above schema looks like</p><pre>NEO4J_URI=os.getenv(&#39;NEO4J_URI&#39;, &#39;bolt://localhost:7687&#39;)<br>NEO4J_USER=os.getenv(&#39;NEO4J_USERNAME&#39;, &#39;neo4j&#39;)<br>NEO4J_PASSWORD=os.getenv(&#39;NEO4J_PASSWORD&#39;)<br>OPENAI_API_KEY = os.getenv(&#39;OPENAI_API_KEY&#39;)<br>JSON_CONTRACT_FOLDER = &#39;./data/output/&#39;<br><br>driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))<br><br>contract_id = 1<br><br>json_contracts = [filename for filename in os.listdir(JSON_CONTRACT_FOLDER) if filename.endswith(&#39;.json&#39;)]<br>for json_contract in json_contracts:<br>  with open(JSON_CONTRACT_FOLDER + json_contract,&#39;r&#39;) as file:<br>    json_string = file.read()<br>    json_data = json.loads(json_string)<br>    agreement = json_data[&#39;agreement&#39;]<br>    agreement[&#39;contract_id&#39;] = contract_id<br>    driver.execute_query(CREATE_GRAPH_STATEMENT,  data=json_data)<br>    contract_id+=1<br><br>create_full_text_indices(driver)<br>driver.execute_query(CREATE_VECTOR_INDEX_STATEMENT)<br>print (&quot;Generating Embeddings for Contract Excerpts...&quot;)<br>driver.execute_query(EMBEDDINGS_STATEMENT, token = OPENAI_API_KEY)</pre><p>Here the “<strong>CREATE_GRAPH_STATEMENT</strong>” is the only “complex” piece. It is a CYPHER statement that maps the Contract (JSON) into the nodes and relationships in the Knowledge Graph.</p><p>The full Cypher statement is below</p><pre>CREATE_GRAPH_STATEMENT = &quot;&quot;&quot;<br>WITH $data AS data<br>WITH data.agreement as a<br><br>MERGE (agreement:Agreement {contract_id: a.contract_id})<br>ON CREATE SET <br>  agreement.contract_id  = a.contract_id,<br>  agreement.name = a.agreement_name,<br>  agreement.effective_date = a.effective_date,<br>  agreement.expiration_date = a.expiration_date,<br>  agreement.agreement_type = a.agreement_type,<br>  agreement.renewal_term = a.renewal_term,<br>  agreement.most_favored_country = a.governing_law.most_favored_country<br>  //agreement.Notice_period_to_Terminate_Renewal = a.Notice_period_to_Terminate_Renewal<br><br>MERGE (gl_country:Country {name: a.governing_law.country})<br>MERGE (agreement)-[gbl:GOVERNED_BY_LAW]-&gt;(gl_country)<br>SET gbl.state = a.governing_law.state<br><br><br>FOREACH (party IN a.parties |<br>  // todo proper global id for the party<br>  MERGE (p:Organization {name: party.name})<br>  MERGE (p)-[ipt:IS_PARTY_TO]-&gt;(agreement)<br>  SET ipt.role = party.role<br>  MERGE (country_of_incorporation:Country {name: party.incorporation_country})<br>  MERGE (p)-[incorporated:INCORPORATED_IN]-&gt;(country_of_incorporation)<br>  SET incorporated.state = party.incorporation_state<br>)<br><br>WITH a, agreement, [clause IN a.clauses WHERE clause.exists = true] AS valid_clauses<br>FOREACH (clause IN valid_clauses |<br>  CREATE (cl:ContractClause {type: clause.clause_type})<br>  MERGE (agreement)-[clt:HAS_CLAUSE]-&gt;(cl)<br>  SET clt.type = clause.clause_type<br>  // ON CREATE SET c.excerpts = clause.excerpts<br>  FOREACH (excerpt IN clause.excerpts |<br>    MERGE (cl)-[:HAS_EXCERPT]-&gt;(e:Excerpt {text: excerpt})<br>  )<br>  //link clauses to a Clause Type label<br>  MERGE (clType:ClauseType{name: clause.clause_type})<br>  MERGE (cl)-[:HAS_TYPE]-&gt;(clType)<br>)&quot;&quot;&quot;</pre><p>Here’s a breakdown of what the statement does:</p><h4>Data Binding</h4><pre>WITH $data AS data<br>WITH data.agreement as a</pre><ul><li>$data is the input data being passed into the query in JSON format. It contains information about an agreement (contract).</li><li>The second line assigns data.agreement to the alias a, so the contract details can be referenced in the subsequent query.</li></ul><h4><strong>Upsert the Agreement Node</strong></h4><pre>MERGE (agreement:Agreement {contract_id: a.contract_id})<br>ON CREATE SET <br>  agreement.name = a.agreement_name,<br>  agreement.effective_date = a.effective_date,<br>  agreement.expiration_date = a.expiration_date,<br>  agreement.agreement_type = a.agreement_type,<br>  agreement.renewal_term = a.renewal_term,<br>  agreement.most_favored_country = a.governing_law.most_favored_country</pre><ul><li>MERGE attempts to find an existing Agreement node with the specified contract_id. If no such node exists, it creates one.</li><li>The ON CREATE SET clause sets various properties on the newly created Agreement node, such as contract_id, agreement_name, effective_date, and other agreement-related fields from the JSON input.</li></ul><h4><strong>Create Governing Law Relationship</strong></h4><pre>MERGE (gl_country:Country {name: a.governing_law.country})<br>MERGE (agreement)-[gbl:GOVERNED_BY_LAW]-&gt;(gl_country)<br>SET gbl.state = a.governing_law.state</pre><ul><li>This creates or merges a Country node for the governing law country associated with the agreement.</li><li>Then, it creates or merges a relationship GOVERNED_BY_LAW between the Agreement and Country.</li><li>It also sets the state property of the GOVERNED_BY_LAW relationship</li></ul><h4><strong>Create Party and Incorporation Relationships</strong></h4><pre>FOREACH (party IN a.parties |<br>  MERGE (p:Organization {name: party.name})<br>  MERGE (p)-[ipt:IS_PARTY_TO]-&gt;(agreement)<br>  SET ipt.role = party.role<br>  MERGE (country_of_incorporation:Country {name: party.incorporation_country})<br>  MERGE (p)-[incorporated:INCORPORATED_IN]-&gt;(country_of_incorporation)<br>  SET incorporated.state = party.incorporation_state<br>)</pre><p>For each party in the contract (a.parties), it:</p><ul><li>Upserts (Merge) an Organization node for the party.</li><li>Creates an IS_PARTY_TO relationship between the Organization and the Agreement, setting the role of the party (e.g., buyer, seller).</li><li>Merges a Country node for the country in which the organization is incorporated.</li><li>Creates an INCORPORATED_IN relationship between the organization and the incorporation country, and sets the state where the organization is incorporated</li></ul><h4><strong>Create Contract Clauses and Excerpts</strong></h4><pre>WITH a, agreement, [clause IN a.clauses WHERE clause.exists = true] AS valid_clauses<br>FOREACH (clause IN valid_clauses |<br>  CREATE (cl:ContractClause {type: clause.clause_type})<br>  MERGE (agreement)-[clt:HAS_CLAUSE]-&gt;(cl)<br>  SET clt.type = clause.clause_type<br>  FOREACH (excerpt IN clause.excerpts |<br>    MERGE (cl)-[:HAS_EXCERPT]-&gt;(e:Excerpt {text: excerpt})<br>  )<br>  MERGE (clType:ClauseType{name: clause.clause_type})<br>  MERGE (cl)-[:HAS_TYPE]-&gt;(clType)<br>)</pre><ul><li>This part first filters the list of clauses (a.clauses) to include only those where clause.exists = true (i.e., clauses with excerpts identified by the LLM in Step 1)</li><li>For each clause:</li><li>It creates a ContractClause node with a name and type corresponding to the clause type.</li><li>A HAS_CLAUSE relationship is established between the Agreement and the ContractClause.</li><li>For each excerpt associated with the clause, it creates an Excerpt node and links it to the ContractClause using a HAS_EXCERPT relationship.</li><li>Finally, a ClauseType node is created (or merged) for the type of the clause, and the ContractClause is linked to the ClauseType using a HAS_TYPE relationship.</li></ul><p>Once the import script runs, a single contract can be visualized in Neo4J as a Knowledge Graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5aJtu_RLBszOYCtMG2tbw.png" /><figcaption>A Knowledge Graph representation of a single Contract: Parties (organizations) in green, Contract Clauses in blue, Excerpts in light brown, Countries in orange. Image by the Author</figcaption></figure><p>The three contracts in the knowledge graph required only a small graph (under 100 nodes and less than 200 relationships). Most importantly, only 40–50 vector embeddings for the Excerpts are needed. This knowledge graph with a small number of vectors can now be used to power a reasonably powerful Q&amp;A agent.</p><h3>Step 3: Developing data retrieval functions for GraphRAG</h3><p>With the contracts now structured in a Knowledge Graph, the next step involves creating a small set of graph data retrieval functions. These functions serve as the core building blocks, allowing us to develop a Q&amp;A agent in step 4.</p><p>Let’s define a few basic data retrieval functions:</p><ol><li>Retrieve basic details about a contract (given a contract ID)</li><li>Find contracts involving a specific organization (given a partial organization name)</li><li>Find contracts that <strong>DO NOT </strong>contain a particular clause type</li><li>Find contracts contain a specific type of clause</li><li>Find contracts based on the semantic similarity with the text (Excerpt) in a clause (e.g., contracts mentioning the use of “prohibited items”)</li><li>Run a natural language query against all contracts in the database. For example, an aggregation query that counts “how many contracts meet certain conditions”.</li></ol><p>In step 4, we will build a Q&amp;A using the <a href="https://learn.microsoft.com/en-us/semantic-kernel/overview/">Microsoft Semantic Kernel library</a>. This library simplifies the agent building process. It allows developers to define the functions and tools that an Agent will have at its disposal to answer a question.</p><p>In order to simplify the integration between Neo4J and the Semantic Kernel library, let’s define a ContractPlugin that defines the “signature” of each our data retrieval functions. Note the @kernel_function decorator for each of the functions and also the type information and description provided for each function.</p><p>Semantic Kernel uses the concept of a “<strong>Plugin</strong>” class to encapsulate a group of functions available to an Agent. It will use the decorated functions, type information and documentation to inform the LLM function calling capabilities about functions available.</p><pre>from typing import List, Optional, Annotated<br>from AgreementSchema import Agreement, ClauseType<br>from semantic_kernel.functions import kernel_function<br>from ContractService import  ContractSearchService<br><br>class ContractPlugin:<br>    def __init__(self, contract_search_service: ContractSearchService ):<br>        self.contract_search_service = contract_search_service<br>    <br>    @kernel_function<br>    async def get_contract(self, contract_id: int) -&gt; Annotated[Agreement, &quot;A contract&quot;]:<br>        &quot;&quot;&quot;Gets details about a contract with the given id.&quot;&quot;&quot;<br>        return await self.contract_search_service.get_contract(contract_id)<br><br>    @kernel_function<br>    async def get_contracts(self, organization_name: str) -&gt; Annotated[List[Agreement], &quot;A list of contracts&quot;]:<br>        &quot;&quot;&quot;Gets basic details about all contracts where one of the parties has a name similar to the given organization name.&quot;&quot;&quot;<br>        return await self.contract_search_service.get_contracts(organization_name)<br>    <br>    @kernel_function<br>    async def get_contracts_without_clause(self, clause_type: ClauseType) -&gt; Annotated[List[Agreement], &quot;A list of contracts&quot;]:<br>        &quot;&quot;&quot;Gets basic details from contracts without a clause of the given type.&quot;&quot;&quot;<br>        return await self.contract_search_service.get_contracts_without_clause(clause_type=clause_type)<br>    <br>    @kernel_function<br>    async def get_contracts_with_clause_type(self, clause_type: ClauseType) -&gt; Annotated[List[Agreement], &quot;A list of contracts&quot;]:<br>        &quot;&quot;&quot;Gets basic details from contracts with a clause of the given type.&quot;&quot;&quot;<br>        return await self.contract_search_service.get_contracts_with_clause_type(clause_type=clause_type)<br><br>    @kernel_function<br>    async def get_contracts_similar_text(self, clause_text: str) -&gt; Annotated[List[Agreement], &quot;A list of contracts with similar text in one of their clauses&quot;]:<br>        &quot;&quot;&quot;Gets basic details from contracts having semantically similar text in one of their clauses to the to the &#39;clause_text&#39; provided.&quot;&quot;&quot;<br>        return await self.contract_search_service.get_contracts_similar_text(clause_text=clause_text)<br>    <br>    @kernel_function<br>    async def answer_aggregation_question(self, user_question: str) -&gt; Annotated[str, &quot;An answer to user_question&quot;]:<br>        &quot;&quot;&quot;Answer obtained by turning user_question into a CYPHER query&quot;&quot;&quot;<br>        return await self.contract_search_service.answer_aggregation_question(user_question=user_question)</pre><p>I would recommend exploring the <a href="https://github.com/neo4j-product-examples/graphrag-contract-review/blob/main/ContractService.py">“ContractService”</a> class that contains the implementations of each of the above functions. Each function exercises a a different data retrieval technique.</p><p>Let’s walk through the implementation of some of these functions as they showcase different GraphRAG data retrieval techniques / patterns</p><h4>Get Contract (from contract ID) — A Cypher-based retrieval function</h4><p>The get_contract(self, contract_id: int), is an asynchronous method designed to retrieve details about a specific contract (Agreement) from a Neo4J database using a Cypher query. The function returns an Agreement object populated with information about the agreement, clauses, parties, and their relationships.</p><p>Here’s the implementation of this function</p><pre>async def get_contract(self, contract_id: int) -&gt; Agreement:<br>        <br>        GET_CONTRACT_BY_ID_QUERY = &quot;&quot;&quot;<br>            MATCH (a:Agreement {contract_id: $contract_id})-[:HAS_CLAUSE]-&gt;(clause:ContractClause)<br>            WITH a, collect(clause) as clauses<br>            MATCH (country:Country)-[i:INCORPORATED_IN]-(p:Organization)-[r:IS_PARTY_TO]-(a)<br>            WITH a, clauses, collect(p) as parties, collect(country) as countries, collect(r) as roles, collect(i) as states<br>            RETURN a as agreement, clauses, parties, countries, roles, states<br>        &quot;&quot;&quot;<br>        <br>        agreement_node = {}<br>        <br>        records, _, _  = self._driver.execute_query(GET_CONTRACT_BY_ID_QUERY,{&#39;contract_id&#39;:contract_id})<br><br>        if (len(records)==1):<br>            agreement_node =    records[0].get(&#39;agreement&#39;)<br>            party_list =        records[0].get(&#39;parties&#39;)<br>            role_list =         records[0].get(&#39;roles&#39;)<br>            country_list =      records[0].get(&#39;countries&#39;)<br>            state_list =        records[0].get(&#39;states&#39;)<br>            clause_list =       records[0].get(&#39;clauses&#39;)<br>        <br>        return await self._get_agreement(<br>            agreement_node, format=&quot;long&quot;,<br>            party_list=party_list, role_list=role_list,<br>            country_list=country_list,state_list=state_list,<br>            clause_list=clause_list<br>        )</pre><p>The most important component is the The Cypher query in <strong>GET_CONTRACT_BY_ID_QUERY</strong> This query is executed using <strong>contract_id</strong> supplied as input parameter. The output is the matching Agreement, its clauses and parties involved (each party has a role and country/state of incorporation)</p><p>The data is then passed to an utility function _get_agreementwhich simply maps the data to an “Agreement”. The agreement is a TypedDict defined as</p><pre>class Agreement(TypedDict):  <br>    contract_id: int<br>    agreement_name: str<br>    agreement_type: str<br>    effective_date: str<br>    expiration_date: str<br>    renewal_term: str<br>    notice_period_to_terminate_Renewal: str<br>    parties: List[Party]<br>    clauses: List[ContractClause]</pre><h4>Get Contracts WITHOUT a Clause type — Another Cypher retrieval function</h4><p>This function illustrate a powerful feature of a knowledge graph, which is to test for the absence of a relationship.</p><p>The get_contracts_without_clause() function retrieves all contracts (Agreements) from the Neo4J database that <strong>do not</strong> contain a specific type of clause. The function takes a ClauseType as input and returns a list of Agreement objects that match the condition.</p><p>This type of data retrieval information can’t be easily implemented with vector search. The full implementation follows</p><pre>async def get_contracts_without_clause(self, clause_type: ClauseType) -&gt; List[Agreement]:<br>        GET_CONTRACT_WITHOUT_CLAUSE_TYPE_QUERY = &quot;&quot;&quot;<br>            MATCH (a:Agreement)<br>            OPTIONAL MATCH (a)-[:HAS_CLAUSE]-&gt;(cc:ContractClause {type: $clause_type})<br>            WITH a,cc<br>            WHERE cc is NULL<br>            WITH a<br>            MATCH (country:Country)-[i:INCORPORATED_IN]-(p:Organization)-[r:IS_PARTY_TO]-(a)<br>            RETURN a as agreement, collect(p) as parties, collect(r) as roles, collect(country) as countries, collect(i) as states<br>        &quot;&quot;&quot;<br>       <br>        #run the Cypher query<br>        records, _ , _ = self._driver.execute_query(GET_CONTRACT_WITHOUT_CLAUSE_TYPE_QUERY,{&#39;clause_type&#39;:clause_type.value})<br><br>        all_agreements = []<br>        for row in records:<br>            agreement_node =  row[&#39;agreement&#39;]<br>            party_list =  row[&#39;parties&#39;]<br>            role_list =  row[&#39;roles&#39;]<br>            country_list = row[&#39;countries&#39;]<br>            state_list = row[&#39;states&#39;]<br>            agreement : Agreement = await self._get_agreement(<br>                format=&quot;short&quot;,<br>                agreement_node=agreement_node,<br>                party_list=party_list,<br>                role_list=role_list,<br>                country_list=country_list,<br>                state_list=state_list<br>            )<br>            all_agreements.append(agreement)<br>        return all_agreements</pre><p>Once again, the format is similar to the previous function. A Cypher query,<strong>GET_CONTRACTS_WITHOUT_CLAUSE_TYPE_QUERY</strong> , defines the nodes and relationship patterns to be matched. It performs an <strong>optional match</strong> to filters out contracts that do contain a clause type, and collects related data about the agreement, such as the involved parties and their details.</p><p>The function then constructs and returns a list of Agreement objects, which encapsulate all the relevant information for each matching agreement.</p><h4>Get Contract with Semantically Similar Text — A Vector-Search + Graph data retrieval function</h4><p>The get_contracts_similar_text() function is designed to find agreements (contracts) that contain clauses with text similar to a provided clause_text. It uses semantic vector search to identify related Excerpts and then traverses the graph to return information about the corresponding agreements and clauses, where those excerpts came from.</p><p>This function leverages a vector index defined on the “text” property of each Excerpt. It uses the recently released <a href="https://neo4j.com/blog/graphrag-python-package/">Neo4J GraphRAG package</a> to simplify the Cypher code needed to run semantic search + Graph traversal code.</p><pre>async def get_contracts_similar_text(self, clause_text: str) -&gt; List[Agreement]:<br><br>        #Cypher to traverse from the semantically similar excerpts back to the agreement<br>        EXCERPT_TO_AGREEMENT_TRAVERSAL_QUERY=&quot;&quot;&quot;<br>            MATCH (a:Agreement)-[:HAS_CLAUSE]-&gt;(cc:ContractClause)-[:HAS_EXCERPT]-(node) <br>            RETURN a.name as agreement_name, a.contract_id as contract_id, cc.type as clause_type, node.text as excerpt<br>        &quot;&quot;&quot;<br>        <br>        #Set up vector Cypher retriever<br>        retriever = VectorCypherRetriever(<br>            driver= self._driver,  <br>            index_name=&quot;excerpt_embedding&quot;,<br>            embedder=self._openai_embedder, <br>            retrieval_query=EXCERPT_TO_AGREEMENT_TRAVERSAL_QUERY,<br>            result_formatter=my_vector_search_excerpt_record_formatter<br>        )<br>        <br>        # run vector search query on excerpts and get results containing the relevant agreement and clause <br>        retriever_result = retriever.search(query_text=clause_text, top_k=3)<br><br>        #set up List of Agreements (with partial data) to be returned<br>        agreements = []<br>        for item in retriever_result.items:<br>            //extract information from returned items and append agreement to results<br>            // full code not shown here but available on the Github repo<br>            <br><br>        return agreements</pre><p>Let’s go over the main components of this data retrieval function</p><ul><li>The Neo4j GraphRAG <strong>VectorCypherRetriever </strong>allows a developer to perform semantic similarity on a vector index. In our case, for each semantically similar Excerpt “node” found, an additional Cypher expression is used to fetch additional nodes in the graph related to the node.</li><li>The parameters of the <strong>VectorCypherRetriever are </strong>straightforward. The index_name is the vector index on which to run semantic similarity. The embedder generates a vector embedding for a piece of text. The driver is just an instance of a Neo4j Python driver. The retrieval_query specify the additional nodes and relationships connected with ever “Excerpt” node identified by semantic similarity</li><li>The EXCERPT_TO_AGREEMENT_TRAVERSAL_QUERY<br>specifies the additional nodes to be retrieved. In this case, for every Excerpt, we are retrieving its related Contract Clause and corresponding Agreement</li></ul><pre>EXCERPT_TO_AGREEMENT_TRAVERSAL_QUERY=&quot;&quot;&quot;<br>  MATCH (a:Agreement)-[:HAS_CLAUSE]-&gt;(cc:ContractClause)-[:HAS_EXCERPT]-(node) <br>  RETURN a.name as agreement_name, a.contract_id as contract_id, cc.type as clause_type, node.text as excerpt<br>&quot;&quot;&quot;</pre><h4>Run a Natural Language Query — A Text 2Cypher data retrieval function</h4><p>The answer_aggregation_question() function leverages Neo4j GraphRAG package “Text2CypherRetriever” to answer a question in natural language. The Text2CypherRetriever uses an LLM to turn the user question into a Cypher query and runs it against the Neo4j database.</p><p>The function leverages <strong>OpenAI gpt-4o</strong> to generate the required Cypher query. Let’s walk through the main components of this data retrieval function.</p><pre> async def answer_aggregation_question(self, user_question) -&gt; str:<br>        answer = &quot;&quot;<br><br><br>        NEO4J_SCHEMA = &quot;&quot;&quot;<br>            omitted for brevity (see below for the full value)<br>        &quot;&quot;&quot;<br><br>        # Initialize the retriever<br>        retriever = Text2CypherRetriever(<br>            driver=self._driver,<br>            llm=self._llm,<br>            neo4j_schema=NEO4J_SCHEMA<br>        )<br><br>        # Generate a Cypher query using the LLM, send it to the Neo4j database, and return the results<br>        retriever_result = retriever.search(query_text=user_question)<br><br>        for item in retriever_result.items:<br>            content = str(item.content)<br>            if content:<br>                answer += content + &#39;\n\n&#39;<br><br>        return answer</pre><p>This function leverages Neo4j GraphRAG package “<strong>Text2CypherRetriever</strong>”. It uses an LLM, in this case OpenAI LLM is used to turn a user question (natural language) into a Cypher query that is executed against the database. The result of this query is returned.</p><p>A key element to ensure that the LLM generates a query that uses the nodes, relationships and properties defined in the database is to provide the LLM with a text description of the schema.</p><p>In our case, we used the following representation of the data model is sufficient.</p><pre>NEO4J_SCHEMA = &quot;&quot;&quot;<br>Node properties:<br>Agreement {agreement_type: STRING, contract_id: INTEGER,effective_date: STRING,renewal_term: STRING, name: STRING}<br>ContractClause {name: STRING, type: STRING}<br>ClauseType {name: STRING}<br>Country {name: STRING}<br>Excerpt {text: STRING}<br>Organization {name: STRING}<br><br>Relationship properties:<br>IS_PARTY_TO {role: STRING}<br>GOVERNED_BY_LAW {state: STRING}<br>HAS_CLAUSE {type: STRING}<br>INCORPORATED_IN {state: STRING}<br><br>The relationships:<br>(:Agreement)-[:HAS_CLAUSE]-&gt;(:ContractClause)<br>(:ContractClause)-[:HAS_EXCERPT]-&gt;(:Excerpt)<br>(:ContractClause)-[:HAS_TYPE]-&gt;(:ClauseType)<br>(:Agreement)-[:GOVERNED_BY_LAW]-&gt;(:Country)<br>(:Organization)-[:IS_PARTY_TO]-&gt;(:Agreement)<br>(:Organization)-[:INCORPORATED_IN]-&gt;(:Country)<br>  &quot;&quot;&quot;</pre><h3>Step 4: Building a Q&amp;A Agent</h3><p>Armed with our Knowledge Graph data retrieval functions, we are ready to build an agent grounded by GraphRAG :-)</p><p>Let’s sets up a chatbot agent capable of answering user queries about contracts using a combination of OpenAI’s <strong>gpt-4o</strong> model, our data retrieval functions and a Neo4j-powered knowledge graph.</p><p>We will use Microsoft <strong>Semantic Kernel, a framework that </strong>allows developers to integrate LLM function calling with existing APIs and data retrieval functions</p><p>The framework uses a concept called <strong>Plugins</strong> to represent specific functionality that the kernel can perform. In our case, all of our data retrieval functions defined in the “ContractPlugin” can be used by the LLM to answer the question.</p><p>The framework uses the concept of <strong>Memory</strong> to keep all interactions between user and agent, as well as functions executed and data retrieved.</p><p>A extremely simple Terminal-based agent can be implemented with a few lines of code. The snippet below shows the main parts of the agent (imports and environment vars removed).</p><pre>logging.basicConfig(level=logging.INFO)<br><br># Initialize the kernel<br>kernel = Kernel()<br><br># Add the Contract Search plugin to the kernel<br>contract_search_neo4j = ContractSearchService(NEO4J_URI,NEO4J_USER,NEO4J_PASSWORD)<br>kernel.add_plugin(ContractPlugin(contract_search_service=contract_search_neo4j),plugin_name=&quot;contract_search&quot;)<br><br># Add the OpenAI chat completion service to the Kernel<br>kernel.add_service(OpenAIChatCompletion(ai_model_id=&quot;gpt-4o&quot;,api_key=OPENAI_KEY, service_id=service_id))<br><br># Enable automatic function calling<br>settings: OpenAIChatPromptExecutionSettings = kernel.get_prompt_execution_settings_from_service_id(service_id=service_id)<br>settings.function_choice_behavior = FunctionChoiceBehavior.Auto(filters={&quot;included_plugins&quot;: [&quot;contract_search&quot;]})<br><br># Create a history of the conversation<br>history = ChatHistory()<br><br>async def basic_agent() :<br>    userInput = None<br>    while True:<br>        # Collect user input<br>        userInput = input(&quot;User &gt; &quot;)<br><br>        # Terminate the loop if the user says &quot;exit&quot;<br>        if userInput == &quot;exit&quot;:<br>            break<br><br>        # Add user input to the history<br>        history.add_user_message(userInput)<br><br>        # 3. Get the response from the AI with automatic function calling<br>        chat_completion : OpenAIChatCompletion = kernel.get_service(type=ChatCompletionClientBase)<br>        result = (await chat_completion.get_chat_message_contents(<br>            chat_history=history,<br>            settings=settings,<br>            kernel=kernel,<br>            arguments=KernelArguments(),<br>        ))[0]<br><br>        # Print the results<br>        print(&quot;Assistant &gt; &quot; + str(result))<br><br>        # Add the message from the agent to the chat history<br>        history.add_message(result)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(basic_agent())</pre><h3>Let ask our agent some non-trivial questions</h3><blockquote><strong>1. Find me contracts with Price Restrictions but no insurance clauses</strong></blockquote><pre>Assistant &gt; I found the following contract that contains a Price Restrictions clause but does not contain an Insurance clause:<br><br>- **Name:** Birch First Global Investments Inc. and Mount Knowledge Holdings Inc. MARKETING AFFILIATE AGREEMENT<br>- **Agreement Type:** MARKETING AFFILIATE AGREEMENT<br>- **Parties:**<br>  - **MOUNT KNOWLEDGE HOLDINGS INC.** (Marketing Affiliate), incorporated in Nevada, USA<br>  - **BIRCH FIRST GLOBAL INVESTMENTS INC.** (Company), incorporated in the Virgin Islands (VIR)<br><br>Would you like to know more details about this contract?</pre><p>Here, The Semantic Agent planner has reviewed the available functions in the Kernel and determined that answering this question requires invoking two functions that, on their own, won’t provide the complete answer.</p><p>First, it executes the <strong>“Get Contracts with [Price Restriction] Clauses”</strong> function, followed by the <strong>“Get Contracts WITHOUT [Insurance] Clauses”</strong> function. The planner then combines the results from both functions to identify the intersection, ultimately arriving at the correct answer.</p><p>If you look at the debugging information, you can confirm the sequence of calls performed by the LLM, along with information on the number of tokens consumed by the call. Notice the calls with the 2 data retrieval functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmxOcKa8ORlFlZRMyytRtQ.png" /></figure><blockquote><strong>2. Yes, please. Provide more details</strong></blockquote><pre>Assistant &gt; Here are the detailed information about the contract:<br><br>### Contract Details:<br>- **Name:** Birch First Global Investments Inc. and Mount Knowledge Holdings Inc. MARKETING AFFILIATE AGREEMENT<br>- **Agreement Type:** MARKETING AFFILIATE AGREEMENT<br>- **Expiration Date:** December 31, 2014<br>- **Renewal Term:** One (1) year<br><br>### Parties Involved:<br>1. **MOUNT KNOWLEDGE HOLDINGS INC.** <br>   - **Role:** Marketing Affiliate<br>   - **Incorporation Country:** USA<br>   - **Incorporation State:** Nevada<br>2. **BIRCH FIRST GLOBAL INVESTMENTS INC.**<br>   - **Role:** Company<br>   - **Incorporation Country:** Virgin Islands (VIR)<br><br>### Clauses Included:<br>- No-Solicit Of Employees<br>- Third Party Beneficiary<br>- Price Restrictions<br>- Affiliate License-Licensee<br>- Affiliate License-Licensor<br>- Cap On Liability<br>- Audit Rights<br>- Warranty Duration<br>- Post-Termination Services<br>- Non-Transferable License<br>- License grant<br>- IP Ownership Assignment<br>- Minimum Commitment<br>- Anti-Assignment<br>- Non-Disparagement<br><br>### Clauses Not Included:<br>- Insurance<br><br>Is there anything specific you would like to know or any particular clause details you are interested in?</pre><p>In this case, behind the scenes, the LLM used the <strong>“Find Contract by ID”</strong>. You may have noticed that the output shown to the user did not include the id of the contract. However, the Semantic Kernel stored all information returned from the functions from previous calls in the conversation memory!</p><p>This powerful combination of having the agent decide which function(s) to call, the use of memory and the automatic marshalling of the user queries into function calls with the right parameters explain the <strong>“Magic”</strong> behind an agent built with Semantic Kernel!</p><blockquote><strong>3. Does any contract mention the ability to make price changes from time to time</strong></blockquote><pre>Assistant &gt; Yes, there is a contract that mentions <br>the ability to make price changes from time to time. <br>Here is the relevant excerpt:<br><br>1. **Birch First Global Investments Inc. and Mount Knowledge Holdings Inc. MARKETING AFFILIATE AGREEMENT**<br>   - **Contract ID:** 1<br>   - **Clause Type:** Price Restrictions<br>   - **Excerpt:**<br>     ```<br>     Company reserves the right to change its process and/or fees, from time to time, in its sole and absolute discretion. In the event of a price and/or fee change for Technology, Company shall notify MA in writing ninety (90) days prior to the effective date of any such change. All other prices and/or fees may be adjusted without prior notice to MA.<br>     ```<br><br>Would you like more information about this contract or any other details?</pre><p>In order to answer this question, Semantic Kernel is executing the <strong>get_contract_similar_text data</strong> retrieval function.</p><pre>User &gt; any contract mentions the ability to make price changes from time to time<br>INFO:semantic_kernel.connectors.ai.open_ai.services.open_ai_chat_completion_base:processing 1 tool calls in parallel.<br><br>INFO:semantic_kernel.kernel:Calling contract_search-get_contracts_similar_text<br> function with args: {&quot;clause_text&quot;:&quot;price changes from time to time&quot;}<br><br><br>Assistant &gt; Yes, there is a contract that mentions the ability to make price changes from time to time. Here is the relevant excerpt:<br><br>1. **Birch First Global Investments Inc. and Mount Knowledge Holdings Inc. MARKETING AFFILIATE AGREEMENT**<br>   - **Contract ID:** 1<br>   - **Clause Type:** Price Restrictions<br>   - **Excerpt:**<br>     ```<br>     Company reserves the right to change its process and/or fees, from time to time, in its sole and absolute discretion. In the event of a price and/or fee change for Technology, Company shall notify MA in writing ninety (90) days prior to the effective date of any such change. All other prices and/or fees may be adjusted without prior notice to MA.<br>     ```</pre><p>As explained earlier, this function uses vector search and a Cypher query to retrieve not just semantically similar excerpts but also the related contract and clauses that includes them.</p><p>Finally, let’s ask how many contracts are there on the database</p><blockquote>4. How many contracts are there in the database?</blockquote><p>This questions requires the LLM to use the Text2Cypher data retriever</p><pre>Assistant &gt; There are a total of 3 contracts in the database.</pre><p>The debug information confirms that Semantic Kernel ran the Text2Cypher data retrieval function with “user_question” = “How many contracts are there in the database’?</p><pre>User &gt;  how many contracts are there on the database?<br>INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions &quot;HTTP/1.1 200 OK&quot;<br>INFO:semantic_kernel.connectors.ai.open_ai.services.open_ai_chat_completion_base:processing 1 tool calls in parallel.<br><br>INFO:semantic_kernel.kernel:Calling contract_search-answer_aggregation_question function <br>with args: {&quot;user_question&quot;:&quot;How many contracts are there in the database?&quot;}<br><br><br>INFO:semantic_kernel.functions.kernel_function:Function completed. Duration: 0.588805s<br><br>INFO:semantic_kernel.connectors.ai.open_ai.services.open_ai_handler:OpenAI usage: CompletionUsage(completion_tokens=13, prompt_tokens=3328, total_tokens=3341, completion_tokens_details={&#39;reasoning_tokens&#39;: 0})<br><br>Assistant &gt; There are a total of 3 contracts in the database.</pre><h3><strong>Try it Yourself</strong></h3><p>The <a href="https://github.com/neo4j-product-examples/graphrag-contract-review">github repo</a> contains a Streamlit app that provides a more elegant Agent UI. You are encouraged to interact with the agent and make changes to the ContractPlugin so your agent’s ability to handle more questions!</p><h3>Conclusion</h3><p>In this blog, we explored a Graph Retrieval Augmented Generation (GraphRAG) approach to transform labor-intensive tasks of commercial contract review into a more efficient, AI-driven process.</p><p>By focusing on targeted information extraction using LLMs and prompts, building a structured knowledge graph with Neo4j, implementing simple data retrieval functions, and ultimately developing a Q&amp;A agent, we created an intelligent solution that handles complex questions effectively.</p><p>This approach minimizes inefficiencies found in traditional vector search based RAG, focusing instead on extracting only relevant information, reducing the need for unnecessary vector embeddings, and simplifying the overall process. We hope this journey from contract ingestion to an interactive Q&amp;A agent inspires you to leverage GraphRAG in your own projects for improved efficiency and smarter AI-driven decision-making.</p><p>Start building your own commercial contract review agent today and experience the power of GraphRAG firsthand!</p><h3>Resources</h3><p>For those eager to take a deeper dive, please check out the resources linked below:</p><ul><li><a href="https://github.com/neo4j-product-examples/graphrag-contract-review">GitHub repository with the code and detailed instructions</a></li><li><a href="https://github.com/TheAtticusProject/cuad">Contract Understanding Atticus Dataset (CUAD) for Legal Contracts</a> (Github)</li><li><a href="https://arxiv.org/pdf/2103.06268">CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review. Hendrycks, Burns, Chen, Ball. NeurIPS 2021</a></li><li><a href="https://neo4j.com/blog/graphrag-python-package/">Neo4j GraphRAG package launch blog post</a></li><li><a href="https://learn.microsoft.com/en-us/semantic-kernel/overview/">Microsoft Semantic Kernel library</a></li></ul><p>Unless otherwise noted, all images are by the author</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d4a6caa6eb5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/graphrag-in-action-from-commercial-contracts-to-a-dynamic-q-a-agent-7d4a6caa6eb5">GraphRAG in Action: From Commercial Contracts to a Dynamic Q&amp;A Agent</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>