{
  "markdown": "# LangGraph OKF Consumer (Legal Knowledge Graph)\n\nA demonstration consumer for [Google's Open Knowledge Format (OKF v0.2)](https://github.com/GoogleCloudPlatform/open-knowledge-format/blob/main/SPEC.md), using LangGraph for LLM-guided graph traversal over fictional legal contracts, with an offline keyword fallback.\n\nThis is a partial implementation, not a conformance-certified consumer. The bundled\nagreements and human review records are fictional fixtures. See\n[bundle scope](bundles/legal_sample/scope.md) for missing evidence and calculation limits.\n\n> **Scope Note**: This repository focuses exclusively on the **OKF Consumer setup**. Ingestion/producer logic will be addressed in a separate project.\n\n---\n\n## Why OKF Over Conventional RAG for Legal Documents\n\nConventional RAG chops legal documents into isolated vector chunks, losing:\n1. **Contract Structure**: Agreements, sections, clauses, and exhibits are flattened.\n2. **Cross-References**: Clauses referencing definitions (e.g. \"Confidential Information\", \"Fees\") or addenda (e.g. DPA supercaps) are severed.\n3. **Trust & Provenance**: Cannot distinguish attorney-reviewed clauses from AI drafts.\n4. **Freshness**: Outdated or superseded terms pollute similarity search.\n\n**OKF (Open Knowledge Format v0.2)** represents legal knowledge as a directory tree of Markdown files with YAML frontmatter:\n- **Progressive Disclosure**: Agents navigate using `index.md` files at each level, loading only what is needed.\n- **Trust Tiers**: `human-reviewed`, `machine-confirmed`, and `unverified` are inferred from frontmatter actor signals.\n- **Relational Links**: Standard Markdown links (`[Fees](/definitions/fees.md)`) create explicit, traversable graph edges.\n- **Attested Computations**: Deterministic formulas (e.g., liability caps, cure periods) are evaluated mathematically rather than guessed.\n\n---\n\n## Architecture\n\n```mermaid\nflowchart TD\n    Plan[Plan: LLM selects sections] --> Navigate[Navigate: LLM selects concepts]\n    Navigate --> Inspect[Inspect: load evidence and check trust]\n    Inspect --> Review[Review: LLM selects more linked evidence]\n    Review -->|More evidence, within depth limit| Inspect\n    Review -->|Enough evidence or limit reached| Compute[Compute: registered Python rules]\n    Compute --> Synthesize[Synthesize: LLM writes cited answer]\n```\n\nWithout an LLM, selection and link expansion use deterministic fallbacks and\nsynthesis produces an evidence report. The review step runs inside `expand.py`.\n\n```\nlanggraph-okf/\n├── bundles/\n│   └── legal_sample/                 # Fictional OKF demonstration bundle\n│       ├── index.md                  # Root progressive disclosure index\n│       ├── log.md                    # Bundle update history (§3.1 & §9)\n│       ├── definitions/              # Legal definition concepts\n│       ├── contracts/                # Agreements & Addenda\n│       │   ├── msa/                  # Master Services Agreement & Clauses\n│       │   ├── dpa/                  # Data Processing Addendum (2x Supercap)\n│       │   └── sla/                  # Service Level Agreement\n│       └── computations/             # Attested Computations (Liability, Notice)\n├── src/\n│   └── langgraph_okf/                # OKF v0.2 Consumer Core\n│       │── models.py             # Pydantic models for Concept, Frontmatter, TrustTier\n│       │── parser.py             # Permissive YAML+Markdown parser (§4 & §11)\n│       │── bundle.py             # Bundle reader, index traversal, link resolution\n│       │── trust.py              # Trust tier evaluator & freshness checker\n│       ├── agent/                    # LangGraph Workflow Layer\n│       │   ├── state.py              # LegalDiscoveryState schema\n│       │   ├── context.py            # Per-run bundle, LLM, and policy dependencies\n│       │   ├── reasoning.py          # Validated LLM selections and usage accounting\n│       │   ├── llm.py                # OpenRouter ChatOpenAI factory with custom headers\n│       │   ├── tools.py              # Attested computation execution tools\n│       │   ├── nodes/                # Individual Node Files\n│       │   │   ├── plan.py           # Planning & root index evaluation\n│       │   │   ├── navigate.py       # Progressive disclosure index traversal\n│       │   │   ├── inspect.py        # Concept inspection & trust evaluation\n│       │   │   ├── expand.py         # Relational link graph expansion\n│       │   │   ├── compute.py        # Deterministic Attested Computation execution\n│       │   │   └── synthesize.py     # Grounded legal synthesis with citations\n│       │   └── graph.py              # Compiled LangGraph workflow\n│       ├── cli.py                    # Interactive query & inspection CLI\n│       └── settings.py               # OpenRouter & OKF configuration settings\n└── tests/\n    ├── test_okf_parser.py            # Permissive parsing conformance tests\n    ├── test_trust_evaluator.py       # Trust signal & lifecycle verification tests\n    ├── test_bundle_traversal.py      # Progressive disclosure & link resolution tests\n    ├── test_agent_workflow.py        # End-to-end LangGraph agent discovery tests\n    ├── test_agent_reasoning.py       # Semantic selection and bounded evidence review\n    ├── test_runtime_context.py       # Per-run dependency and policy isolation\n    ├── test_usage_metrics.py         # Token, cost, timing, and fallback reporting\n    └── test_audit_regressions.py     # Security and consumer behavior regressions\n```\n\n---\n\n## Setup & Quickstart\n\n### Prerequisites\n- Python >= 3.14\n- [uv](https://docs.astral.sh/uv/)\n\n### Installation\n```bash\ngit clone https://github.com/ConceptCodes/langgraph-okf.git\ncd langgraph-okf\nuv sync\n```\n\n### Configuration\nCreate a `.env` file (optional, defaults to deterministic fallback if no API key is provided):\n```ini\nOPENROUTER_API_KEY=your_openrouter_api_key_here\nOPENROUTER_MODEL=google/gemini-3.8-flash\n```\n\n---\n\n## Running the CLI\n\nQueries end with a Run Metrics table showing total time (setup and graph execution),\nLLM time, the returned model name, input/output/total tokens, and request cost in USD.\nCost uses [OpenRouter usage accounting](https://openrouter.ai/docs/cookbook/administration/usage-accounting),\nnot a hard-coded price estimate. Unreported usage or failed calls show unavailable\nvalues; offline runs show zero tokens and cost. Metrics aggregate all planning,\nnavigation, evidence-review, and synthesis calls, with a per-call breakdown. They\ndo not cover account-wide usage or separately billed SDK retry attempts. If any\ncall lacks usage, the corresponding aggregate is unavailable rather than undercounted.\n\n### 1. Run a Legal Discovery Query\n```bash\nuv run langgraph-okf query 'What is the liability cap under the MSA, what exceptions apply, and how does a data breach affect it with $100,000 in fees?'\n```\n\n### 2. Inspect a Concept Document\n```bash\nuv run langgraph-okf inspect contracts/msa/clauses/limitation_of_liability\n```\n\n### 3. List All Concepts in the Legal Bundle\n```bash\nuv run langgraph-okf list\n```\n\n### 4. Test Semantic Retrieval or Offline Mode\n```bash\nuv run langgraph-okf query 'What remedies are available if the platform goes dark?'\nOPENROUTER_API_KEY='' uv run langgraph-okf query 'What notice is required for termination?'\n```\n\nThe final answer appears in the **Grounded Evidence & Synthesis** panel, followed\nby **Run Metrics** and, for live runs, **LLM Calls**. The traversal log records model\nselections and fallbacks. Keep dollar amounts inside single quotes to prevent shell expansion.\n\n---\n\n## Running Tests\n\n```bash\nuv run pytest -v\nuv run ruff check src tests\n```\n\nTests force offline mode and use the sample bundle, regardless of local `.env` credentials.\n\n## Consumer behavior and limits\n\nWith an LLM configured, planning selects sections from directory indexes and\nnavigation selects concepts from index titles/descriptions. After inspection, the\nLLM reviews retrieved evidence and can request more offered linked concepts or stop.\nEach selection is checked against the candidate IDs; arbitrary paths are rejected.\nMalformed or failed selection calls use deterministic traversal as a fallback.\nEmpty planning/navigation selections also fall back; an empty review selection stops expansion.\nTrust checks and registered Python calculations remain deterministic.\n\nThere are at most `MAX_TRAVERSAL_DEPTH + 3` application-level LLM calls: planning,\nnavigation, one review per expansion round, and synthesis. Phases without candidates\nare skipped. SDK retries may add network requests. Offline mode uses no LLM calls.\n\nThe graph uses [LangGraph runtime context](https://docs.langchain.com/oss/python/langgraph/graph-api#runtime-context).\nEvery node accepts `Runtime[Context]`. Each invocation supplies one bundle instance,\nan optional chat model (`None` means offline), and fixed trust/traversal policy.\nNodes do not read global settings. Query progress and results remain in graph state.\n\n```python\nfrom langgraph_okf.agent import Context, build_legal_discovery_graph\nfrom langgraph_okf.bundle import OKFBundle\n\ngraph = build_legal_discovery_graph()\ncontext = Context(bundle=OKFBundle(\"bundles/legal_sample\"), max_traversal_depth=3)\nresult = graph.invoke(\n    {\"query\": \"What is the standard liability cap with $100,000 in fees?\"},\n    context=context,\n    config=context.invocation_config,\n)\n```\n\nThe CLI constructs `Context.from_settings(settings)` once per query. Python callers\nmust now pass context explicitly; `get_openrouter_llm` also requires an explicit\n`Settings` argument. Supply `config=context.invocation_config` so LangGraph's step\nlimit accommodates the selected traversal depth. One compiled graph can be reused\nwith different contexts, including concurrent calls.\n\n- Paths and symlinks must remain inside the bundle. Index navigation follows nested\n  directories; relational expansion uses `MAX_TRAVERSAL_DEPTH` as a link-hop limit.\n- `MIN_TRUST_TIER` selects evidence for this application's workflow. `STRICT_VALIDATION=true`\n  additionally excludes stale/deprecated concepts. The underlying parser remains permissive;\n  these settings are application policy, not OKF validity checks.\n- Verification mappings and lists are supported. Trust is inferred from declared actors;\n  identities and signatures are not authenticated.\n- Only two registered sample computations run. They require explicit inputs and reject\n  unknown executors and invalid numeric values. Query classification is heuristic, with\n  assumptions shown in the output. Arbitrary bundle code is never executed.\n- Calculation outputs are local results, not independently attested receipts.\n- Offline output includes the retrieved text and citations; it is an evidence report,\n  not a substitute for legal interpretation. Configuring an API key enables sending\n  the query, index metadata, and retrieved evidence to OpenRouter for selection,\n  evidence review, and synthesis.\n- The parser supports inline Markdown links, not the full CommonMark link grammar.\n  Legacy v0.1 provenance conversion and external computation runtimes are not implemented.\n- Run CLI examples from the repository root, or set `BUNDLE_PATH` to an absolute directory.\n  The sample bundle is not installed as package data.\n",
  "bytes": 11225,
  "sha": "251a1c7c6fa0a1d14125f5e771973587237fb799e76148006cbc4c46ca29e5e8",
  "repo_slug": "conceptcodes/langgraph-okf",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/okf_conceptcodes_langgraph_okf_bundles_legal_3655f7fd/readme"
}