Skip to content

RuntimeConfig

🛈 DocStrings

Fully initialized runtime configuration.

This represents the "live" state of a Config, with all components initialized and ready to use. It provides a clean interface to access and manage runtime resources without exposing internal registries.

Source code in src/llmling/config/runtime.py
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 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
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
class RuntimeConfig:
    """Fully initialized runtime configuration.

    This represents the "live" state of a Config, with all components
    initialized and ready to use. It provides a clean interface to
    access and manage runtime resources without exposing internal registries.
    """

    def __init__(
        self,
        config: Config,
        *,
        loader_registry: ResourceLoaderRegistry,
        processor_registry: ProcessorRegistry,
        resource_registry: ResourceRegistry,
        prompt_registry: PromptRegistry,
        tool_registry: ToolRegistry,
    ) -> None:
        """Initialize with config and registries.

        Args:
            config: Original static configuration
            loader_registry: Registry for resource loaders
            processor_registry: Registry for content processors
            resource_registry: Registry for resources
            prompt_registry: Registry for prompts
            tool_registry: Registry for tools
        """
        from llmling.depmanager import DependencyManager

        super().__init__()
        self._config = config
        self._loader_registry = loader_registry
        self._processor_registry = processor_registry
        self._resource_registry = resource_registry
        self._prompt_registry = prompt_registry
        self._tool_registry = tool_registry
        self._initialized = False
        # Register builtin processors
        proc = Jinja2Processor(config.global_settings.jinja_environment)
        self._processor_registry["jinja_template"] = proc
        settings = self._config.global_settings
        self._dep_manager = DependencyManager(
            prefer_uv=settings.prefer_uv,
            requirements=settings.requirements,
            extra_paths=settings.extra_paths,
            pip_index_url=str(settings.pip_index_url) if settings.pip_index_url else None,
            scripts=settings.scripts,
        )

    def __enter__(self) -> Self:
        """Synchronous context manager entry."""
        self._dep_manager.__enter__()
        # Initialize registries if not already done
        import asyncio

        if not self._initialized:
            loop = asyncio.new_event_loop()
            try:
                loop.run_until_complete(self._initialize_registries())
                self._initialized = True
            finally:
                loop.close()
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: types.TracebackType | None,
    ) -> None:
        """Synchronous context manager exit."""
        self._dep_manager.__exit__(exc_type, exc_val, exc_tb)

    async def __aenter__(self) -> Self:
        """Initialize dependencies and registries."""
        # Check and set initialized flag atomically before ANY async op
        # This should allow caeses where same runtime gets initialized multiple times
        needs_init = not self._initialized
        self._initialized = True

        if needs_init:
            await self._dep_manager.__aenter__()
            await self._initialize_registries()
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: types.TracebackType | None,
    ) -> None:
        """Clean up dependencies and registries."""
        try:
            await self.shutdown()
        finally:
            await self._dep_manager.__aexit__(exc_type, exc_val, exc_tb)

    def _register_default_components(self) -> None:
        """Register all default components and config items."""
        self._loader_registry.register_default_loaders()
        for name, proc_config in self._config.context_processors.items():
            self._processor_registry[name] = proc_config

        for name, resource in self._config.resources.items():
            self._resource_registry[name] = resource

        for name, tool_config in self._config.tools.items():
            self._tool_registry[name] = LLMCallableTool.from_callable(
                tool_config.import_path,
                name_override=tool_config.name,
                description_override=tool_config.description,
                hints=tool_config.hints,
            )

        self._initialize_toolsets()

        for name, prompt in self._config.prompts.items():
            if isinstance(prompt, DynamicPrompt):
                # Convert completion function import paths to actual functions
                # TODO: we are setting .completions to a non-allowed type here
                prompt.completions = prompt.get_completion_functions()  # type: ignore
                args, desc = extract_function_info(prompt.import_path, prompt.completions)
                prompt.arguments = args
                if not prompt.description:
                    prompt.description = desc

            self._prompt_registry[name] = prompt

    def _initialize_toolsets(self) -> None:
        """Initialize toolsets from config."""
        for name, config in self._config.toolsets.items():
            try:
                toolset = toolset_config_to_toolset(config)
                for tool in toolset.get_llm_callable_tools():
                    # tool_name = f"{name}.{tool.name}"
                    tool_name = tool.name
                    if tool_name in self._tool_registry:
                        msg = "Tool %s from toolset %s overlaps with existing tool"
                        logger.warning(msg, tool.name, name)
                        continue
                    self._tool_registry[tool_name] = tool

            except Exception:
                logger.exception("Failed to load toolset: %s", name)

    async def _initialize_registries(self) -> None:
        """Initialize all registries."""
        self._register_default_components()
        await self.startup()

    @classmethod
    async def create(cls, config: Config) -> Self:
        """Create and initialize a runtime configuration.

        This is a convenience method that ensures proper initialization
        when not using the async context manager.

        Args:
            config: Static configuration to initialize from

        Returns:
            Initialized runtime configuration
        """
        runtime = cls.from_config(config)
        async with runtime as initialized:
            return initialized

    @classmethod
    @asynccontextmanager
    async def open(
        cls,
        source: JoinablePathLike | Config,
        *,
        validate: bool = True,
        strict: bool = False,
    ) -> AsyncGenerator[RuntimeConfig]:
        """Create and manage a runtime configuration asynchronously.

        This is the primary way to create and use a RuntimeConfig. It ensures proper
        initialization and cleanup of all resources and provides an async context
        manager interface.

        Args:
            source: Either a path to a configuration file or a Config object.
                   File paths can be strings or PathLike objects.
            validate: Whether to validate the configuration. When True, performs
                     additional checks beyond basic schema validation.
            strict: Whether to raise exceptions on validation warnings. Only
                   applicable when validate=True.

        Yields:
            Fully initialized RuntimeConfig instance

        Raises:
            ConfigError: If configuration is invalid or validation fails in strict mode
            TypeError: If source is neither a path nor a Config object
            OSError: If configuration file cannot be accessed

        Example:
            ```python
            async with RuntimeConfig.open("config.yml") as runtime:
                resource = await runtime.load_resource("example")
            ```

        Note:
            The context manager ensures that all resources are properly initialized
            before use and cleaned up afterwards, even if an error occurs.
        """
        runtime = prepare_runtime(cls, source, validate=validate, strict=strict)
        async with runtime as r:
            yield r

    @classmethod
    @contextmanager
    def open_sync(
        cls,
        source: JoinablePathLike | Config,
        *,
        validate: bool = True,
        strict: bool = False,
    ) -> Generator[RuntimeConfig]:
        """Create and manage a runtime configuration synchronously.

        This is the synchronous version of open(). It provides the same functionality
        but uses a standard synchronous context manager interface. Use this if you
        don't need async functionality.

        Args:
            source: Either a path to a configuration file or a Config object.
                   File paths can be strings or PathLike objects.
            validate: Whether to validate the configuration. When True, performs
                     additional checks beyond basic schema validation.
            strict: Whether to raise exceptions on validation warnings. Only
                   applicable when validate=True.

        Yields:
            Fully initialized RuntimeConfig instance

        Raises:
            ConfigError: If configuration is invalid or validation fails in strict mode
            TypeError: If source is neither a path nor a Config object
            OSError: If configuration file cannot be accessed

        Example:
            ```python
            with RuntimeConfig.open_sync("config.yml") as runtime:
                resource = runtime.load_resource_sync("example")
            ```

        Note:
            The context manager ensures that all resources are properly initialized
            before use and cleaned up afterwards, even if an error occurs.
        """
        runtime = prepare_runtime(cls, source, validate=validate, strict=strict)
        with runtime:
            yield runtime

    @classmethod
    def from_file(cls, path: JoinablePathLike) -> Self:
        """Convenience function to directly create runtime config from a file.

        Args:
            path: Path to the config file

        Returns:
            Initialized runtime configuration
        """
        manager = ConfigManager.load(path)
        return cls.from_config(manager.config)

    @classmethod
    def from_config(cls, config: Config | JoinablePathLike) -> Self:
        """Create a fully initialized runtime config from static config.

        Args:
            config: Static configuration to initialize from

        Returns:
            Initialized runtime configuration
        """
        if isinstance(config, str | os.PathLike | UPath):
            config = ConfigManager.load(config).config
        loader_registry = ResourceLoaderRegistry()
        processor_registry = ProcessorRegistry()
        resource_registry = ResourceRegistry(
            loader_registry=loader_registry,
            processor_registry=processor_registry,
        )
        prompt_registry = PromptRegistry()
        tool_registry = ToolRegistry()
        assert isinstance(config, Config)
        runtime = cls(
            config=config,
            loader_registry=loader_registry,
            processor_registry=processor_registry,
            resource_registry=resource_registry,
            prompt_registry=prompt_registry,
            tool_registry=tool_registry,
        )
        from llmling.config.llm_tools import LLMTools

        llm_tools = LLMTools(runtime)
        capabilities = config.global_settings.llm_capabilities

        # Register enabled capabilities
        if capabilities.load_resource:
            tool_registry["load_resource"] = llm_tools.load_resource
        if capabilities.get_resources:
            tool_registry["get_resources"] = llm_tools.get_resources
        if capabilities.install_package:
            tool_registry["install_package"] = llm_tools.install_package
        if capabilities.register_tool:
            tool_registry["register_tool"] = llm_tools.register_tool
        if capabilities.register_code_tool:
            tool_registry["register_code_tool"] = llm_tools.register_code_tool
        if capabilities.chain_tools:
            tool_registry["chain"] = ChainTool(runtime)
        return runtime

    async def startup(self) -> None:
        """Start all runtime components."""
        await self._processor_registry.startup()
        await self._tool_registry.startup()
        await self._resource_registry.startup()
        await self._prompt_registry.startup()

    async def shutdown(self) -> None:
        """Shut down all runtime components."""
        await self._prompt_registry.shutdown()
        await self._resource_registry.shutdown()
        await self._tool_registry.shutdown()
        await self._processor_registry.shutdown()

    # Resource Management
    async def load_resource(self, name: str) -> LoadedResource:
        """Load a resource by its registered name.

        Args:
            name: Name of the resource as registered in configuration

        Returns:
            LoadedResource containing content and metadata

        Raises:
            ResourceError: If resource doesn't exist or cannot be loaded
        """
        return await self._resource_registry.load(name)

    async def resolve_resource_uri(self, uri_or_name: str) -> tuple[str, BaseResource]:
        """Resolve a resource identifier to a proper URI and resource.

        Args:
            uri_or_name: Can be:
                - Resource name: "test.txt"
                - Full URI: "file:///test.txt"
                - Local path: "/path/to/file.txt"

        Returns:
            Tuple of (resolved URI, resource object)

        Raises:
            ResourceError: If resolution fails
        """
        logger.debug("Resolving resource identifier: %s", uri_or_name)

        # 1. If it's already a URI, use directly
        if "://" in uri_or_name:
            logger.debug("Using direct URI")
            loader = self._loader_registry.find_loader_for_uri(uri_or_name)
            name = loader.get_name_from_uri(uri_or_name)
            if name in self._resource_registry:
                return uri_or_name, self._resource_registry[name]
            # Create temporary resource for the URI
            resource: BaseResource = PathResource(path=uri_or_name)  # pyright: ignore
            return uri_or_name, resource

        # 2. Try as resource name
        try:
            logger.debug("Trying as resource name")
            resource = self._resource_registry[uri_or_name]
            loader = self._loader_registry.get_loader(resource)
            loader = loader.create(resource, uri_or_name)  # Create instance
            uri = loader.create_uri(name=uri_or_name)
        except KeyError:
            pass
        else:
            return uri, resource

        # 3. If it looks like a path, try as file
        if "/" in uri_or_name or "\\" in uri_or_name or "." in uri_or_name:
            try:
                logger.debug("Trying as file path")
                resource = PathResource(path=uri_or_name)  # pyright: ignore
                loader = PathResourceLoader.create(resource, uri_or_name)
                uri = loader.create_uri(name=uri_or_name)
            except Exception as exc:  # noqa: BLE001
                logger.debug("Failed to create file URI: %s", exc)
            else:
                return uri, resource
        msg = f"Could not resolve resource {uri_or_name!r}. Expected resource name or path."
        raise exceptions.ResourceError(msg)

    async def load_resource_by_uri(self, uri: str) -> LoadedResource:
        """Load a resource by URI."""
        try:
            resolved_uri, resource = await self.resolve_resource_uri(uri)
            loader = self._loader_registry.get_loader(resource)
            name = loader.get_name_from_uri(resolved_uri)
            loader = loader.create(resource, name)
            async for res in loader.load(processor_registry=self._processor_registry):
                return res  # Return first resource
            msg = "No resources loaded"
            raise exceptions.ResourceError(msg)  # noqa: TRY301
        except Exception as exc:
            msg = f"Failed to load resource from URI {uri}"
            raise exceptions.ResourceError(msg) from exc

    def list_resource_names(self) -> Sequence[str]:
        """List all available resource names.

        Returns:
            List of registered resource names
        """
        return self._resource_registry.list_items()

    def list_resource_uris(self) -> Sequence[str]:
        """List all available resource URIs.

        Returns:
            List of registered resource names
        """
        return [res.uri for res in self._resource_registry.values() if res.uri]

    def get_resource_uri(self, name: str) -> str:
        """Get URI for a resource.

        Args:
            name: Name of the resource

        Returns:
            URI for the resource

        Raises:
            ResourceError: If resource not found
        """
        return self._resource_registry.get_uri(name)

    def get_resource(self, name_or_uri: str) -> BaseResource:
        """Get a resource configuration by name or URI.

        Args:
            name_or_uri: Name of the resource or its URI. URIs must start with a scheme
                (e.g., "file://", "text://", etc.)

        Returns:
            The resource configuration

        Raises:
            ResourceError: If resource not found
        """
        if "://" in name_or_uri:  # It's a URI
            for resource in self._resource_registry.values():
                if resource.uri == name_or_uri:
                    return resource
            msg = f"No resource found with URI: {name_or_uri}"
            raise exceptions.ResourceError(msg)
        return self._resource_registry[name_or_uri]

    def get_resources(self) -> Sequence[BaseResource]:
        """Get all registered resource configurations.

        Returns:
            List of all resource configurations
        """
        return list(self._resource_registry.values())

    async def register_resource_by_loader(
        self,
        loader_type: str,
        name: str,
        *,
        description: str = "",
        **params: Any,
    ) -> BaseResource:
        """Register a resource using a loader type.

        Provides a parameter-based interface for registering resources
        without requiring resource objects.

        Args:
            loader_type: Type of loader to use ("path", "text", "cli", etc.)
            name: Name for the resource
            description: Optional description
            **params: Loader-specific parameters

        Example:
            await runtime.register_resource_by_loader(
                "path",
                "readme",
                description="Project readme",
                path="README.md"
            )

            await runtime.register_resource_by_loader(
                "text",
                "greeting",
                content="Hello, world!"
            )
        """
        try:
            # Get loader class from registry
            loader_cls = self._loader_registry[loader_type]

            # Get the resource class from the loader
            resource_class = loader_cls.context_class

            # Create resource instance with just the essential fields
            resource = resource_class(description=description, **params)
            self._resource_registry.register(name, resource)
        except KeyError as exc:
            msg = f"Unknown loader type: {loader_type}"
            raise exceptions.ResourceError(msg) from exc
        except Exception as exc:
            msg = f"Failed to create resource: {exc}"
            raise exceptions.ResourceError(msg) from exc
        else:
            return resource

    def register_resource(
        self,
        name: str,
        resource: BaseResource,
        *,
        replace: bool = False,
    ) -> None:
        """Register a new resource.

        Args:
            name: Name for the resource
            resource: Resource to register
            replace: Whether to replace existing resource

        Raises:
            ResourceError: If name exists and replace=False
        """
        self._resource_registry.register(name, resource, replace=replace)

    def get_resource_loader(self, resource: BaseResource) -> Any:  # type: ignore[return]
        """Get loader for a resource type.

        Args:
            resource: Resource to get loader for

        Returns:
            Resource loader instance

        Raises:
            LoaderError: If no loader found for resource type
        """
        return self._loader_registry.get_loader(resource)

    # Tool Management
    def list_tool_names(self) -> Sequence[str]:
        """List all available tool names.

        Returns:
            List of registered tool names
        """
        return self._tool_registry.list_items()

    @property
    def tools(self) -> dict[str, LLMCallableTool]:
        """Get all registered tools.

        Returns:
            Dictionary mapping tool names to tools
        """
        return dict(self._tool_registry)

    async def execute_tool(
        self,
        _name: str,  # prefixed with "_" to avoid name collisions
        **params: Any,
    ) -> Any:
        """Execute a tool by name.

        Args:
            _name: Name of the tool to execute
            **params: Parameters to pass to the tool

        Returns:
            Tool execution result

        Raises:
            ToolError: If tool execution fails
        """
        return await self._tool_registry.execute(_name, **params)

    def get_tool(self, name: str) -> LLMCallableTool:
        """Get a tool by name.

        Args:
            name: Name of the tool

        Returns:
            The tool

        Raises:
            ToolError: If tool not found
        """
        return self._tool_registry[name]

    def get_tools(self) -> Sequence[LLMCallableTool]:
        """Get all registered tools.

        Returns:
            List of all tools
        """
        return list(self._tool_registry.values())

    async def install_package(
        self,
        package: str,
    ) -> str:
        """Install a Python package using the dependency manager.

        Package specifications follow PIP format (e.g. "requests>=2.28.0").

        Args:
            package: Package specification to install

        Returns:
            Message confirming the installation

        Raises:
            ToolError: If installation fails or package spec is invalid

        Example:
            >>> await runtime.install_package("requests>=2.28.0")
        """
        try:
            self._dep_manager.install_dependency(package)
            return f"Successfully installed package: {package}"  # noqa: TRY300
        except Exception as exc:
            msg = f"Failed to install package: {exc}"
            raise ToolError(msg) from exc

    async def register_tool(
        self,
        function: str | Callable[..., Any],
        name: str | None = None,
        description: str | None = None,
        *,
        auto_install: bool = False,
    ) -> str:
        """Register a new tool from a function or import path.

        Args:
            function: Function to register (callable or import path)
            name: Optional name override (uses function name if None)
            description: Optional description override (uses docstring if None)
            auto_install: Whether to attempt installing missing package

        Returns:
            Message confirming the registration

        Raises:
            ToolError: If registration fails

        Example:
            >>> await runtime.register_tool("webbrowser.open", "open_url")
            >>> await runtime.register_tool(my_function)
        """
        try:
            if auto_install and isinstance(function, str):
                # Try to import root module, install if missing
                package = function.split(".")[0]
                try:
                    importlib.import_module(package)
                except ImportError:
                    logger.info("Attempting to install package: %s", package)
                    await self.install_package(package)

            tool = LLMCallableTool.from_callable(
                function, name_override=name, description_override=description
            )
            self._tool_registry.register(name or tool.name, tool)
            source = (
                function
                if isinstance(function, str)
                else getattr(function, "__name__", str(function))
            )
        except Exception as exc:
            msg = f"Failed to register tool: {exc}"
            raise ToolError(msg) from exc
        else:
            return f"Successfully registered tool: {tool.name} from {source}"

    async def register_code_tool(
        self,
        name: str,
        code: str,
        description: str | None = None,
    ) -> str:
        """Register a new tool from Python code.

        The provided code should define a function that will be converted into a tool.
        The function's docstring will be used as the tool's description if no description
        is provided.

        Args:
            name: Name for the new tool
            code: Python code defining the tool function
            description: Optional description override

        Returns:
            Message confirming the registration

        Raises:
            ToolError: If registration fails

        Example:
            >>> code = '''
            ... async def count_words(text: str) -> dict[str, int]:
            ...     words = text.split()
            ...     return {"total": len(words)}
            ... '''
            >>> await runtime.register_code_tool("word_count", code)
        """
        try:
            namespace: dict[str, Any] = {}
            exec(code, namespace)
            func = next((v for v in namespace.values() if callable(v)), None)
            if not func:
                msg = "No callable found in provided code"
                raise ValueError(msg)  # noqa: TRY301

            tool = LLMCallableTool.from_callable(
                func, name_override=name, description_override=description
            )
            self._tool_registry.register(name, tool)
            return f"Successfully registered tool: {name}"  # noqa: TRY300

        except Exception as exc:
            msg = f"Failed to register tool: {exc}"
            raise ToolError(msg) from exc

    # Prompt Management
    def list_prompt_names(self) -> Sequence[str]:
        """List all available prompt names.

        Returns:
            List of registered prompt names
        """
        return self._prompt_registry.list_items()

    def register_dynamic_prompt(
        self,
        name: str,
        fn: str | Callable[..., Any],
        *,
        description: str | None = None,
        template: str | None = None,
        replace: bool = False,
    ) -> None:
        """Register a function-based prompt.

        Args:
            name: Name to register under
            fn: Function or import path (e.g., "module.submodule.function")
            description: Optional description (extracted from docstring if not provided)
            template: Optional template for formatting output
            replace: Whether to replace existing prompt

        Example:
            >>> def get_info(url: str) -> str:
            ...     '''Fetch info from URL.'''
            ...     return "info"
            ...
            >>> runtime.register_dynamic_prompt("fetch", get_info)
            >>> # or
            >>> runtime.register_dynamic_prompt(
            ...     "github",
            ...     "my_module.get_github_info",
            ...     description="Fetch GitHub repository information"
            ... )
        """
        try:
            prompt = DynamicPrompt.from_callable(
                fn,
                name_override=name,
                description_override=description,
                template_override=template,
            )
            self._prompt_registry.register(name, prompt, replace=replace)

        except Exception as exc:
            msg = f"Failed to register dynamic prompt {name!r}: {exc}"
            raise exceptions.LLMLingError(msg) from exc

    def register_static_prompt(
        self,
        name: str,
        content: str,
        description: str | None = None,
        *,
        replace: bool = False,
    ) -> None:
        r"""Register a static prompt with text content.

        A static prompt is a simple text template that can be used as-is or with
        Python's string formatting (using {placeholder} syntax).

        Args:
            name: Name to register under
            content: Prompt text content
            description: Optional description of what the prompt does
            replace: Whether to replace existing prompt

        Example:
            >>> runtime.register_static_prompt(
            ...     "summarize",
            ...     "Please summarize the following text in 3 bullet points:\\n{text}",
            ...     description="Create a bullet-point summary",
            ... )
            >>> runtime.register_static_prompt(
            ...     "greet",
            ...     "Hello {name}! Welcome to {company}.",
            ...     description="Simple greeting template",
            ... )

        Raises:
            LLMLingError: If registration fails
        """
        try:
            # Create standard user message from content
            messages = [PromptMessage(role="user", content=content)]

            # Use content's first line as description if none provided
            if not description:
                first_line = content.split("\n", 1)[0]
                description = (
                    first_line[:100] + "..." if len(first_line) > 100 else first_line  # noqa: PLR2004
                )

            prompt = StaticPrompt(name=name, description=description, messages=messages)
            self._prompt_registry.register(name, prompt, replace=replace)

        except Exception as exc:
            msg = f"Failed to register static prompt {name!r}: {exc}"
            raise exceptions.LLMLingError(msg) from exc

    def register_file_prompt(
        self,
        name: str,
        path: JoinablePathLike,
        *,
        description: str,
        output_format: Literal["text", "markdown", "jinja2"] = "text",
        watch: bool = False,
        replace: bool = False,
    ) -> None:
        """Register a file-based prompt.

        Args:
            name: Name to register under
            path: Path to the prompt file
            description: Human-readable description
            output_format: Format of the file content
            watch: Whether to watch file for changes
            replace: Whether to replace existing prompt

        Example:
            >>> runtime.register_file_prompt(
            ...     "analyze",
            ...     "prompts/analysis.md",
            ...     description="Code analysis prompt",
            ...     format="markdown"
            ... )
        """
        from upathtools import to_upath

        try:
            if not to_upath(path).exists():
                msg = f"Prompt file not found: {path}"
                raise FileNotFoundError(msg)  # noqa: TRY301

            prompt = FilePrompt(
                name=name,
                path=upath.UPath(path),
                description=description,
                format=output_format,
                watch=watch,
            )
            self._prompt_registry.register(name, prompt, replace=replace)

        except Exception as exc:
            msg = f"Failed to register file prompt {name!r}: {exc}"
            raise exceptions.LLMLingError(msg) from exc

    def register_prompt(
        self,
        name: str,
        prompt: BasePrompt,
        *,
        replace: bool = False,
    ) -> None:
        """Register a pre-configured prompt.

        Note:
            The specialized registration methods should be preferred:
            - register_dynamic_prompt() for function-based prompts
            - register_static_prompt() for message-based prompts
            - register_file_prompt() for file-based prompts

        This method is provided for advanced use cases where you need
        to register an already configured prompt instance.

        Args:
            name: Name to register under
            prompt: Configured prompt instance
            replace: Whether to replace existing prompt
        """
        if isinstance(prompt, dict):
            if "type" not in prompt:
                msg = "Missing prompt type in configuration"
                raise exceptions.ConfigError(msg)
            from llmling.prompts.models import DynamicPrompt, FilePrompt, StaticPrompt

            match prompt["type"]:
                case "text":
                    prompt_obj: BasePrompt = StaticPrompt.model_validate(prompt)
                case "function":
                    prompt_obj = DynamicPrompt.model_validate(prompt)
                case "file":
                    prompt_obj = FilePrompt.model_validate(prompt)
                case _:
                    msg = f"Unknown prompt type: {prompt['type']}"
                    raise exceptions.ConfigError(msg)
        else:
            prompt_obj = prompt

        self._prompt_registry.register(name, prompt_obj, replace=replace)

    async def render_prompt(
        self,
        name: str,
        arguments: dict[str, Any] | None = None,
    ) -> Sequence[PromptMessage]:
        """Format a prompt with arguments.

        Args:
            name: Name of the prompt
            arguments: Optional arguments for formatting

        Returns:
            List of formatted messages

        Raises:
            LLMLingError: If prompt not found or formatting fails
        """
        try:
            prompt = self._prompt_registry[name]
            return await prompt.format(arguments)
        except KeyError as exc:
            msg = f"Prompt not found: {name}"
            raise exceptions.LLMLingError(msg) from exc
        except Exception as exc:
            msg = f"Failed to format prompt {name}: {exc}"
            raise exceptions.LLMLingError(msg) from exc

    def get_prompt(self, name: str) -> BasePrompt:
        """Get a prompt by name.

        Args:
            name: Name of the prompt

        Returns:
            The prompt

        Raises:
            LLMLingError: If prompt not found
        """
        try:
            return self._prompt_registry[name]
        except KeyError as exc:
            msg = f"Prompt not found: {name}"
            raise exceptions.LLMLingError(msg) from exc

    def get_prompts(self) -> Sequence[BasePrompt]:
        """Get all registered prompts.

        Returns:
            List of all prompts
        """
        return list(self._prompt_registry.values())

    async def process_content(
        self,
        content: str,
        processor_name: str,
        **kwargs: Any,
    ) -> ProcessorResult:
        """Process content with a named processor.

        Args:
            content: Content to process
            processor_name: Name of processor to use
            **kwargs: Additional processor arguments

        Returns:
            Processing result

        Raises:
            ProcessorError: If processing fails
        """
        return await self._processor_registry.process(
            content, [ProcessingStep(name=processor_name, kwargs=kwargs)]
        )

    @property
    def original_config(self) -> Config:
        """Get the original static configuration.

        Returns:
            Original configuration
        """
        return self._config

    async def get_prompt_completions(
        self,
        current_value: str,
        argument_name: str,
        prompt_name: str,
        **options: Any,
    ) -> list[str]:
        """Get completions for a prompt argument.

        Args:
            current_value: Current input value
            argument_name: Name of the argument
            prompt_name: Name of the prompt
            **options: Additional options

        Returns:
            List of completion suggestions
        """
        return await self._prompt_registry.get_completions(
            current_value=current_value,
            argument_name=argument_name,
            prompt_name=prompt_name,
            **options,
        )

    async def get_resource_completions(
        self,
        uri: str,
        current_value: str,
        argument_name: str | None = None,
        **options: Any,
    ) -> list[str]:
        """Get completions for a resource.

        Args:
            uri: Resource URI
            current_value: Current input value
            argument_name: Optional argument name
            **options: Additional options

        Returns:
            List of completion suggestions
        """
        loader = self._loader_registry.find_loader_for_uri(uri)
        return await loader.get_completions(
            current_value=current_value,
            argument_name=argument_name,
            **options,
        )

original_config property

original_config: Config

Get the original static configuration.

Returns:

Type Description
Config

Original configuration

tools property

tools: dict[str, LLMCallableTool]

Get all registered tools.

Returns:

Type Description
dict[str, LLMCallableTool]

Dictionary mapping tool names to tools

__aenter__ async

__aenter__() -> Self

Initialize dependencies and registries.

Source code in src/llmling/config/runtime.py
async def __aenter__(self) -> Self:
    """Initialize dependencies and registries."""
    # Check and set initialized flag atomically before ANY async op
    # This should allow caeses where same runtime gets initialized multiple times
    needs_init = not self._initialized
    self._initialized = True

    if needs_init:
        await self._dep_manager.__aenter__()
        await self._initialize_registries()
    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Clean up dependencies and registries.

Source code in src/llmling/config/runtime.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: types.TracebackType | None,
) -> None:
    """Clean up dependencies and registries."""
    try:
        await self.shutdown()
    finally:
        await self._dep_manager.__aexit__(exc_type, exc_val, exc_tb)

__enter__

__enter__() -> Self

Synchronous context manager entry.

Source code in src/llmling/config/runtime.py
def __enter__(self) -> Self:
    """Synchronous context manager entry."""
    self._dep_manager.__enter__()
    # Initialize registries if not already done
    import asyncio

    if not self._initialized:
        loop = asyncio.new_event_loop()
        try:
            loop.run_until_complete(self._initialize_registries())
            self._initialized = True
        finally:
            loop.close()
    return self

__exit__

__exit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Synchronous context manager exit.

Source code in src/llmling/config/runtime.py
def __exit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: types.TracebackType | None,
) -> None:
    """Synchronous context manager exit."""
    self._dep_manager.__exit__(exc_type, exc_val, exc_tb)

__init__

__init__(
    config: Config,
    *,
    loader_registry: ResourceLoaderRegistry,
    processor_registry: ProcessorRegistry,
    resource_registry: ResourceRegistry,
    prompt_registry: PromptRegistry,
    tool_registry: ToolRegistry
) -> None

Initialize with config and registries.

Parameters:

Name Type Description Default
config Config

Original static configuration

required
loader_registry ResourceLoaderRegistry

Registry for resource loaders

required
processor_registry ProcessorRegistry

Registry for content processors

required
resource_registry ResourceRegistry

Registry for resources

required
prompt_registry PromptRegistry

Registry for prompts

required
tool_registry ToolRegistry

Registry for tools

required
Source code in src/llmling/config/runtime.py
def __init__(
    self,
    config: Config,
    *,
    loader_registry: ResourceLoaderRegistry,
    processor_registry: ProcessorRegistry,
    resource_registry: ResourceRegistry,
    prompt_registry: PromptRegistry,
    tool_registry: ToolRegistry,
) -> None:
    """Initialize with config and registries.

    Args:
        config: Original static configuration
        loader_registry: Registry for resource loaders
        processor_registry: Registry for content processors
        resource_registry: Registry for resources
        prompt_registry: Registry for prompts
        tool_registry: Registry for tools
    """
    from llmling.depmanager import DependencyManager

    super().__init__()
    self._config = config
    self._loader_registry = loader_registry
    self._processor_registry = processor_registry
    self._resource_registry = resource_registry
    self._prompt_registry = prompt_registry
    self._tool_registry = tool_registry
    self._initialized = False
    # Register builtin processors
    proc = Jinja2Processor(config.global_settings.jinja_environment)
    self._processor_registry["jinja_template"] = proc
    settings = self._config.global_settings
    self._dep_manager = DependencyManager(
        prefer_uv=settings.prefer_uv,
        requirements=settings.requirements,
        extra_paths=settings.extra_paths,
        pip_index_url=str(settings.pip_index_url) if settings.pip_index_url else None,
        scripts=settings.scripts,
    )

create async classmethod

create(config: Config) -> Self

Create and initialize a runtime configuration.

This is a convenience method that ensures proper initialization when not using the async context manager.

Parameters:

Name Type Description Default
config Config

Static configuration to initialize from

required

Returns:

Type Description
Self

Initialized runtime configuration

Source code in src/llmling/config/runtime.py
@classmethod
async def create(cls, config: Config) -> Self:
    """Create and initialize a runtime configuration.

    This is a convenience method that ensures proper initialization
    when not using the async context manager.

    Args:
        config: Static configuration to initialize from

    Returns:
        Initialized runtime configuration
    """
    runtime = cls.from_config(config)
    async with runtime as initialized:
        return initialized

execute_tool async

execute_tool(_name: str, **params: Any) -> Any

Execute a tool by name.

Parameters:

Name Type Description Default
_name str

Name of the tool to execute

required
**params Any

Parameters to pass to the tool

{}

Returns:

Type Description
Any

Tool execution result

Raises:

Type Description
ToolError

If tool execution fails

Source code in src/llmling/config/runtime.py
async def execute_tool(
    self,
    _name: str,  # prefixed with "_" to avoid name collisions
    **params: Any,
) -> Any:
    """Execute a tool by name.

    Args:
        _name: Name of the tool to execute
        **params: Parameters to pass to the tool

    Returns:
        Tool execution result

    Raises:
        ToolError: If tool execution fails
    """
    return await self._tool_registry.execute(_name, **params)

from_config classmethod

from_config(config: Config | JoinablePathLike) -> Self

Create a fully initialized runtime config from static config.

Parameters:

Name Type Description Default
config Config | JoinablePathLike

Static configuration to initialize from

required

Returns:

Type Description
Self

Initialized runtime configuration

Source code in src/llmling/config/runtime.py
@classmethod
def from_config(cls, config: Config | JoinablePathLike) -> Self:
    """Create a fully initialized runtime config from static config.

    Args:
        config: Static configuration to initialize from

    Returns:
        Initialized runtime configuration
    """
    if isinstance(config, str | os.PathLike | UPath):
        config = ConfigManager.load(config).config
    loader_registry = ResourceLoaderRegistry()
    processor_registry = ProcessorRegistry()
    resource_registry = ResourceRegistry(
        loader_registry=loader_registry,
        processor_registry=processor_registry,
    )
    prompt_registry = PromptRegistry()
    tool_registry = ToolRegistry()
    assert isinstance(config, Config)
    runtime = cls(
        config=config,
        loader_registry=loader_registry,
        processor_registry=processor_registry,
        resource_registry=resource_registry,
        prompt_registry=prompt_registry,
        tool_registry=tool_registry,
    )
    from llmling.config.llm_tools import LLMTools

    llm_tools = LLMTools(runtime)
    capabilities = config.global_settings.llm_capabilities

    # Register enabled capabilities
    if capabilities.load_resource:
        tool_registry["load_resource"] = llm_tools.load_resource
    if capabilities.get_resources:
        tool_registry["get_resources"] = llm_tools.get_resources
    if capabilities.install_package:
        tool_registry["install_package"] = llm_tools.install_package
    if capabilities.register_tool:
        tool_registry["register_tool"] = llm_tools.register_tool
    if capabilities.register_code_tool:
        tool_registry["register_code_tool"] = llm_tools.register_code_tool
    if capabilities.chain_tools:
        tool_registry["chain"] = ChainTool(runtime)
    return runtime

from_file classmethod

from_file(path: JoinablePathLike) -> Self

Convenience function to directly create runtime config from a file.

Parameters:

Name Type Description Default
path JoinablePathLike

Path to the config file

required

Returns:

Type Description
Self

Initialized runtime configuration

Source code in src/llmling/config/runtime.py
@classmethod
def from_file(cls, path: JoinablePathLike) -> Self:
    """Convenience function to directly create runtime config from a file.

    Args:
        path: Path to the config file

    Returns:
        Initialized runtime configuration
    """
    manager = ConfigManager.load(path)
    return cls.from_config(manager.config)

get_prompt

get_prompt(name: str) -> BasePrompt

Get a prompt by name.

Parameters:

Name Type Description Default
name str

Name of the prompt

required

Returns:

Type Description
BasePrompt

The prompt

Raises:

Type Description
LLMLingError

If prompt not found

Source code in src/llmling/config/runtime.py
def get_prompt(self, name: str) -> BasePrompt:
    """Get a prompt by name.

    Args:
        name: Name of the prompt

    Returns:
        The prompt

    Raises:
        LLMLingError: If prompt not found
    """
    try:
        return self._prompt_registry[name]
    except KeyError as exc:
        msg = f"Prompt not found: {name}"
        raise exceptions.LLMLingError(msg) from exc

get_prompt_completions async

get_prompt_completions(
    current_value: str, argument_name: str, prompt_name: str, **options: Any
) -> list[str]

Get completions for a prompt argument.

Parameters:

Name Type Description Default
current_value str

Current input value

required
argument_name str

Name of the argument

required
prompt_name str

Name of the prompt

required
**options Any

Additional options

{}

Returns:

Type Description
list[str]

List of completion suggestions

Source code in src/llmling/config/runtime.py
async def get_prompt_completions(
    self,
    current_value: str,
    argument_name: str,
    prompt_name: str,
    **options: Any,
) -> list[str]:
    """Get completions for a prompt argument.

    Args:
        current_value: Current input value
        argument_name: Name of the argument
        prompt_name: Name of the prompt
        **options: Additional options

    Returns:
        List of completion suggestions
    """
    return await self._prompt_registry.get_completions(
        current_value=current_value,
        argument_name=argument_name,
        prompt_name=prompt_name,
        **options,
    )

get_prompts

get_prompts() -> Sequence[BasePrompt]

Get all registered prompts.

Returns:

Type Description
Sequence[BasePrompt]

List of all prompts

Source code in src/llmling/config/runtime.py
def get_prompts(self) -> Sequence[BasePrompt]:
    """Get all registered prompts.

    Returns:
        List of all prompts
    """
    return list(self._prompt_registry.values())

get_resource

get_resource(name_or_uri: str) -> BaseResource

Get a resource configuration by name or URI.

Parameters:

Name Type Description Default
name_or_uri str

Name of the resource or its URI. URIs must start with a scheme (e.g., "file://", "text://", etc.)

required

Returns:

Type Description
BaseResource

The resource configuration

Raises:

Type Description
ResourceError

If resource not found

Source code in src/llmling/config/runtime.py
def get_resource(self, name_or_uri: str) -> BaseResource:
    """Get a resource configuration by name or URI.

    Args:
        name_or_uri: Name of the resource or its URI. URIs must start with a scheme
            (e.g., "file://", "text://", etc.)

    Returns:
        The resource configuration

    Raises:
        ResourceError: If resource not found
    """
    if "://" in name_or_uri:  # It's a URI
        for resource in self._resource_registry.values():
            if resource.uri == name_or_uri:
                return resource
        msg = f"No resource found with URI: {name_or_uri}"
        raise exceptions.ResourceError(msg)
    return self._resource_registry[name_or_uri]

get_resource_completions async

get_resource_completions(
    uri: str, current_value: str, argument_name: str | None = None, **options: Any
) -> list[str]

Get completions for a resource.

Parameters:

Name Type Description Default
uri str

Resource URI

required
current_value str

Current input value

required
argument_name str | None

Optional argument name

None
**options Any

Additional options

{}

Returns:

Type Description
list[str]

List of completion suggestions

Source code in src/llmling/config/runtime.py
async def get_resource_completions(
    self,
    uri: str,
    current_value: str,
    argument_name: str | None = None,
    **options: Any,
) -> list[str]:
    """Get completions for a resource.

    Args:
        uri: Resource URI
        current_value: Current input value
        argument_name: Optional argument name
        **options: Additional options

    Returns:
        List of completion suggestions
    """
    loader = self._loader_registry.find_loader_for_uri(uri)
    return await loader.get_completions(
        current_value=current_value,
        argument_name=argument_name,
        **options,
    )

get_resource_loader

get_resource_loader(resource: BaseResource) -> Any

Get loader for a resource type.

Parameters:

Name Type Description Default
resource BaseResource

Resource to get loader for

required

Returns:

Type Description
Any

Resource loader instance

Raises:

Type Description
LoaderError

If no loader found for resource type

Source code in src/llmling/config/runtime.py
def get_resource_loader(self, resource: BaseResource) -> Any:  # type: ignore[return]
    """Get loader for a resource type.

    Args:
        resource: Resource to get loader for

    Returns:
        Resource loader instance

    Raises:
        LoaderError: If no loader found for resource type
    """
    return self._loader_registry.get_loader(resource)

get_resource_uri

get_resource_uri(name: str) -> str

Get URI for a resource.

Parameters:

Name Type Description Default
name str

Name of the resource

required

Returns:

Type Description
str

URI for the resource

Raises:

Type Description
ResourceError

If resource not found

Source code in src/llmling/config/runtime.py
def get_resource_uri(self, name: str) -> str:
    """Get URI for a resource.

    Args:
        name: Name of the resource

    Returns:
        URI for the resource

    Raises:
        ResourceError: If resource not found
    """
    return self._resource_registry.get_uri(name)

get_resources

get_resources() -> Sequence[BaseResource]

Get all registered resource configurations.

Returns:

Type Description
Sequence[BaseResource]

List of all resource configurations

Source code in src/llmling/config/runtime.py
def get_resources(self) -> Sequence[BaseResource]:
    """Get all registered resource configurations.

    Returns:
        List of all resource configurations
    """
    return list(self._resource_registry.values())

get_tool

get_tool(name: str) -> LLMCallableTool

Get a tool by name.

Parameters:

Name Type Description Default
name str

Name of the tool

required

Returns:

Type Description
LLMCallableTool

The tool

Raises:

Type Description
ToolError

If tool not found

Source code in src/llmling/config/runtime.py
def get_tool(self, name: str) -> LLMCallableTool:
    """Get a tool by name.

    Args:
        name: Name of the tool

    Returns:
        The tool

    Raises:
        ToolError: If tool not found
    """
    return self._tool_registry[name]

get_tools

get_tools() -> Sequence[LLMCallableTool]

Get all registered tools.

Returns:

Type Description
Sequence[LLMCallableTool]

List of all tools

Source code in src/llmling/config/runtime.py
def get_tools(self) -> Sequence[LLMCallableTool]:
    """Get all registered tools.

    Returns:
        List of all tools
    """
    return list(self._tool_registry.values())

install_package async

install_package(package: str) -> str

Install a Python package using the dependency manager.

Package specifications follow PIP format (e.g. "requests>=2.28.0").

Parameters:

Name Type Description Default
package str

Package specification to install

required

Returns:

Type Description
str

Message confirming the installation

Raises:

Type Description
ToolError

If installation fails or package spec is invalid

Example

await runtime.install_package("requests>=2.28.0")

Source code in src/llmling/config/runtime.py
async def install_package(
    self,
    package: str,
) -> str:
    """Install a Python package using the dependency manager.

    Package specifications follow PIP format (e.g. "requests>=2.28.0").

    Args:
        package: Package specification to install

    Returns:
        Message confirming the installation

    Raises:
        ToolError: If installation fails or package spec is invalid

    Example:
        >>> await runtime.install_package("requests>=2.28.0")
    """
    try:
        self._dep_manager.install_dependency(package)
        return f"Successfully installed package: {package}"  # noqa: TRY300
    except Exception as exc:
        msg = f"Failed to install package: {exc}"
        raise ToolError(msg) from exc

list_prompt_names

list_prompt_names() -> Sequence[str]

List all available prompt names.

Returns:

Type Description
Sequence[str]

List of registered prompt names

Source code in src/llmling/config/runtime.py
def list_prompt_names(self) -> Sequence[str]:
    """List all available prompt names.

    Returns:
        List of registered prompt names
    """
    return self._prompt_registry.list_items()

list_resource_names

list_resource_names() -> Sequence[str]

List all available resource names.

Returns:

Type Description
Sequence[str]

List of registered resource names

Source code in src/llmling/config/runtime.py
def list_resource_names(self) -> Sequence[str]:
    """List all available resource names.

    Returns:
        List of registered resource names
    """
    return self._resource_registry.list_items()

list_resource_uris

list_resource_uris() -> Sequence[str]

List all available resource URIs.

Returns:

Type Description
Sequence[str]

List of registered resource names

Source code in src/llmling/config/runtime.py
def list_resource_uris(self) -> Sequence[str]:
    """List all available resource URIs.

    Returns:
        List of registered resource names
    """
    return [res.uri for res in self._resource_registry.values() if res.uri]

list_tool_names

list_tool_names() -> Sequence[str]

List all available tool names.

Returns:

Type Description
Sequence[str]

List of registered tool names

Source code in src/llmling/config/runtime.py
def list_tool_names(self) -> Sequence[str]:
    """List all available tool names.

    Returns:
        List of registered tool names
    """
    return self._tool_registry.list_items()

load_resource async

load_resource(name: str) -> LoadedResource

Load a resource by its registered name.

Parameters:

Name Type Description Default
name str

Name of the resource as registered in configuration

required

Returns:

Type Description
LoadedResource

LoadedResource containing content and metadata

Raises:

Type Description
ResourceError

If resource doesn't exist or cannot be loaded

Source code in src/llmling/config/runtime.py
async def load_resource(self, name: str) -> LoadedResource:
    """Load a resource by its registered name.

    Args:
        name: Name of the resource as registered in configuration

    Returns:
        LoadedResource containing content and metadata

    Raises:
        ResourceError: If resource doesn't exist or cannot be loaded
    """
    return await self._resource_registry.load(name)

load_resource_by_uri async

load_resource_by_uri(uri: str) -> LoadedResource

Load a resource by URI.

Source code in src/llmling/config/runtime.py
async def load_resource_by_uri(self, uri: str) -> LoadedResource:
    """Load a resource by URI."""
    try:
        resolved_uri, resource = await self.resolve_resource_uri(uri)
        loader = self._loader_registry.get_loader(resource)
        name = loader.get_name_from_uri(resolved_uri)
        loader = loader.create(resource, name)
        async for res in loader.load(processor_registry=self._processor_registry):
            return res  # Return first resource
        msg = "No resources loaded"
        raise exceptions.ResourceError(msg)  # noqa: TRY301
    except Exception as exc:
        msg = f"Failed to load resource from URI {uri}"
        raise exceptions.ResourceError(msg) from exc

open async classmethod

open(
    source: JoinablePathLike | Config, *, validate: bool = True, strict: bool = False
) -> AsyncGenerator[RuntimeConfig]

Create and manage a runtime configuration asynchronously.

This is the primary way to create and use a RuntimeConfig. It ensures proper initialization and cleanup of all resources and provides an async context manager interface.

Parameters:

Name Type Description Default
source JoinablePathLike | Config

Either a path to a configuration file or a Config object. File paths can be strings or PathLike objects.

required
validate bool

Whether to validate the configuration. When True, performs additional checks beyond basic schema validation.

True
strict bool

Whether to raise exceptions on validation warnings. Only applicable when validate=True.

False

Yields:

Type Description
AsyncGenerator[RuntimeConfig]

Fully initialized RuntimeConfig instance

Raises:

Type Description
ConfigError

If configuration is invalid or validation fails in strict mode

TypeError

If source is neither a path nor a Config object

OSError

If configuration file cannot be accessed

Example
async with RuntimeConfig.open("config.yml") as runtime:
    resource = await runtime.load_resource("example")
Note

The context manager ensures that all resources are properly initialized before use and cleaned up afterwards, even if an error occurs.

Source code in src/llmling/config/runtime.py
@classmethod
@asynccontextmanager
async def open(
    cls,
    source: JoinablePathLike | Config,
    *,
    validate: bool = True,
    strict: bool = False,
) -> AsyncGenerator[RuntimeConfig]:
    """Create and manage a runtime configuration asynchronously.

    This is the primary way to create and use a RuntimeConfig. It ensures proper
    initialization and cleanup of all resources and provides an async context
    manager interface.

    Args:
        source: Either a path to a configuration file or a Config object.
               File paths can be strings or PathLike objects.
        validate: Whether to validate the configuration. When True, performs
                 additional checks beyond basic schema validation.
        strict: Whether to raise exceptions on validation warnings. Only
               applicable when validate=True.

    Yields:
        Fully initialized RuntimeConfig instance

    Raises:
        ConfigError: If configuration is invalid or validation fails in strict mode
        TypeError: If source is neither a path nor a Config object
        OSError: If configuration file cannot be accessed

    Example:
        ```python
        async with RuntimeConfig.open("config.yml") as runtime:
            resource = await runtime.load_resource("example")
        ```

    Note:
        The context manager ensures that all resources are properly initialized
        before use and cleaned up afterwards, even if an error occurs.
    """
    runtime = prepare_runtime(cls, source, validate=validate, strict=strict)
    async with runtime as r:
        yield r

open_sync classmethod

open_sync(
    source: JoinablePathLike | Config, *, validate: bool = True, strict: bool = False
) -> Generator[RuntimeConfig]

Create and manage a runtime configuration synchronously.

This is the synchronous version of open(). It provides the same functionality but uses a standard synchronous context manager interface. Use this if you don't need async functionality.

Parameters:

Name Type Description Default
source JoinablePathLike | Config

Either a path to a configuration file or a Config object. File paths can be strings or PathLike objects.

required
validate bool

Whether to validate the configuration. When True, performs additional checks beyond basic schema validation.

True
strict bool

Whether to raise exceptions on validation warnings. Only applicable when validate=True.

False

Yields:

Type Description
Generator[RuntimeConfig]

Fully initialized RuntimeConfig instance

Raises:

Type Description
ConfigError

If configuration is invalid or validation fails in strict mode

TypeError

If source is neither a path nor a Config object

OSError

If configuration file cannot be accessed

Example
with RuntimeConfig.open_sync("config.yml") as runtime:
    resource = runtime.load_resource_sync("example")
Note

The context manager ensures that all resources are properly initialized before use and cleaned up afterwards, even if an error occurs.

Source code in src/llmling/config/runtime.py
@classmethod
@contextmanager
def open_sync(
    cls,
    source: JoinablePathLike | Config,
    *,
    validate: bool = True,
    strict: bool = False,
) -> Generator[RuntimeConfig]:
    """Create and manage a runtime configuration synchronously.

    This is the synchronous version of open(). It provides the same functionality
    but uses a standard synchronous context manager interface. Use this if you
    don't need async functionality.

    Args:
        source: Either a path to a configuration file or a Config object.
               File paths can be strings or PathLike objects.
        validate: Whether to validate the configuration. When True, performs
                 additional checks beyond basic schema validation.
        strict: Whether to raise exceptions on validation warnings. Only
               applicable when validate=True.

    Yields:
        Fully initialized RuntimeConfig instance

    Raises:
        ConfigError: If configuration is invalid or validation fails in strict mode
        TypeError: If source is neither a path nor a Config object
        OSError: If configuration file cannot be accessed

    Example:
        ```python
        with RuntimeConfig.open_sync("config.yml") as runtime:
            resource = runtime.load_resource_sync("example")
        ```

    Note:
        The context manager ensures that all resources are properly initialized
        before use and cleaned up afterwards, even if an error occurs.
    """
    runtime = prepare_runtime(cls, source, validate=validate, strict=strict)
    with runtime:
        yield runtime

process_content async

process_content(content: str, processor_name: str, **kwargs: Any) -> ProcessorResult

Process content with a named processor.

Parameters:

Name Type Description Default
content str

Content to process

required
processor_name str

Name of processor to use

required
**kwargs Any

Additional processor arguments

{}

Returns:

Type Description
ProcessorResult

Processing result

Raises:

Type Description
ProcessorError

If processing fails

Source code in src/llmling/config/runtime.py
async def process_content(
    self,
    content: str,
    processor_name: str,
    **kwargs: Any,
) -> ProcessorResult:
    """Process content with a named processor.

    Args:
        content: Content to process
        processor_name: Name of processor to use
        **kwargs: Additional processor arguments

    Returns:
        Processing result

    Raises:
        ProcessorError: If processing fails
    """
    return await self._processor_registry.process(
        content, [ProcessingStep(name=processor_name, kwargs=kwargs)]
    )

register_code_tool async

register_code_tool(name: str, code: str, description: str | None = None) -> str

Register a new tool from Python code.

The provided code should define a function that will be converted into a tool. The function's docstring will be used as the tool's description if no description is provided.

Parameters:

Name Type Description Default
name str

Name for the new tool

required
code str

Python code defining the tool function

required
description str | None

Optional description override

None

Returns:

Type Description
str

Message confirming the registration

Raises:

Type Description
ToolError

If registration fails

Example

code = ''' ... async def count_words(text: str) -> dict[str, int]: ... words = text.split() ... return {"total": len(words)} ... ''' await runtime.register_code_tool("word_count", code)

Source code in src/llmling/config/runtime.py
async def register_code_tool(
    self,
    name: str,
    code: str,
    description: str | None = None,
) -> str:
    """Register a new tool from Python code.

    The provided code should define a function that will be converted into a tool.
    The function's docstring will be used as the tool's description if no description
    is provided.

    Args:
        name: Name for the new tool
        code: Python code defining the tool function
        description: Optional description override

    Returns:
        Message confirming the registration

    Raises:
        ToolError: If registration fails

    Example:
        >>> code = '''
        ... async def count_words(text: str) -> dict[str, int]:
        ...     words = text.split()
        ...     return {"total": len(words)}
        ... '''
        >>> await runtime.register_code_tool("word_count", code)
    """
    try:
        namespace: dict[str, Any] = {}
        exec(code, namespace)
        func = next((v for v in namespace.values() if callable(v)), None)
        if not func:
            msg = "No callable found in provided code"
            raise ValueError(msg)  # noqa: TRY301

        tool = LLMCallableTool.from_callable(
            func, name_override=name, description_override=description
        )
        self._tool_registry.register(name, tool)
        return f"Successfully registered tool: {name}"  # noqa: TRY300

    except Exception as exc:
        msg = f"Failed to register tool: {exc}"
        raise ToolError(msg) from exc

register_dynamic_prompt

register_dynamic_prompt(
    name: str,
    fn: str | Callable[..., Any],
    *,
    description: str | None = None,
    template: str | None = None,
    replace: bool = False
) -> None

Register a function-based prompt.

Parameters:

Name Type Description Default
name str

Name to register under

required
fn str | Callable[..., Any]

Function or import path (e.g., "module.submodule.function")

required
description str | None

Optional description (extracted from docstring if not provided)

None
template str | None

Optional template for formatting output

None
replace bool

Whether to replace existing prompt

False
Example

def get_info(url: str) -> str: ... '''Fetch info from URL.''' ... return "info" ... runtime.register_dynamic_prompt("fetch", get_info)

or

runtime.register_dynamic_prompt( ... "github", ... "my_module.get_github_info", ... description="Fetch GitHub repository information" ... )

Source code in src/llmling/config/runtime.py
def register_dynamic_prompt(
    self,
    name: str,
    fn: str | Callable[..., Any],
    *,
    description: str | None = None,
    template: str | None = None,
    replace: bool = False,
) -> None:
    """Register a function-based prompt.

    Args:
        name: Name to register under
        fn: Function or import path (e.g., "module.submodule.function")
        description: Optional description (extracted from docstring if not provided)
        template: Optional template for formatting output
        replace: Whether to replace existing prompt

    Example:
        >>> def get_info(url: str) -> str:
        ...     '''Fetch info from URL.'''
        ...     return "info"
        ...
        >>> runtime.register_dynamic_prompt("fetch", get_info)
        >>> # or
        >>> runtime.register_dynamic_prompt(
        ...     "github",
        ...     "my_module.get_github_info",
        ...     description="Fetch GitHub repository information"
        ... )
    """
    try:
        prompt = DynamicPrompt.from_callable(
            fn,
            name_override=name,
            description_override=description,
            template_override=template,
        )
        self._prompt_registry.register(name, prompt, replace=replace)

    except Exception as exc:
        msg = f"Failed to register dynamic prompt {name!r}: {exc}"
        raise exceptions.LLMLingError(msg) from exc

register_file_prompt

register_file_prompt(
    name: str,
    path: JoinablePathLike,
    *,
    description: str,
    output_format: Literal["text", "markdown", "jinja2"] = "text",
    watch: bool = False,
    replace: bool = False
) -> None

Register a file-based prompt.

Parameters:

Name Type Description Default
name str

Name to register under

required
path JoinablePathLike

Path to the prompt file

required
description str

Human-readable description

required
output_format Literal['text', 'markdown', 'jinja2']

Format of the file content

'text'
watch bool

Whether to watch file for changes

False
replace bool

Whether to replace existing prompt

False
Example

runtime.register_file_prompt( ... "analyze", ... "prompts/analysis.md", ... description="Code analysis prompt", ... format="markdown" ... )

Source code in src/llmling/config/runtime.py
def register_file_prompt(
    self,
    name: str,
    path: JoinablePathLike,
    *,
    description: str,
    output_format: Literal["text", "markdown", "jinja2"] = "text",
    watch: bool = False,
    replace: bool = False,
) -> None:
    """Register a file-based prompt.

    Args:
        name: Name to register under
        path: Path to the prompt file
        description: Human-readable description
        output_format: Format of the file content
        watch: Whether to watch file for changes
        replace: Whether to replace existing prompt

    Example:
        >>> runtime.register_file_prompt(
        ...     "analyze",
        ...     "prompts/analysis.md",
        ...     description="Code analysis prompt",
        ...     format="markdown"
        ... )
    """
    from upathtools import to_upath

    try:
        if not to_upath(path).exists():
            msg = f"Prompt file not found: {path}"
            raise FileNotFoundError(msg)  # noqa: TRY301

        prompt = FilePrompt(
            name=name,
            path=upath.UPath(path),
            description=description,
            format=output_format,
            watch=watch,
        )
        self._prompt_registry.register(name, prompt, replace=replace)

    except Exception as exc:
        msg = f"Failed to register file prompt {name!r}: {exc}"
        raise exceptions.LLMLingError(msg) from exc

register_prompt

register_prompt(name: str, prompt: BasePrompt, *, replace: bool = False) -> None

Register a pre-configured prompt.

Note

The specialized registration methods should be preferred: - register_dynamic_prompt() for function-based prompts - register_static_prompt() for message-based prompts - register_file_prompt() for file-based prompts

This method is provided for advanced use cases where you need to register an already configured prompt instance.

Parameters:

Name Type Description Default
name str

Name to register under

required
prompt BasePrompt

Configured prompt instance

required
replace bool

Whether to replace existing prompt

False
Source code in src/llmling/config/runtime.py
def register_prompt(
    self,
    name: str,
    prompt: BasePrompt,
    *,
    replace: bool = False,
) -> None:
    """Register a pre-configured prompt.

    Note:
        The specialized registration methods should be preferred:
        - register_dynamic_prompt() for function-based prompts
        - register_static_prompt() for message-based prompts
        - register_file_prompt() for file-based prompts

    This method is provided for advanced use cases where you need
    to register an already configured prompt instance.

    Args:
        name: Name to register under
        prompt: Configured prompt instance
        replace: Whether to replace existing prompt
    """
    if isinstance(prompt, dict):
        if "type" not in prompt:
            msg = "Missing prompt type in configuration"
            raise exceptions.ConfigError(msg)
        from llmling.prompts.models import DynamicPrompt, FilePrompt, StaticPrompt

        match prompt["type"]:
            case "text":
                prompt_obj: BasePrompt = StaticPrompt.model_validate(prompt)
            case "function":
                prompt_obj = DynamicPrompt.model_validate(prompt)
            case "file":
                prompt_obj = FilePrompt.model_validate(prompt)
            case _:
                msg = f"Unknown prompt type: {prompt['type']}"
                raise exceptions.ConfigError(msg)
    else:
        prompt_obj = prompt

    self._prompt_registry.register(name, prompt_obj, replace=replace)

register_resource

register_resource(name: str, resource: BaseResource, *, replace: bool = False) -> None

Register a new resource.

Parameters:

Name Type Description Default
name str

Name for the resource

required
resource BaseResource

Resource to register

required
replace bool

Whether to replace existing resource

False

Raises:

Type Description
ResourceError

If name exists and replace=False

Source code in src/llmling/config/runtime.py
def register_resource(
    self,
    name: str,
    resource: BaseResource,
    *,
    replace: bool = False,
) -> None:
    """Register a new resource.

    Args:
        name: Name for the resource
        resource: Resource to register
        replace: Whether to replace existing resource

    Raises:
        ResourceError: If name exists and replace=False
    """
    self._resource_registry.register(name, resource, replace=replace)

register_resource_by_loader async

register_resource_by_loader(
    loader_type: str, name: str, *, description: str = "", **params: Any
) -> BaseResource

Register a resource using a loader type.

Provides a parameter-based interface for registering resources without requiring resource objects.

Parameters:

Name Type Description Default
loader_type str

Type of loader to use ("path", "text", "cli", etc.)

required
name str

Name for the resource

required
description str

Optional description

''
**params Any

Loader-specific parameters

{}
Example

await runtime.register_resource_by_loader( "path", "readme", description="Project readme", path="README.md" )

await runtime.register_resource_by_loader( "text", "greeting", content="Hello, world!" )

Source code in src/llmling/config/runtime.py
async def register_resource_by_loader(
    self,
    loader_type: str,
    name: str,
    *,
    description: str = "",
    **params: Any,
) -> BaseResource:
    """Register a resource using a loader type.

    Provides a parameter-based interface for registering resources
    without requiring resource objects.

    Args:
        loader_type: Type of loader to use ("path", "text", "cli", etc.)
        name: Name for the resource
        description: Optional description
        **params: Loader-specific parameters

    Example:
        await runtime.register_resource_by_loader(
            "path",
            "readme",
            description="Project readme",
            path="README.md"
        )

        await runtime.register_resource_by_loader(
            "text",
            "greeting",
            content="Hello, world!"
        )
    """
    try:
        # Get loader class from registry
        loader_cls = self._loader_registry[loader_type]

        # Get the resource class from the loader
        resource_class = loader_cls.context_class

        # Create resource instance with just the essential fields
        resource = resource_class(description=description, **params)
        self._resource_registry.register(name, resource)
    except KeyError as exc:
        msg = f"Unknown loader type: {loader_type}"
        raise exceptions.ResourceError(msg) from exc
    except Exception as exc:
        msg = f"Failed to create resource: {exc}"
        raise exceptions.ResourceError(msg) from exc
    else:
        return resource

register_static_prompt

register_static_prompt(
    name: str, content: str, description: str | None = None, *, replace: bool = False
) -> None

Register a static prompt with text content.

A static prompt is a simple text template that can be used as-is or with Python's string formatting (using {placeholder} syntax).

Parameters:

Name Type Description Default
name str

Name to register under

required
content str

Prompt text content

required
description str | None

Optional description of what the prompt does

None
replace bool

Whether to replace existing prompt

False
Example

runtime.register_static_prompt( ... "summarize", ... "Please summarize the following text in 3 bullet points:\n{text}", ... description="Create a bullet-point summary", ... ) runtime.register_static_prompt( ... "greet", ... "Hello {name}! Welcome to {company}.", ... description="Simple greeting template", ... )

Raises:

Type Description
LLMLingError

If registration fails

Source code in src/llmling/config/runtime.py
def register_static_prompt(
    self,
    name: str,
    content: str,
    description: str | None = None,
    *,
    replace: bool = False,
) -> None:
    r"""Register a static prompt with text content.

    A static prompt is a simple text template that can be used as-is or with
    Python's string formatting (using {placeholder} syntax).

    Args:
        name: Name to register under
        content: Prompt text content
        description: Optional description of what the prompt does
        replace: Whether to replace existing prompt

    Example:
        >>> runtime.register_static_prompt(
        ...     "summarize",
        ...     "Please summarize the following text in 3 bullet points:\\n{text}",
        ...     description="Create a bullet-point summary",
        ... )
        >>> runtime.register_static_prompt(
        ...     "greet",
        ...     "Hello {name}! Welcome to {company}.",
        ...     description="Simple greeting template",
        ... )

    Raises:
        LLMLingError: If registration fails
    """
    try:
        # Create standard user message from content
        messages = [PromptMessage(role="user", content=content)]

        # Use content's first line as description if none provided
        if not description:
            first_line = content.split("\n", 1)[0]
            description = (
                first_line[:100] + "..." if len(first_line) > 100 else first_line  # noqa: PLR2004
            )

        prompt = StaticPrompt(name=name, description=description, messages=messages)
        self._prompt_registry.register(name, prompt, replace=replace)

    except Exception as exc:
        msg = f"Failed to register static prompt {name!r}: {exc}"
        raise exceptions.LLMLingError(msg) from exc

register_tool async

register_tool(
    function: str | Callable[..., Any],
    name: str | None = None,
    description: str | None = None,
    *,
    auto_install: bool = False
) -> str

Register a new tool from a function or import path.

Parameters:

Name Type Description Default
function str | Callable[..., Any]

Function to register (callable or import path)

required
name str | None

Optional name override (uses function name if None)

None
description str | None

Optional description override (uses docstring if None)

None
auto_install bool

Whether to attempt installing missing package

False

Returns:

Type Description
str

Message confirming the registration

Raises:

Type Description
ToolError

If registration fails

Example

await runtime.register_tool("webbrowser.open", "open_url") await runtime.register_tool(my_function)

Source code in src/llmling/config/runtime.py
async def register_tool(
    self,
    function: str | Callable[..., Any],
    name: str | None = None,
    description: str | None = None,
    *,
    auto_install: bool = False,
) -> str:
    """Register a new tool from a function or import path.

    Args:
        function: Function to register (callable or import path)
        name: Optional name override (uses function name if None)
        description: Optional description override (uses docstring if None)
        auto_install: Whether to attempt installing missing package

    Returns:
        Message confirming the registration

    Raises:
        ToolError: If registration fails

    Example:
        >>> await runtime.register_tool("webbrowser.open", "open_url")
        >>> await runtime.register_tool(my_function)
    """
    try:
        if auto_install and isinstance(function, str):
            # Try to import root module, install if missing
            package = function.split(".")[0]
            try:
                importlib.import_module(package)
            except ImportError:
                logger.info("Attempting to install package: %s", package)
                await self.install_package(package)

        tool = LLMCallableTool.from_callable(
            function, name_override=name, description_override=description
        )
        self._tool_registry.register(name or tool.name, tool)
        source = (
            function
            if isinstance(function, str)
            else getattr(function, "__name__", str(function))
        )
    except Exception as exc:
        msg = f"Failed to register tool: {exc}"
        raise ToolError(msg) from exc
    else:
        return f"Successfully registered tool: {tool.name} from {source}"

render_prompt async

render_prompt(name: str, arguments: dict[str, Any] | None = None) -> Sequence[PromptMessage]

Format a prompt with arguments.

Parameters:

Name Type Description Default
name str

Name of the prompt

required
arguments dict[str, Any] | None

Optional arguments for formatting

None

Returns:

Type Description
Sequence[PromptMessage]

List of formatted messages

Raises:

Type Description
LLMLingError

If prompt not found or formatting fails

Source code in src/llmling/config/runtime.py
async def render_prompt(
    self,
    name: str,
    arguments: dict[str, Any] | None = None,
) -> Sequence[PromptMessage]:
    """Format a prompt with arguments.

    Args:
        name: Name of the prompt
        arguments: Optional arguments for formatting

    Returns:
        List of formatted messages

    Raises:
        LLMLingError: If prompt not found or formatting fails
    """
    try:
        prompt = self._prompt_registry[name]
        return await prompt.format(arguments)
    except KeyError as exc:
        msg = f"Prompt not found: {name}"
        raise exceptions.LLMLingError(msg) from exc
    except Exception as exc:
        msg = f"Failed to format prompt {name}: {exc}"
        raise exceptions.LLMLingError(msg) from exc

resolve_resource_uri async

resolve_resource_uri(uri_or_name: str) -> tuple[str, BaseResource]

Resolve a resource identifier to a proper URI and resource.

Parameters:

Name Type Description Default
uri_or_name str

Can be: - Resource name: "test.txt" - Full URI: "file:///test.txt" - Local path: "/path/to/file.txt"

required

Returns:

Type Description
tuple[str, BaseResource]

Tuple of (resolved URI, resource object)

Raises:

Type Description
ResourceError

If resolution fails

Source code in src/llmling/config/runtime.py
async def resolve_resource_uri(self, uri_or_name: str) -> tuple[str, BaseResource]:
    """Resolve a resource identifier to a proper URI and resource.

    Args:
        uri_or_name: Can be:
            - Resource name: "test.txt"
            - Full URI: "file:///test.txt"
            - Local path: "/path/to/file.txt"

    Returns:
        Tuple of (resolved URI, resource object)

    Raises:
        ResourceError: If resolution fails
    """
    logger.debug("Resolving resource identifier: %s", uri_or_name)

    # 1. If it's already a URI, use directly
    if "://" in uri_or_name:
        logger.debug("Using direct URI")
        loader = self._loader_registry.find_loader_for_uri(uri_or_name)
        name = loader.get_name_from_uri(uri_or_name)
        if name in self._resource_registry:
            return uri_or_name, self._resource_registry[name]
        # Create temporary resource for the URI
        resource: BaseResource = PathResource(path=uri_or_name)  # pyright: ignore
        return uri_or_name, resource

    # 2. Try as resource name
    try:
        logger.debug("Trying as resource name")
        resource = self._resource_registry[uri_or_name]
        loader = self._loader_registry.get_loader(resource)
        loader = loader.create(resource, uri_or_name)  # Create instance
        uri = loader.create_uri(name=uri_or_name)
    except KeyError:
        pass
    else:
        return uri, resource

    # 3. If it looks like a path, try as file
    if "/" in uri_or_name or "\\" in uri_or_name or "." in uri_or_name:
        try:
            logger.debug("Trying as file path")
            resource = PathResource(path=uri_or_name)  # pyright: ignore
            loader = PathResourceLoader.create(resource, uri_or_name)
            uri = loader.create_uri(name=uri_or_name)
        except Exception as exc:  # noqa: BLE001
            logger.debug("Failed to create file URI: %s", exc)
        else:
            return uri, resource
    msg = f"Could not resolve resource {uri_or_name!r}. Expected resource name or path."
    raise exceptions.ResourceError(msg)

shutdown async

shutdown() -> None

Shut down all runtime components.

Source code in src/llmling/config/runtime.py
async def shutdown(self) -> None:
    """Shut down all runtime components."""
    await self._prompt_registry.shutdown()
    await self._resource_registry.shutdown()
    await self._tool_registry.shutdown()
    await self._processor_registry.shutdown()

startup async

startup() -> None

Start all runtime components.

Source code in src/llmling/config/runtime.py
async def startup(self) -> None:
    """Start all runtime components."""
    await self._processor_registry.startup()
    await self._tool_registry.startup()
    await self._resource_registry.startup()
    await self._prompt_registry.startup()

:fa-brands-github: Show source on GitHub