Skip to content

linexcel.aidoc

linexcel.aidoc

AI-generated documentation for Excel calculations.

Vendor-neutral by construction: no provider is named in the code and none is chosen for you. There are exactly two ways in:

  • base_url=, for any OpenAI-compatible endpoint (a local Ollama, vLLM or LM Studio runtime; a hosted gateway such as OpenRouter; OpenAI itself; anything else that speaks /chat/completions)
  • provider=, for your own callable or :class:LLMProvider object, for an API that speaks something else entirely

Each node is presented with deterministic evidence from the graph and source metadata. Prompts ask the model to cite this evidence; generated claims still require review and are not a proof of calculation correctness.

TokenUsage dataclass

Tokens consumed by one or more documentation requests.

estimated is True as soon as any request in the tally had to be approximated by :func:estimate_tokens instead of being reported by the provider. Treat such a total as an order of magnitude, not a bill.

Source code in src/linexcel/aidoc.py
@dataclass
class TokenUsage:
    """Tokens consumed by one or more documentation requests.

    ``estimated`` is ``True`` as soon as any request in the tally had to be
    approximated by :func:`estimate_tokens` instead of being reported by the
    provider. Treat such a total as an order of magnitude, not a bill.
    """

    input_tokens: int = 0
    output_tokens: int = 0
    requests: int = 0
    estimated: bool = False
    model: str = ""
    provider: str = ""

    @property
    def total(self) -> int:
        return self.input_tokens + self.output_tokens

    def add(self, other: TokenUsage) -> None:
        """Accumulate ``other`` in place, keeping the model/provider labels."""
        self.input_tokens += other.input_tokens
        self.output_tokens += other.output_tokens
        self.requests += other.requests
        self.estimated = self.estimated or other.estimated
        self.model = self.model or other.model
        self.provider = self.provider or other.provider

    def __str__(self) -> str:
        about = "~" if self.estimated else ""
        where = f" [{self.provider}/{self.model}]" if self.provider else ""
        return (
            f"{about}{self.total:,} tokens "
            f"({about}{self.input_tokens:,} in + {about}{self.output_tokens:,} out) "
            f"over {self.requests} request(s){where}"
        )

add

add(other: TokenUsage) -> None

Accumulate other in place, keeping the model/provider labels.

Source code in src/linexcel/aidoc.py
def add(self, other: TokenUsage) -> None:
    """Accumulate ``other`` in place, keeping the model/provider labels."""
    self.input_tokens += other.input_tokens
    self.output_tokens += other.output_tokens
    self.requests += other.requests
    self.estimated = self.estimated or other.estimated
    self.model = self.model or other.model
    self.provider = self.provider or other.provider

LLMProvider

Bases: Protocol

Minimal protocol mapping a system and user prompt to a text response.

Source code in src/linexcel/aidoc.py
@runtime_checkable
class LLMProvider(Protocol):
    """Minimal protocol mapping a system and user prompt to a text response."""

    def generate(
        self,
        system_prompt: str,
        user_prompt: str,
        *,
        temperature: float = 0.2,
        max_tokens: int | None = None,
    ) -> str: ...

UsageReportingProvider

Bases: Protocol

A provider that also reports what the call consumed.

Optional: the built-in OpenAI-compatible client implements it so that token counts come from the API rather than from an approximation. Custom providers only need :class:LLMProvider.

Source code in src/linexcel/aidoc.py
@runtime_checkable
class UsageReportingProvider(Protocol):
    """A provider that also reports what the call consumed.

    Optional: the built-in OpenAI-compatible client implements it so that token
    counts come from the API rather than from an approximation. Custom
    providers only need :class:`LLMProvider`.
    """

    def generate_with_usage(
        self,
        system_prompt: str,
        user_prompt: str,
        *,
        temperature: float = 0.2,
        max_tokens: int | None = None,
    ) -> tuple[str, TokenUsage]: ...

VisionProvider

Bases: Protocol

A provider that can be handed an image alongside the prompts.

Optional, and separate from :class:LLMProvider on purpose: most models served behind an OpenAI-compatible endpoint are text-only, and a caller asking for screenshot descriptions should be told so rather than have an image quietly dropped from the request.

Source code in src/linexcel/aidoc.py
@runtime_checkable
class VisionProvider(Protocol):
    """A provider that can be handed an image alongside the prompts.

    Optional, and separate from :class:`LLMProvider` on purpose: most models
    served behind an OpenAI-compatible endpoint are text-only, and a caller
    asking for screenshot descriptions should be told so rather than have an
    image quietly dropped from the request.
    """

    def generate_with_image(
        self,
        system_prompt: str,
        user_prompt: str,
        image: bytes,
        *,
        media_type: str = "image/png",
        temperature: float = 0.2,
        max_tokens: int | None = None,
    ) -> tuple[str, TokenUsage]: ...

MultiImageVisionProvider

Bases: Protocol

Optional native-region batching, preserving labels and image identities.

Source code in src/linexcel/aidoc.py
@runtime_checkable
class MultiImageVisionProvider(Protocol):
    """Optional native-region batching, preserving labels and image identities."""

    def generate_with_images(
        self,
        system_prompt: str,
        user_prompt: str,
        images: list[tuple[str, bytes, str]],
        *,
        temperature: float = 0.2,
        max_tokens: int | None = None,
    ) -> tuple[str, TokenUsage]: ...

OpenAICompatProvider

A client for anything exposing an OpenAI-compatible chat API.

The wire format is the only thing assumed. Which vendor, gateway or local runtime answers at base_url is the caller's business.

base_url may contain {model} in its hostname or path. The model is also sent in the JSON body. Pass this object as provider= to node, workbook or image documentation. client_kwargs configures the SDK; http_client_kwargs configures its default HTTPX transport (HTTPX2 in newer SDKs); request_kwargs configures chat completions, including extra_body, extra_headers and extra_query.

streaming=True explicitly assembles content deltas and terminal usage. A stream must finish with stop; interrupted streams are never accepted as documentation. SDK retries do not restart an interrupted stream.

Use a context manager to close connections created here. Injected SDK clients and HTTP clients remain caller-owned and are never closed here.

Source code in src/linexcel/aidoc.py
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
class OpenAICompatProvider:
    """A client for anything exposing an OpenAI-compatible chat API.

    The wire format is the only thing assumed. Which vendor, gateway or local
    runtime answers at ``base_url`` is the caller's business.

    ``base_url`` may contain ``{model}`` in its hostname or path. The model
    is also sent in the JSON body. Pass this object as ``provider=`` to node,
    workbook or image documentation. ``client_kwargs`` configures the SDK;
    ``http_client_kwargs`` configures its default HTTPX transport (HTTPX2 in
    newer SDKs); ``request_kwargs`` configures chat completions, including
    ``extra_body``, ``extra_headers`` and ``extra_query``.

    ``streaming=True`` explicitly assembles content deltas and terminal usage.
    A stream must finish with ``stop``; interrupted streams are never accepted
    as documentation. SDK retries do not restart an interrupted stream.

    Use a context manager to close connections created here. Injected SDK
    clients and HTTP clients remain caller-owned and are never closed here.
    """

    def __init__(
        self,
        *,
        model: str,
        base_url: str | None = None,
        api_key: str | None = None,
        proxy: str | None = None,
        http_client: Any = None,
        http_client_kwargs: Mapping[str, Any] | None = None,
        client_kwargs: Mapping[str, Any] | None = None,
        request_kwargs: Mapping[str, Any] | None = None,
        streaming: bool = False,
        client: Any = None,
    ):
        if not model:
            raise ValueError("model must be named")
        self._model = model
        self._streaming = streaming
        self._vision_state = local()
        self._request_state = local()
        self._request_kwargs = dict(request_kwargs or {})
        if {
            "model",
            "messages",
            "max_tokens",
            "max_completion_tokens",
        } & self._request_kwargs.keys():
            raise ValueError(
                "request_kwargs cannot override model, messages or max_tokens"
            )
        extra_body = self._request_kwargs.get("extra_body") or {}
        if {
            "model",
            "messages",
            "max_tokens",
            "max_completion_tokens",
        } & extra_body.keys():
            raise ValueError("extra_body cannot override model, messages or max_tokens")
        if "stream" in self._request_kwargs or "stream" in extra_body:
            raise ValueError(
                "Use the explicit streaming argument, not request_kwargs stream"
            )
        for options in (self._request_kwargs, extra_body):
            if "n" in options and (type(options["n"]) is not int or options["n"] != 1):
                raise ValueError("Documentation requires a single choice (n=1)")
        self._owns_client = client is None and http_client is None
        if client is not None:
            if getattr(getattr(client, "_client", None), "follow_redirects", False):
                raise ValueError("AI SDK clients must disable follow_redirects")
            if any(
                (
                    base_url,
                    api_key,
                    proxy,
                    http_client is not None,
                    http_client_kwargs,
                    client_kwargs,
                )
            ):
                raise ValueError(
                    "client cannot be combined with SDK or HTTP configuration"
                )
            self._client = client
            self._base_url = str(getattr(client, "base_url", "")).rstrip("/")
            return
        base = (
            base_url
            or os.getenv("LINEXCEL_AI_BASE_URL")
            or os.getenv("OPENAI_BASE_URL")
        )
        if not base:
            raise AiDocError("No AI provider selected: pass base_url= or client=")
        base = _model_base_url(base, model)
        self._base_url = base.rstrip("/")
        options = dict(client_kwargs or {})
        if {"api_key", "base_url", "http_client"} & options.keys():
            raise ValueError("Use explicit api_key, base_url and http_client arguments")
        http_options = dict(http_client_kwargs or {})
        if http_client is not None and (proxy is not None or http_options):
            raise ValueError(
                "http_client cannot be combined with proxy or http_client_kwargs"
            )
        if http_client is None:
            if http_options.get("follow_redirects"):
                raise ValueError(
                    "AI endpoint redirects are refused; configure the final URL"
                )
            http_options["follow_redirects"] = False
        elif getattr(http_client, "follow_redirects", False):
            raise ValueError("AI HTTP clients must disable follow_redirects")
        if proxy is not None:
            if "proxy" in http_options:
                raise ValueError("Specify proxy only once")
            http_options["proxy"] = proxy
        try:
            from openai import DefaultHttpxClient, OpenAI
        except ImportError as exc:  # pragma: no cover
            raise AiDocError(
                "openai is not installed (pip install 'linexcel[ai]' or "
                "pip install openai). It is the client for every "
                "OpenAI-compatible endpoint, not a choice of vendor."
            ) from exc
        # Local runtimes ignore the key but the client refuses to start without
        # one, so a placeholder stands in rather than a hosted key being needed.
        if "timeout" not in options:
            timeout = float(os.getenv("LINEXCEL_AI_TIMEOUT_SECONDS", "300"))
            if not math.isfinite(timeout) or timeout <= 0:
                raise ValueError(
                    "LINEXCEL_AI_TIMEOUT_SECONDS must be finite and positive"
                )
            options["timeout"] = timeout
        options.setdefault("max_retries", 0)
        created_http = None
        if http_options:
            created_http = DefaultHttpxClient(**http_options)
            http_client = created_http
        try:
            self._client = OpenAI(
                api_key=(
                    api_key
                    or os.getenv("LINEXCEL_AI_API_KEY")
                    or os.getenv("OPENAI_API_KEY")
                    or "not-needed"
                ),
                base_url=base,
                http_client=http_client,
                **options,
            )
        except Exception:
            if created_http is not None:
                created_http.close()
            raise

    def close(self) -> None:
        """Close owned connections after all in-flight calls have finished."""
        if self._owns_client:
            self._client.close()

    def __enter__(self) -> OpenAICompatProvider:
        return self

    def __exit__(self, *args: Any) -> None:
        self.close()

    def generate(
        self,
        system_prompt: str,
        user_prompt: str,
        *,
        temperature: float = 0.2,
        max_tokens: int | None = None,
    ) -> str:
        return self.generate_with_usage(
            system_prompt, user_prompt, temperature=temperature, max_tokens=max_tokens
        )[0]

    def generate_with_usage(
        self,
        system_prompt: str,
        user_prompt: str,
        *,
        temperature: float = 0.2,
        max_tokens: int | None = None,
    ) -> tuple[str, TokenUsage]:
        kwargs: dict[str, Any] = {"temperature": temperature, **self._request_options()}
        if max_tokens is not None:
            kwargs["max_tokens"] = max_tokens
        return self._complete(
            [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt},
            ],
            system_prompt + "\n\n" + user_prompt,
            kwargs,
        )

    def _complete(
        self,
        messages: list[dict[str, Any]],
        prompt: str,
        options: dict[str, Any],
        *,
        vision: bool = False,
        structured: bool = False,
    ) -> tuple[Any, TokenUsage]:
        streaming = getattr(self, "_streaming", False)
        if streaming:
            options["stream"] = True
            # Extra-body SDK fields can override top-level options; consolidate
            # both sources before forcing terminal usage for the stream.
            extra_body = dict(options.get("extra_body") or {})
            stream_options = {
                **(options.get("stream_options") or {}),
                **(extra_body.pop("stream_options", None) or {}),
                "include_usage": True,
            }
            options["stream_options"] = stream_options
            if "extra_body" in options:
                options["extra_body"] = extra_body
        if not hasattr(self, "_request_state"):
            self._request_state = local()
        self._request_state.receipt = None
        self._request_state.attempts = []
        self._request_state.rejected_usage = TokenUsage()
        self._request_state.usage_accounted = False
        key = (getattr(self, "_base_url", ""), self._model)
        with _PARAMETER_LOCK:
            shape = set(_PARAMETER_SHAPES.get(key, ())) if key[0] else set()
        options = dict(options)
        options["extra_body"] = dict(options.get("extra_body") or {})

        def adapt():
            if "max_tokens" in shape and "max_tokens" in options:
                options["max_completion_tokens"] = options.pop("max_tokens")
            if "temperature" in shape:
                options.pop("temperature", None)
                options["extra_body"].pop("temperature", None)

        adapt()
        try:
            while True:
                sent = {**options, **options["extra_body"]}
                attempt = {
                    "parameters": {
                        k: sent[k]
                        for k in ("temperature", "max_tokens", "max_completion_tokens")
                        if k in sent
                    },
                    "temperature_omitted": "temperature" not in sent,
                    "token_parameter": next(
                        (
                            k
                            for k in ("max_tokens", "max_completion_tokens")
                            if k in sent
                        ),
                        None,
                    ),
                    "status": "pending",
                }
                self._request_state.attempts.append(attempt)
                try:
                    response = self._client.chat.completions.create(
                        model=self._model,
                        messages=cast("Iterable[ChatCompletionMessageParam]", messages),
                        **options,
                    )
                    attempt["status"] = "received"
                    if key[0]:
                        with _PARAMETER_LOCK:
                            _PARAMETER_SHAPES[key] = frozenset(
                                shape
                            ) | _PARAMETER_SHAPES.get(key, frozenset())
                    break
                except Exception as exc:
                    rejected = _rejected_parameter(exc)
                    attempt.update(
                        status="failed",
                        http_status=getattr(exc, "status_code", None),
                        rejected_parameter=rejected,
                    )
                    # HTTP 400 has no completion usage. Charge a conservative
                    # prompt estimate and count the request rather than silently
                    # excluding the negotiation from the shared budget tally.
                    self._request_state.rejected_usage.add(
                        TokenUsage(
                            input_tokens=estimate_tokens(prompt),
                            requests=1,
                            estimated=True,
                            model=self._model,
                            provider="openai-compatible",
                        )
                    )
                    if rejected is None or rejected in shape or rejected not in sent:
                        raise
                    shape.add(rejected)
                    adapt()  # At most one retry for each rejected parameter.
            if streaming:
                return self._consume_stream(response, prompt)
            if structured:
                # The question agent has a distinct structured-output contract.
                # Reuse the client and negotiated wire parameters, without
                # treating tool calls as documentation prose.
                blob = response.model_dump_json()
                usage = _usage_from(
                    getattr(response, "usage", None),
                    ("prompt_tokens", "completion_tokens"),
                    prompt,
                    blob,
                    model=self._model,
                    provider="openai-compatible",
                )
                usage.add(self._request_state.rejected_usage)
                self._request_state.usage_accounted = True
                return response, usage
            text = (response.choices[0].message.content or "").strip()
        except AiDocError as exc:
            if exc.usage is not None and not self._request_state.usage_accounted:
                exc.usage.add(self._request_state.rejected_usage)
            self._failed_receipt(prompt, exc.usage)
            raise
        except Exception as exc:
            kind = "vision" if vision else "API"
            hint = (
                " Check gateway settings and the model's image support."
                if vision
                else ""
            )
            status = getattr(exc, "status_code", None)
            if isinstance(status, int) and 300 <= status < 400:
                hint = " Endpoint redirect refused; configure the final endpoint URL."
            self._failed_receipt(prompt, self._request_state.rejected_usage)
            raise AiDocError(
                f"OpenAI-compatible {kind} call failed ({_api_error_name(exc)}).{hint}",
                usage=self._request_state.rejected_usage,
            ) from exc
        return self._checked_response(response, prompt, text)

    def _failed_receipt(self, prompt: str, usage: TokenUsage | None) -> None:
        if self.receipt is not None:
            return
        self._request_state.receipt = {
            "status": "failed",
            "requested_model": self._model,
            "prompt_text_sha256": hashlib.sha256(prompt.encode()).hexdigest(),
            "usage": vars(usage).copy() if usage is not None else None,
            **self.request_parameters,
        }
        state = getattr(self, "_vision_state", None)
        if state is not None and getattr(state, "active", False):
            state.receipt = self._request_state.receipt

    def _consume_stream(self, stream: Any, prompt: str) -> tuple[str, TokenUsage]:
        parts: list[str] = []
        reported = None
        finish_reason = None
        resolved_model = None
        response_id = None
        failure = None
        try:
            for chunk in stream:
                chunk_model, chunk_id = (
                    getattr(chunk, "model", None),
                    getattr(chunk, "id", None),
                )
                if chunk_model:
                    if resolved_model is not None and chunk_model != resolved_model:
                        raise AiDocError("AI stream changed its resolved model")
                    resolved_model = chunk_model
                if chunk_id:
                    if response_id is not None and chunk_id != response_id:
                        raise AiDocError("AI stream changed its response id")
                    response_id = chunk_id
                if getattr(chunk, "usage", None) is not None:
                    reported = chunk.usage
                choices = getattr(chunk, "choices", None) or []
                if len(choices) > 1:
                    raise AiDocError(
                        "AI stream contains multiple choices; expected index 0"
                    )
                for choice in choices:
                    if getattr(choice, "index", None) != 0:
                        raise AiDocError(
                            "AI stream contains an unexpected choice index; expected 0"
                        )
                    if finish_reason is not None:
                        raise AiDocError(
                            "AI stream returned choices after a terminal finish reason"
                        )
                    content = getattr(choice.delta, "content", None)
                    if content is not None:
                        if not isinstance(content, str):
                            raise AiDocError(
                                "AI stream returned a non-text content delta"
                            )
                        parts.append(content)
                    # reasoning_content and reasoning_details are not prose.
                    finish_reason = getattr(choice, "finish_reason", None)
        except AiDocError as exc:
            failure = exc
            if exc.usage is None:
                exc.usage = _usage_from(
                    reported,
                    ("prompt_tokens", "completion_tokens"),
                    prompt,
                    "".join(parts),
                    model=self._model,
                    provider="openai-compatible",
                )
            raise
        except Exception as exc:
            usage = _usage_from(
                reported,
                ("prompt_tokens", "completion_tokens"),
                prompt,
                "".join(parts),
                model=self._model,
                provider="openai-compatible",
            )
            failure = AiDocError(
                f"OpenAI-compatible stream failed ({_api_error_name(exc)})",
                usage=usage,
            )
            raise failure from exc
        finally:
            try:
                stream.close()
            except Exception as exc:
                usage = _usage_from(
                    reported,
                    ("prompt_tokens", "completion_tokens"),
                    prompt,
                    "".join(parts),
                    model=self._model,
                    provider="openai-compatible",
                )
                if failure is not None:
                    failure.add_note(
                        f"Stream close also failed ({_api_error_name(exc)})"
                    )
                else:
                    raise AiDocError(
                        "OpenAI-compatible stream close failed "
                        f"({_api_error_name(exc)})",
                        usage=usage,
                    ) from exc
        # A completed receipt follows successful close, so a subclass cannot
        # record success before a close failure makes the whole call fail.
        text = "".join(parts).strip()
        assembled = SimpleNamespace(
            model=resolved_model,
            id=response_id,
            usage=reported,
            choices=[
                SimpleNamespace(
                    index=0,
                    finish_reason=finish_reason,
                    message=SimpleNamespace(content=text),
                )
            ],
        )
        return self._checked_response(assembled, prompt, text, require_stop=True)

    def _checked_response(
        self,
        response: Any,
        prompt: str,
        text: str,
        *,
        require_stop: bool = False,
    ) -> tuple[str, TokenUsage]:
        status, usage = "failed", None
        try:
            output, usage = self._checked_output(
                getattr(response, "usage", None),
                prompt,
                text,
                getattr(response.choices[0], "finish_reason", None),
                require_stop=require_stop,
            )
            state = getattr(self, "_request_state", None)
            if state is not None:
                usage.add(getattr(state, "rejected_usage", TokenUsage()))
                state.usage_accounted = True
            status = "complete"
            return output, usage
        except AiDocError as exc:
            usage = exc.usage
            state = getattr(self, "_request_state", None)
            if usage is not None and state is not None:
                usage.add(getattr(state, "rejected_usage", TokenUsage()))
                state.usage_accounted = True
            raise
        finally:
            state = getattr(self, "_request_state", None)
            if state is not None:
                state.receipt = {
                    "status": status,
                    "requested_model": self._model,
                    "resolved_model": getattr(response, "model", None),
                    "response_id": getattr(response, "id", None),
                    "finish_reason": getattr(
                        response.choices[0], "finish_reason", None
                    ),
                    "streaming": require_stop,
                    "prompt_text_sha256": hashlib.sha256(prompt.encode()).hexdigest(),
                    "content_sha256": hashlib.sha256(text.encode()).hexdigest(),
                    "content_characters": len(text),
                    "usage": vars(usage).copy() if usage is not None else None,
                    **self.request_parameters,
                }
                vision_state = getattr(self, "_vision_state", None)
                if vision_state is not None and getattr(vision_state, "active", False):
                    vision_state.receipt = state.receipt

    def _checked_output(
        self,
        reported: Any,
        prompt: str,
        text: str,
        reason: Any,
        *,
        require_stop: bool = False,
    ) -> tuple[str, TokenUsage]:
        usage = _usage_from(
            reported,
            ("prompt_tokens", "completion_tokens"),
            prompt,
            text,
            model=self._model,
            provider="openai-compatible",
        )
        if require_stop and reason is None:
            raise AiDocError("AI stream ended without finish_reason=stop", usage=usage)
        if reason not in (None, "stop"):
            raise AiDocError(
                f"AI response is incomplete (finish_reason={reason}). "
                "Increase max_tokens for a length limit, "
                "or inspect the provider response.",
                usage=usage,
            )
        if not text:
            raise AiDocError("AI returned empty response", usage=usage)
        return text, usage

    def generate_with_image(
        self,
        system_prompt: str,
        user_prompt: str,
        image: bytes,
        *,
        media_type: str = "image/png",
        temperature: float = 0.2,
        max_tokens: int | None = None,
    ) -> tuple[str, TokenUsage]:
        """The same call, with the image inlined as a data URI.

        No upload and no file id: the picture travels in the request body, so
        nothing is left behind on the endpoint's side.
        """
        return self.generate_with_images(
            system_prompt,
            user_prompt,
            [("image", image, media_type)],
            temperature=temperature,
            max_tokens=max_tokens,
        )

    def generate_with_images(
        self,
        system_prompt: str,
        user_prompt: str,
        images: list[tuple[str, bytes, str]],
        *,
        temperature: float = 0.2,
        max_tokens: int | None = None,
    ) -> tuple[str, TokenUsage]:
        """Send labelled native crops; the prompt supplies their exact manifest."""
        if not images:
            raise AiDocError("A vision request requires at least one image")
        content: list[dict[str, Any]] = [{"type": "text", "text": user_prompt}]
        for label, image, media_type in images:
            # Preserve the historic one-image request shape for direct callers.
            if len(images) > 1 or label != "image":
                content.append({"type": "text", "text": f"Region: {label}"})
            encoded = base64.b64encode(image).decode("ascii")
            content.append(
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:{media_type};base64,{encoded}",
                        "detail": "high",
                    },
                }
            )
        kwargs: dict[str, Any] = {"temperature": temperature, **self._request_options()}
        if max_tokens is not None:
            kwargs["max_tokens"] = max_tokens
        # The fallback estimate counts the prompts only, because an image is
        # worth hundreds of tokens that no character count can see, so a run
        # whose endpoint reports nothing is under-counted, and says it is
        # estimated.
        if not hasattr(self, "_vision_state"):
            self._vision_state = local()
        self._vision_state.active = True
        self._vision_state.receipt = None
        try:
            return self._complete(
                [
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": content},
                ],
                system_prompt + "\n\n" + user_prompt,
                kwargs,
                vision=True,
            )
        finally:
            self._vision_state.active = False

    @property
    def request_parameters(self) -> dict[str, Any]:
        """Actual wire sampling/token fields, including rejected attempts."""
        attempts = getattr(getattr(self, "_request_state", None), "attempts", [])
        return {
            **(
                {
                    k: attempts[-1][k]
                    for k in ("parameters", "temperature_omitted", "token_parameter")
                }
                if attempts
                else {}
            ),
            "request_attempts": [dict(a) for a in attempts],
        }

    @property
    def receipt(self) -> dict[str, Any] | None:
        """Last completion receipt in this thread, excluding credentials."""
        return getattr(getattr(self, "_request_state", None), "receipt", None)

    @property
    def vision_receipt(self) -> dict[str, Any] | None:
        """Last image completion identity in this thread, excluding credentials."""
        return getattr(getattr(self, "_vision_state", None), "receipt", None)

    def _request_options(self) -> dict[str, Any]:
        # Older callers and response-contract tests construct the private class
        # without __init__; retain that compatibility.
        return getattr(self, "_request_kwargs", {})

request_parameters property

request_parameters: dict[str, Any]

Actual wire sampling/token fields, including rejected attempts.

receipt property

receipt: dict[str, Any] | None

Last completion receipt in this thread, excluding credentials.

vision_receipt property

vision_receipt: dict[str, Any] | None

Last image completion identity in this thread, excluding credentials.

close

close() -> None

Close owned connections after all in-flight calls have finished.

Source code in src/linexcel/aidoc.py
def close(self) -> None:
    """Close owned connections after all in-flight calls have finished."""
    if self._owns_client:
        self._client.close()

generate_with_image

generate_with_image(
    system_prompt: str,
    user_prompt: str,
    image: bytes,
    *,
    media_type: str = "image/png",
    temperature: float = 0.2,
    max_tokens: int | None = None,
) -> tuple[str, TokenUsage]

The same call, with the image inlined as a data URI.

No upload and no file id: the picture travels in the request body, so nothing is left behind on the endpoint's side.

Source code in src/linexcel/aidoc.py
def generate_with_image(
    self,
    system_prompt: str,
    user_prompt: str,
    image: bytes,
    *,
    media_type: str = "image/png",
    temperature: float = 0.2,
    max_tokens: int | None = None,
) -> tuple[str, TokenUsage]:
    """The same call, with the image inlined as a data URI.

    No upload and no file id: the picture travels in the request body, so
    nothing is left behind on the endpoint's side.
    """
    return self.generate_with_images(
        system_prompt,
        user_prompt,
        [("image", image, media_type)],
        temperature=temperature,
        max_tokens=max_tokens,
    )

generate_with_images

generate_with_images(
    system_prompt: str,
    user_prompt: str,
    images: list[tuple[str, bytes, str]],
    *,
    temperature: float = 0.2,
    max_tokens: int | None = None,
) -> tuple[str, TokenUsage]

Send labelled native crops; the prompt supplies their exact manifest.

Source code in src/linexcel/aidoc.py
def generate_with_images(
    self,
    system_prompt: str,
    user_prompt: str,
    images: list[tuple[str, bytes, str]],
    *,
    temperature: float = 0.2,
    max_tokens: int | None = None,
) -> tuple[str, TokenUsage]:
    """Send labelled native crops; the prompt supplies their exact manifest."""
    if not images:
        raise AiDocError("A vision request requires at least one image")
    content: list[dict[str, Any]] = [{"type": "text", "text": user_prompt}]
    for label, image, media_type in images:
        # Preserve the historic one-image request shape for direct callers.
        if len(images) > 1 or label != "image":
            content.append({"type": "text", "text": f"Region: {label}"})
        encoded = base64.b64encode(image).decode("ascii")
        content.append(
            {
                "type": "image_url",
                "image_url": {
                    "url": f"data:{media_type};base64,{encoded}",
                    "detail": "high",
                },
            }
        )
    kwargs: dict[str, Any] = {"temperature": temperature, **self._request_options()}
    if max_tokens is not None:
        kwargs["max_tokens"] = max_tokens
    # The fallback estimate counts the prompts only, because an image is
    # worth hundreds of tokens that no character count can see, so a run
    # whose endpoint reports nothing is under-counted, and says it is
    # estimated.
    if not hasattr(self, "_vision_state"):
        self._vision_state = local()
    self._vision_state.active = True
    self._vision_state.receipt = None
    try:
        return self._complete(
            [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": content},
            ],
            system_prompt + "\n\n" + user_prompt,
            kwargs,
            vision=True,
        )
    finally:
        self._vision_state.active = False

estimate_tokens

estimate_tokens(text: str) -> int

Approximate the token count of text.

Only a fallback: :class:TokenUsage prefers the counts the provider reports. Latin script is counted as words times 4/3 (the usual 1 token to roughly 0.75 words ratio); CJK characters are counted individually, because a Japanese or Chinese sentence carries no spaces and would otherwise register as a single word.

estimate_tokens("the quick brown fox jumps") 6 estimate_tokens("") 0

Source code in src/linexcel/aidoc.py
def estimate_tokens(text: str) -> int:
    """Approximate the token count of ``text``.

    Only a fallback: :class:`TokenUsage` prefers the counts the provider
    reports. Latin script is counted as words times 4/3 (the usual 1 token to
    roughly 0.75 words ratio); CJK characters are counted individually, because
    a Japanese or Chinese sentence carries no spaces and would otherwise
    register as a single word.

    >>> estimate_tokens("the quick brown fox jumps")
    6
    >>> estimate_tokens("")
    0
    """
    if not text:
        return 0
    cjk = len(_CJK_RE.findall(text))
    latin_words = len(_WORD_RE.findall(_CJK_RE.sub(" ", text)))
    return cjk + latin_words * 4 // 3

build_dossier

build_dossier(
    graph: dict[str, Any], node_id: str
) -> dict[str, Any] | None

Deterministic dossier for a node: everything the AI is allowed to use.

Source code in src/linexcel/aidoc.py
def build_dossier(graph: dict[str, Any], node_id: str) -> dict[str, Any] | None:
    """
    Deterministic dossier for a node: everything the AI is allowed to use.
    """
    return _build_dossier(_index_dossiers(graph), node_id)

build_workbook_dossier

build_workbook_dossier(
    graph: dict[str, Any],
    *,
    context: dict[str, Any] | None = None,
) -> dict[str, Any]

Return a compact, deterministic dossier for a whole-workbook overview.

context is a :attr:linexcel.LineageResult.workbook_context mapping. The graph alone describes how a workbook computes; it says nothing about what a reader sees on opening it: titles sitting above a table, the labels in the first column, cell comments, hidden columns, frozen panes. Those cues are exactly what the sheet screenshots show, and merging them into each sheet entry lets a text-only model describe the file as it looks without any image ever leaving the machine.

Both parts stay deterministic: every value is read from the workbook, so the "cite only the dossier" rule of the system prompt still holds.

Source code in src/linexcel/aidoc.py
def build_workbook_dossier(
    graph: dict[str, Any], *, context: dict[str, Any] | None = None
) -> dict[str, Any]:
    """Return a compact, deterministic dossier for a whole-workbook overview.

    ``context`` is a :attr:`linexcel.LineageResult.workbook_context` mapping.
    The graph alone describes how a workbook *computes*; it says nothing about
    what a reader sees on opening it: titles sitting above a table, the labels
    in the first column, cell comments, hidden columns, frozen panes. Those cues
    are exactly what the sheet screenshots show, and merging them into each
    sheet entry lets a text-only model describe the file as it looks without any
    image ever leaving the machine.

    Both parts stay deterministic: every value is read from the workbook, so the
    "cite only the dossier" rule of the system prompt still holds.
    """
    nodes = graph.get("nodes", [])
    meta = graph.get("meta", {})
    stats = meta.get("stats", {})
    sheet_stats = stats.get("sheets", [])
    nodes_by_sheet: dict[str, dict[str, int]] = {}
    for node in nodes:
        sheet = node.get("sheet")
        if not sheet:
            continue
        kinds = nodes_by_sheet.setdefault(sheet, {})
        kind = node.get("kind", "unknown")
        kinds[kind] = kinds.get(kind, 0) + 1

    sheets = [
        {
            "name": sheet.get("name"),
            "dimensions": {"rows": sheet.get("rows"), "columns": sheet.get("cols")},
            "formula_cells": sheet.get("formulaCells"),
            "lineage_nodes": nodes_by_sheet.get(sheet.get("name"), {}),
        }
        for sheet in sheet_stats
    ]
    if context:
        sheets = _merge_presentation(sheets, context)
    formula_patterns = sorted(
        (
            {
                "node_id": node.get("id"),
                "sheet": node.get("sheet"),
                "address": node.get("addr"),
                "formula": node.get("formula"),
                "cells": node.get("count", 1),
                "extent": node.get("bbox"),
                "formula_facts": formula_evidence(
                    node.get("formula"),
                    sheet=node.get("sheet"),
                    address=node.get("addr"),
                ),
                **_value_evidence(node),
                **_formula_provenance(node),
            }
            for node in nodes
            if node.get("kind") in {"cell", "group"}
        ),
        key=lambda item: (
            item["cells"] if isinstance(item["cells"], (int, float)) else 0
        ),
        reverse=True,
    )
    pattern_total = len(formula_patterns)
    formula_patterns = formula_patterns[:20]
    defined_names = [
        {"name": node.get("label"), "targets": node.get("targets", [])}
        for node in nodes
        if node.get("kind") == "name"
    ]
    vba = [
        {
            "module": node.get("module"),
            "procedure": node.get("proc"),
            "type": node.get("procKind"),
        }
        for node in nodes
        if node.get("kind") == "vba"
    ]
    opaque_references = [
        node.get("label") for node in nodes if node.get("kind") == "opaque"
    ]
    ext_total = stats.get("externalWorkbooks", 0)
    ext_read = stats.get("externalWorkbooksRead", 0)
    external_workbooks = {
        "workbooks_referenced": ext_total,
        "workbooks_read_from_disk": ext_read,
        "unread_workbooks": max(0, ext_total - ext_read),
        "interpretation": (
            "Workbooks not read from disk were not opened; dependent cells use "
            "embedded file caches if present, or have no value. "
            "A known cached value does not prove an external file was opened or read."
        ),
    }
    return {
        "review_protocol": review_protocol(),
        "filename": meta.get("filename"),
        # Live native handles are intentionally not returned from an isolated
        # worker. Their API availability says nothing about recalculation.
        "execution": {
            key: value
            for key, value in meta.get("execution", {"status": "unknown"}).items()
            if key in {"status", "phase", "completedPhases", "elapsedSeconds"}
        },
        "recalculation_engine": meta.get("engine", "unspecified"),
        "value_coverage": {
            "scope": meta.get("coverage", {}).get("scope", "not_provided"),
            "total_nodes": meta.get("coverage", {}).get("totalNodes"),
            "counts": {
                key: value.get("count")
                for key, value in meta.get("coverage", {}).get("categories", {}).items()
            },
            "interpretation": (
                "Counts describe graph nodes, not workbook cells. Engine formula "
                "values were recalculated in the worker; they remain independently "
                "unverified. Cache values are separate. A group represents several "
                "cells but counts once; its displayed value belongs to one member."
            ),
            "count_categories_are_value_origin_kinds": False,
        },
        "coverage": meta.get("analysisCoverage", {"status": "not_inspected"}),
        "analysis": {
            "formula_cells": stats.get("totalFormulas"),
            "count_scope": "extracted_formula_cells_not_workbook_total",
            "lineage_nodes": stats.get("totalNodes", 0),
            "lineage_edges": stats.get("totalEdges", 0),
            "grouped_patterns": stats.get("groupedPatterns", 0),
        },
        "sheets": sheets,
        "formula_patterns": formula_patterns,
        "formula_pattern_coverage": {
            "scope": "graph_formula_nodes",
            "total": pattern_total,
            "shown": len(formula_patterns),
            "omitted": pattern_total - len(formula_patterns),
        },
        "graph_connections": _document_connections(graph),
        "defined_names": defined_names,
        "source_defined_names": _document_name_evidence(
            meta.get("definedNameEvidence", {"status": "not_inspected"})
        ),
        "defined_names_in_graph_are_not_source_inventory": True,
        "vba_procedures": vba,
        "vba_source_scope": {
            "code_text": "not_supplied_in_overview",
            "execution": "not_executed",
            "interpretation": (
                "Procedure metadata is not readable full source or an executed "
                "macro trace. No omitted code can be reconstructed from names."
            ),
        },
        "external_workbooks": external_workbooks,
        "value_policy": (
            "Volatile readings marked volatile are deliberately preserved file "
            "snapshots, not engine inability; unknown values and cache mismatch "
            "causes remain unknown."
        ),
        "external_or_unresolved_references": opaque_references,
        "warnings": [
            *meta.get("warnings", []),
            *(context.get("warnings", []) if context else []),
        ],
    }

render_markdown_table

render_markdown_table(
    columns: list[Any],
    rows: list[list[Any]],
    *,
    caption: str | None = None,
) -> str

Render a Markdown pipe table from structured data.

This is the only place in linexcel where table syntax is written.

A column whose cells all parse as numbers is right-aligned (---:), so amounts line up on their decimal separator. Rows shorter than the header are padded, longer ones truncated: a ragged model row can no longer shift every column after it.

Source code in src/linexcel/aidoc.py
def render_markdown_table(
    columns: list[Any],
    rows: list[list[Any]],
    *,
    caption: str | None = None,
) -> str:
    """Render a Markdown pipe table from structured data.

    This is the only place in linexcel where table syntax is written.

    A column whose cells all parse as numbers is right-aligned (``---:``),
    so amounts line up on their decimal separator. Rows shorter than the
    header are padded, longer ones truncated: a ragged model row can no
    longer shift every column after it.
    """
    cols = [_md_cell(c) for c in columns]
    width = len(cols)
    body = [([_md_cell(v) for v in row] + [""] * width)[:width] for row in rows]
    aligns = []
    for j in range(width):
        values = [r[j] for r in body if r[j]]
        numeric = bool(values) and all(_NUMERIC_CELL_RE.fullmatch(v) for v in values)
        aligns.append("---:" if numeric else "---")
    lines: list[str] = []
    if caption:
        lines += [f"*{caption}*", ""]
    lines.append("| " + " | ".join(cols) + " |")
    lines.append("|" + "|".join(aligns) + "|")
    lines += ["| " + " | ".join(r) + " |" for r in body]
    return "\n".join(lines)

document_workbook

document_workbook(
    graph: dict[str, Any],
    *,
    model: str | None = None,
    api_key: str | None = None,
    base_url: str | None = None,
    provider: ProviderLike | None = None,
    language: str = "en",
    usage: TokenUsage | None = None,
    max_tokens: int | None = None,
    token_budget: int | None = None,
    context: dict[str, Any] | None = None,
    validation_results: dict[str, Any] | None = None,
    specialized_review: bool = True,
) -> str

Generate a Markdown overview grounded in the workbook dossier.

Provider resolution (first match wins; no implicit default): 1. provider, a custom LLMProvider instance or callable 2. base_url + model (or LINEXCEL_AI_BASE_URL + LINEXCEL_AI_MODEL), for any OpenAI-compatible endpoint

context is the workbook presentation context, including the sheet previews, comments, merged cells, frozen panes and hidden columns a reader sees when opening the file. Pass it to describe the workbook as it looks, not only as it computes; see :func:build_workbook_dossier.

If a :class:TokenUsage is passed as usage, what the call consumed is accumulated into it. token_budget caps cumulative spend across that accumulator: an already-exhausted budget raises before anything is sent. By default, specialized_review makes two requests: draft, then review against the same source dossier. Both count toward usage. A budget exhausted after the draft prevents the review and no draft is published as reviewed. A final request already in flight may finish above the approximate ceiling; its complete response and cost are retained. max_tokens caps each response, not the two-request document's combined output.

validation_results, when supplied, receives the bounded quotation-check report under workbook, including the raw response. Unsupported comparable quotations and processing limits add a visible qualification; ellipses and numerical illustrations remain explicitly unverified without alerts.

Source code in src/linexcel/aidoc.py
def document_workbook(
    graph: dict[str, Any],
    *,
    model: str | None = None,
    api_key: str | None = None,
    base_url: str | None = None,
    provider: ProviderLike | None = None,
    language: str = "en",
    usage: TokenUsage | None = None,
    max_tokens: int | None = None,
    token_budget: int | None = None,
    context: dict[str, Any] | None = None,
    validation_results: dict[str, Any] | None = None,
    specialized_review: bool = True,
) -> str:
    """Generate a Markdown overview grounded in the workbook dossier.

    Provider resolution (first match wins; no implicit default):
    1. `provider`, a custom LLMProvider instance or callable
    2. `base_url` + `model` (or `LINEXCEL_AI_BASE_URL` + `LINEXCEL_AI_MODEL`),
       for any OpenAI-compatible endpoint

    ``context`` is the workbook presentation context, including the sheet
    previews, comments, merged cells, frozen panes and hidden columns a reader
    sees when opening the file. Pass it to describe the workbook as it looks,
    not only as it computes; see :func:`build_workbook_dossier`.

    If a :class:`TokenUsage` is passed as ``usage``, what the call consumed is
    accumulated into it. ``token_budget`` caps cumulative spend across that
    accumulator: an already-exhausted budget raises before anything is sent.
    By default, ``specialized_review`` makes two requests: draft, then review
    against the same source dossier. Both count toward usage. A budget exhausted
    after the draft prevents the review and no draft is published as reviewed.
    A final request already in flight may finish above the approximate ceiling;
    its complete response and cost are retained. ``max_tokens`` caps each
    response, not the two-request document's combined output.

    ``validation_results``, when supplied, receives the bounded quotation-check
    report under ``workbook``, including the raw response. Unsupported comparable
    quotations and processing limits add a visible qualification; ellipses and
    numerical illustrations remain explicitly unverified without alerts.
    """
    if language not in _LANGUAGES:
        raise ValueError(f"Unsupported language: {language!r}. Use one of {_LANGUAGES}")
    _check_budget(token_budget, usage)
    dossier = build_workbook_dossier(graph, context=context)
    blob = _fit_workbook_dossier(dossier)
    llm = _resolve_provider(
        provider=provider, model=model, api_key=api_key, base_url=base_url
    )
    system = _WORKBOOK_SYSTEM[language]
    user = "Workbook dossier (deterministic, extracted from workbook):\n" + blob
    try:
        text, call_usage, review = _reviewed_document(
            llm,
            system,
            user,
            blob,
            specialized_review=specialized_review,
            max_tokens=max_tokens,
            remaining_budget=None
            if token_budget is None
            else token_budget - (usage.total if usage else 0),
        )
    except AiDocError as exc:
        if usage is not None and exc.usage is not None:
            usage.add(exc.usage)
        if validation_results is not None and exc.review_report is not None:
            validation_results["workbook"] = {
                "status": "failed",
                "specialized_review": exc.review_report,
                "raw_response": None,
            }
        raise
    except Exception as exc:
        raise AiDocError(f"AI documentation failed: {exc}") from exc
    if usage is not None:
        usage.add(call_usage)
    rendered = _insert_tables(text) if text else ""
    if not rendered.strip():
        raise AiDocError("AI returned empty response")
    report = _documentation_report(text, blob)
    report["specialized_review"] = review
    rendered, insertions = render_formula_tokens(rendered, json.loads(blob))
    report["deterministic_formula_insertions"] = insertions
    if validation_results is not None:
        validation_results["workbook"] = report
    return _qualify_documentation(rendered, report, language)

describe_images

describe_images(
    images: Mapping[
        str,
        bytes | str | Path | Iterable[bytes | str | Path],
    ],
    *,
    model: str | None = None,
    api_key: str | None = None,
    base_url: str | None = None,
    provider: ProviderLike | None = None,
    language: str = "en",
    usage: TokenUsage | None = None,
    max_tokens: int | None = None,
    token_budget: int | None = None,
    validation_results: dict[str, Any] | None = None,
    evidence_dir: str | Path | None = None,
) -> dict[str, str]

Describe every native image region with bounded visual observations.

Large screenshots are cropped without resampling into overlapping 1024px regions. Each request contains exactly one native crop, including for multi-image providers. Each response must identify the requested region and short contiguous quotations. Their scope is the exact crop computed by code; the model supplies no geometry. Rendering is deterministic, with no further model-generated summary. This validates scope, not visual truth. Exact uniform or fully transparent decoded crops are resolved locally: their empty text observation is not a model response and has no provider receipt. Nonuniform pixels always require the model.

validation_results retains original/crop hashes, coordinates, raw responses and request identities, including one optional complete retry for invalid regional JSON. Both attempts retain their full raw response and consumption; no reply is truncated or repaired. evidence_dir saves the exact sent crops. Multiple pages belonging to one sheet are processed. A sheet is returned only if every page and region completes; partial evidence is retained, but cannot silently become a complete screenshot description.

Source code in src/linexcel/aidoc.py
def describe_images(
    images: Mapping[str, bytes | str | Path | Iterable[bytes | str | Path]],
    *,
    model: str | None = None,
    api_key: str | None = None,
    base_url: str | None = None,
    provider: ProviderLike | None = None,
    language: str = "en",
    usage: TokenUsage | None = None,
    max_tokens: int | None = None,
    token_budget: int | None = None,
    validation_results: dict[str, Any] | None = None,
    evidence_dir: str | Path | None = None,
) -> dict[str, str]:
    """Describe every native image region with bounded visual observations.

    Large screenshots are cropped without resampling into overlapping 1024px
    regions. Each request contains exactly one native crop, including for
    multi-image providers. Each response must identify the requested
    region and short contiguous quotations. Their scope is the exact
    crop computed by code; the model supplies no geometry. Rendering is
    deterministic, with no further model-generated summary. This validates
    scope, not visual truth. Exact uniform or fully transparent decoded crops
    are resolved locally: their empty text observation is not a model response
    and has no provider receipt. Nonuniform pixels always require the model.

    ``validation_results`` retains original/crop hashes, coordinates, raw
    responses and request identities, including one optional complete retry
    for invalid regional JSON. Both attempts retain their full raw response
    and consumption; no reply is truncated or repaired. ``evidence_dir`` saves
    the exact sent crops. Multiple pages belonging to one sheet are processed. A sheet
    is returned only if every page and region completes; partial evidence is
    retained, but cannot silently become a complete screenshot description.
    """
    from linexcel.vision_evidence import (
        BATCH_SIZE,
        VisionEvidenceError,
        batch_prompt,
        persist_image,
        prepare_image,
        render_observations,
        uniform_region_observations,
    )

    if language not in _LANGUAGES:
        raise ValueError(f"Unsupported language: {language!r}. Use one of {_LANGUAGES}")
    if not images:
        return {}
    llm = None
    system = _VISION_SYSTEM[language]
    accumulator = usage if usage is not None else TokenUsage()
    described: dict[str, str] = {}
    failed: list[str] = []
    for name, image in images.items():
        report: dict[str, Any] = {
            "status": "incomplete",
            "language": language,
            "pages": [],
            "factual_certification": False,
        }
        if validation_results is not None:
            validation_results[name] = report
        try:
            sources = [image] if isinstance(image, bytes | str | Path) else list(image)
            if not sources:
                raise VisionEvidenceError("No image pages supplied")
            report["expected_pages"] = len(sources)
            for page_number, source in enumerate(sources, 1):
                payload, _ = _image_payload(name, source)
                native = prepare_image(payload)
                metadata = (
                    persist_image(native, Path(evidence_dir))
                    if evidence_dir is not None
                    else native.metadata()
                )
                page: dict[str, Any] = {
                    "evidence": metadata,
                    "batches": [],
                    "observations": [],
                    "page": page_number,
                    "source_path": (
                        str(Path(source).resolve())
                        if not isinstance(source, bytes)
                        else None
                    ),
                    "completed_regions": [],
                    "model_regions": [],
                    "deterministic_regions": [],
                }
                report["pages"].append(page)
                size = BATCH_SIZE
                for offset in range(0, len(native.regions), size):
                    regions = list(native.regions[offset : offset + size])
                    batch: dict[str, Any] = {
                        "id": f"page-{page_number}-batch-{offset // size}",
                        "region_ids": [region.id for region in regions],
                        "original_sha256": native.sha256,
                        "images": [region.metadata() for region in regions],
                        "status": "pending",
                    }
                    page["batches"].append(batch)
                    for region in regions:
                        if len(region.payload) > MAX_IMAGE_BYTES:
                            raise VisionEvidenceError(
                                f"{name}/{region.id}: crop exceeds image byte ceiling"
                            )
                    if all(r.text_visibility != "not_determined" for r in regions):
                        observations = uniform_region_observations(regions)
                        batch.update(
                            {
                                "status": "complete",
                                "resolution": "deterministic_pixels",
                                "observations": observations,
                                "attempts": [],
                                "usage_total": vars(TokenUsage()).copy(),
                                "provider_request_required": False,
                            }
                        )
                        page["observations"].extend(observations)
                        page["completed_regions"].extend(r.id for r in regions)
                        page["deterministic_regions"].extend(r.id for r in regions)
                        continue
                    _check_budget(token_budget, accumulator)
                    if llm is None:
                        llm = _resolve_provider(
                            provider=provider,
                            model=model,
                            api_key=api_key,
                            base_url=base_url,
                        )
                    if not isinstance(llm, VisionProvider | MultiImageVisionProvider):
                        raise AiDocError(
                            f"{type(llm).__name__} cannot be handed an image: "
                            "describing screenshots needs a provider exposing "
                            "generate_with_image(system_prompt, user_prompt, image, "
                            "*, media_type). The built-in "
                            "OpenAI-compatible client does; "
                            "point it at a multimodal model."
                        )
                    prompt = batch_prompt(name, page_number, native, regions)
                    batch.update(
                        {
                            "resolution": "model",
                            "provider_request_required": True,
                            "user_prompt": prompt,
                            "json_prompt_sha256": hashlib.sha256(
                                prompt.encode()
                            ).hexdigest(),
                            "prompt_text_sha256": hashlib.sha256(
                                (system + "\n\n" + prompt).encode()
                            ).hexdigest(),
                            "system_prompt_sha256": hashlib.sha256(
                                system.encode()
                            ).hexdigest(),
                        }
                    )
                    _check_budget(token_budget, accumulator)
                    observations = _describe_native_batch(
                        llm,
                        system,
                        prompt,
                        native,
                        regions,
                        batch,
                        accumulator,
                        token_budget=token_budget,
                        max_tokens=max_tokens,
                    )
                    page["observations"].extend(observations)
                    page["completed_regions"].extend(region.id for region in regions)
                    page["model_regions"].extend(region.id for region in regions)
                page["region_coverage_complete"] = set(page["completed_regions"]) == {
                    region.id for region in native.regions
                }
            report["status"] = "complete"
            described[name] = render_observations(report["pages"], language)
        except (AiDocError, OSError, VisionEvidenceError) as exc:
            report["error"] = str(exc)
            failed.append(f"{name} ({exc})")
    if failed and not described:
        raise AiDocError(
            "No screenshot could be described: " + "; ".join(failed), usage=accumulator
        )
    if failed:
        warnings.warn(
            f"{len(failed)} screenshot(s) not described: " + "; ".join(failed),
            UserWarning,
            stacklevel=2,
        )
    return described

document_nodes

document_nodes(
    graph: dict[str, Any],
    node_ids: list[str],
    *,
    model: str | None = None,
    api_key: str | None = None,
    base_url: str | None = None,
    provider: ProviderLike | None = None,
    language: str = "en",
    max_workers: int = 4,
    usage: TokenUsage | None = None,
    max_tokens: int | None = None,
    token_budget: int | None = None,
    validation_results: dict[str, Any] | None = None,
    specialized_review: bool = True,
) -> dict[str, str]

Document the requested nodes, returns {node_id: markdown}.

Provider resolution is the same as :func:document_workbook (no implicit default; see :func:_resolve_provider).

Nodes are documented concurrently (max_workers in-flight requests; raise it if the provider's rate limits allow). Documenting a large workbook is a long, often billed operation, so a node that fails does not discard the ones that succeeded: the successful cards are returned and a :class:UserWarning reports how many nodes were dropped. :class:AiDocError is raised only when every node failed.

specialized_review=True makes two requests per node: draft, then bounded editorial review by the same provider. Both requests count toward usage. An incomplete or unaffordable review never publishes the draft as reviewed. Set it to False explicitly to request only one draft per node.

If a :class:TokenUsage is passed as usage, consumed tokens are accumulated into it, including usage reported for rejected responses and calls in a run that later fails. Tokens already spent are still billed.

token_budget is a ceiling on the total tokens the run may spend, input and output together, counted against usage so several calls sharing one accumulator share one ceiling. It is enforced between requests, the only point at which a cost is known: nodes still queued when the tally reaches the budget are never sent, and a :class:UserWarning reports how many were left undocumented. Requests already in flight are allowed to finish. Each active node has its own remaining-budget snapshot, so the final tally may include both phases of up to max_workers active nodes. Set the ceiling as an order of magnitude, not to the token. Use max_tokens to bound each individual response, not a document's combined output.

validation_results, when supplied, receives a bounded quotation-check report keyed by node ID, including raw responses. Formula quotations without source support are visibly qualified, not silently corrected. General prose remains unverified even when every inspected quotation has source support.

Source code in src/linexcel/aidoc.py
def document_nodes(
    graph: dict[str, Any],
    node_ids: list[str],
    *,
    model: str | None = None,
    api_key: str | None = None,
    base_url: str | None = None,
    provider: ProviderLike | None = None,
    language: str = "en",
    max_workers: int = 4,
    usage: TokenUsage | None = None,
    max_tokens: int | None = None,
    token_budget: int | None = None,
    validation_results: dict[str, Any] | None = None,
    specialized_review: bool = True,
) -> dict[str, str]:
    """Document the requested nodes, returns {node_id: markdown}.

    Provider resolution is the same as :func:`document_workbook` (no implicit
    default; see :func:`_resolve_provider`).

    Nodes are documented concurrently (``max_workers`` in-flight requests;
    raise it if the provider's rate limits allow). Documenting a large
    workbook is a long, often billed operation, so a node that fails does not
    discard the ones that succeeded: the successful cards are returned and a
    :class:`UserWarning` reports how many nodes were dropped.
    :class:`AiDocError` is raised only when *every* node failed.

    ``specialized_review=True`` makes two requests per node: draft, then bounded
    editorial review by the same provider. Both requests count toward usage.
    An incomplete or unaffordable review never publishes the draft as reviewed.
    Set it to ``False`` explicitly to request only one draft per node.

    If a :class:`TokenUsage` is passed as ``usage``, consumed tokens are
    accumulated into it, including usage reported for rejected responses and
    calls in a run that later fails. Tokens already spent are still billed.

    ``token_budget`` is a ceiling on the **total** tokens the run may spend,
    input and output together, counted against ``usage`` so several calls
    sharing one accumulator share one ceiling. It is enforced between requests,
    the only point at which a cost is known: nodes still queued when the tally
    reaches the budget are never sent, and a :class:`UserWarning` reports how
    many were left undocumented. Requests already in flight are allowed to
    finish. Each active node has its own remaining-budget snapshot, so the final
    tally may include both phases of up to ``max_workers`` active nodes. Set the
    ceiling as an order of magnitude, not to the token. Use ``max_tokens`` to
    bound each individual response, not a document's combined output.

    ``validation_results``, when supplied, receives a bounded quotation-check
    report keyed by node ID, including raw responses. Formula quotations without
    source support are visibly qualified, not silently corrected. General prose
    remains unverified even when every inspected quotation has source support.
    """
    if language not in _LANGUAGES:
        raise ValueError(f"Unsupported language: {language!r}. Use one of {_LANGUAGES}")
    if max_workers < 1:
        raise ValueError("max_workers must be >= 1")
    _check_budget(token_budget, usage)
    llm = _resolve_provider(
        provider=provider, model=model, api_key=api_key, base_url=base_url
    )
    system = _SYSTEM[language]
    docs: dict[str, str] = {}
    dossiers = []
    index = _index_dossiers(graph)
    for nid in node_ids:
        d = _build_dossier(index, nid)
        if d is not None:
            blob = _fit_node_dossier(d)
            dossiers.append((nid, blob))
    if not dossiers:
        return docs

    def _doc_one(nid_blob: tuple[str, str]) -> tuple[str, str, TokenUsage, dict]:
        nid, blob = nid_blob
        user = "Lineage dossier (deterministic, extracted from workbook):\n" + blob
        text, call_usage, review = _reviewed_document(
            llm,
            system,
            user,
            blob,
            specialized_review=specialized_review,
            max_tokens=max_tokens,
            remaining_budget=None
            if token_budget is None
            else token_budget - tally.total,
        )
        rendered = _insert_tables(text) if text else ""
        if not rendered.strip():
            raise AiDocError("AI returned empty response", usage=call_usage)
        report = _documentation_report(text, blob)
        report["specialized_review"] = review
        rendered, insertions = render_formula_tokens(rendered, json.loads(blob))
        report["deterministic_formula_insertions"] = insertions
        return (
            nid,
            _qualify_documentation(rendered, report, language),
            call_usage,
            report,
        )

    # The tally drives the budget, so it must exist even when the caller wants
    # no accumulator of their own; when they do pass one, it *is* the tally.
    tally = usage if usage is not None else TokenUsage()
    failures: list[tuple[str, Exception]] = []
    queue = iter(dossiers)
    with ThreadPoolExecutor(max_workers=max_workers) as pool:
        futures: dict[Future[tuple[str, str, TokenUsage, dict]], str] = {}

        def _submit_next() -> bool:
            """Queue one more node unless the budget is spent or none is left."""
            if token_budget is not None and tally.total >= token_budget:
                return False
            item = next(queue, None)
            if item is None:
                return False
            futures[pool.submit(_doc_one, item)] = item[0]
            return True

        # Nodes are submitted a few at a time rather than all at once: a budget
        # can only stop work that has not been handed to the pool yet.
        for _ in range(max_workers):
            if not _submit_next():
                break
        # Accumulating here rather than inside the workers keeps `tally` free of
        # races: this loop is the single consumer of the pool's results.
        while futures:
            done, _pending = wait(list(futures), return_when=FIRST_COMPLETED)
            for fut in done:
                node_id = futures.pop(fut)
                try:
                    nid, text, call_usage, report = fut.result()
                except Exception as exc:
                    if isinstance(exc, AiDocError) and exc.usage is not None:
                        tally.add(exc.usage)
                    if (
                        validation_results is not None
                        and isinstance(exc, AiDocError)
                        and exc.review_report is not None
                    ):
                        validation_results[node_id] = {
                            "status": "failed",
                            "specialized_review": exc.review_report,
                            "raw_response": None,
                        }
                    failures.append((node_id, exc))
                    continue
                docs[nid] = text
                if validation_results is not None:
                    validation_results[nid] = report
                tally.add(call_usage)
            for _ in range(len(done)):
                if not _submit_next():
                    break

    # Only an exhausted budget can leave the queue undrained.
    unsent = sum(1 for _ in queue) if token_budget is not None else 0
    if unsent:
        warnings.warn(
            f"Token budget of {token_budget:,} tokens reached after "
            f"{tally.total:,}: {len(docs)} of {len(dossiers)} nodes documented, "
            f"{unsent} never sent. Raise token_budget to document the rest.",
            UserWarning,
            stacklevel=2,
        )

    if failures and not docs:
        node_id, exc = failures[0]
        raise AiDocError(
            f"AI documentation failed for all {len(failures)} nodes "
            f"(first error, node {node_id}): {exc}"
        ) from exc
    if failures:
        node_id, exc = failures[0]
        warnings.warn(
            f"AI documentation failed for {len(failures)} of {len(dossiers)} "
            f"nodes; {len(docs)} cards returned. First error (node {node_id}): "
            f"{exc}",
            UserWarning,
            stacklevel=2,
        )
    return docs