Configuration settings

Read and write configuration file.

This file also contains the definitions of the models supported in the package.

Expected behaviour

By being implemented with the pydantic_settings package, the constructors of the settings object may through errors at validation. The function load_settings centralizes the error handling of the construction of settings objects, but the default logger raises an exception like th eother constructors. Pass a concole logger for functions to be called from the console.

EmbeddingSettings

Bases: BaseSettings

Specification of embeddings object.

Attributes:

Name Type Description
dense_model str

embedding model specification

sparse_model SparseModel

sparse embeddings

Source code in lmm/config/config.py
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
class EmbeddingSettings(BaseSettings):
    """
    Specification of embeddings object.

    Attributes:
        dense_model: embedding model specification
        sparse_model: sparse embeddings
    """

    dense_model: str = Field(
        default="SentenceTransformers/distiluse-base-multilingual-cased-v2",
        description="Model specification in the form "
        + "'model_provider/model' (e.g., 'OpenAI/text-embedding-3-small')",
    )
    sparse_model: SparseModel = Field(
        default="Qdrant/bm25",  # multilingual
        description="Sparse embedding model for hybrid search",
    )

    model_config = SettingsConfigDict(frozen=True, extra='forbid')

    def get_model_source(self) -> EmbeddingSource:
        return self.dense_model.split('/')[0]  # type: ignore

    def get_model_name(self) -> str:
        return self.dense_model.split('/')[1]

    def get_sparse_model_name(self) -> str:
        return str(self.sparse_model)

    @field_validator('dense_model', mode='after')
    @classmethod
    def validate_model_spec(cls, spec: str) -> str:
        cleaned_spec = spec.strip()
        if not (bool(cleaned_spec)):
            raise ValueError("Model specification is empty")
        if '\n' in cleaned_spec or '\r' in cleaned_spec:
            raise ValueError(
                "Model specification cannot contain newlines or carriage"
                + " returns."
            )
        tokens = cleaned_spec.split('/')
        if len(tokens) != 2:
            raise ValueError(
                "Model specification must contain the model provider and "
                + "the model name separated by a single '/'."
            )
        model_spec = tokens[0].strip()
        if model_spec not in EmbeddingSource.__args__:
            raise ValueError(
                f"Invalid model provider: '{model_spec}'. "
                + f"Must be one of {EmbeddingSource.__args__}."
            )
        return model_spec + '/' + tokens[1].strip()

LanguageModelSettings

Bases: BaseModel

Specification of language sources and models.

Attributes:

Name Type Description
model str

model specificaion

temperature float

float between 0.0 and 2.0

max_tokens int | None

max number of generated tokens

max_retries int

max number retries attempts

timmeout int

timeout when waiting for response

provider_params dict[str, MetadataPrimitiveWithList]

provider-specific parameters

Source code in lmm/config/config.py
 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
class LanguageModelSettings(BaseModel):
    """
    Specification of language sources and models.

    Attributes:
        model: model specificaion
        temperature: float between 0.0 and 2.0
        max_tokens: max number of generated tokens
        max_retries: max number retries attempts
        timmeout: timeout when waiting for response
        provider_params: provider-specific parameters
    """

    # Required
    model: str = Field(
        description="Model specification in the form "
        + "'model_provider/model' (e.g., 'OpenAI/gpt-4o')"
    )

    # Common configurable parameters
    temperature: float = Field(
        default=0.1,
        ge=0.0,
        le=2.0,
        description="Controls randomness in model responses (0.0-2.0)",
    )
    max_tokens: int | None = Field(
        default=None,
        ge=1,
        description="Maximum number of tokens to generate",
    )
    max_retries: int = Field(
        default=2,
        ge=0,
        description="Maximum number of retry attempts",
    )
    timeout: float | None = Field(
        default=None, gt=0, description="Request timeout in seconds"
    )

    # Provider-specific parameters
    provider_params: dict[str, MetadataPrimitiveWithList] = Field(
        default_factory=dict,
        description="Provider-specific parameters (e.g., frequency_penalty for OpenAI)",
    )

    model_config = SettingsConfigDict(frozen=True, extra='forbid')

    def __hash__(self) -> int:
        """Make the object hashable by converting provider_params to a sorted tuple."""
        # Convert provider_params dict to a sorted tuple of items for hashing
        provider_params_tuple = tuple(
            sorted(self.provider_params.items())
        )
        return hash(
            (
                self.model,
                self.temperature,
                self.max_tokens,
                self.max_retries,
                self.timeout,
                provider_params_tuple,
            )
        )

    def get_model_source(self) -> ModelSource:
        return self.model.split('/')[0]  # type: ignore

    def get_model_name(self) -> str:
        return self.model.split('/')[1]

    # A method to create a new instance with some fields modified
    def from_instance(
        self,
        model: str | None = None,
        temperature: float | None = None,
        max_tokens: int | None = None,
        max_retries: int | None = None,
        timeout: float | None = None,
        provider_params: (
            dict[str, MetadataPrimitiveWithList] | None
        ) = None,
    ) -> 'LanguageModelSettings':
        return LanguageModelSettings(
            model=model if model is not None else self.model,
            temperature=(
                temperature
                if temperature is not None
                else self.temperature
            ),
            max_tokens=(
                max_tokens
                if max_tokens is not None
                else self.max_tokens
            ),
            max_retries=(
                max_retries
                if max_retries is not None
                else self.max_retries
            ),
            timeout=timeout if timeout is not None else self.timeout,
            provider_params=(
                provider_params
                if provider_params is not None
                else self.provider_params
            ),
        )

    @field_validator('model', mode='after')
    @classmethod
    def validate_model_spec(cls, spec: str) -> str:
        cleaned_spec = spec.strip()
        if not (bool(cleaned_spec)):
            raise ValueError("Model specification is empty")
        if '\n' in cleaned_spec or '\r' in cleaned_spec:
            raise ValueError(
                "Model specification cannot contain newlines or carriage"
                + " returns."
            )
        tokens = cleaned_spec.split('/')
        if len(tokens) != 2:
            raise ValueError(
                "Model specification must contain the model provider and "
                + "the model name separated by a single '/'.",
            )
        model_spec = tokens[0].strip()
        if model_spec not in ModelSource.__args__:
            raise ValueError(
                f"Invalid model provider: '{model_spec}'. "
                + f"Must be one of {ModelSource.__args__}."
            )
        return model_spec + '/' + tokens[1].strip()

    @model_validator(mode='after')
    def validate_provider_params(self) -> Self:
        """Validate provider-specific parameters based on the source."""
        params = self.provider_params

        # Define allowed parameters per provider (keeping it simple)
        ALLOWED_PARAMS = {
            'OpenAI': {
                'frequency_penalty',
                'presence_penalty',
                'top_p',
                'seed',
                'logprobs',
                'top_logprobs',
                'use_responses_api',
            },
            'Anthropic': {'top_p', 'top_k', 'stop_sequences'},
            'Mistral': {'top_p', 'random_seed', 'safe_mode'},
            'Gemini': {'top_p', 'top_k', 'candidate_count'},
        }

        # Get source from the current validation context
        source: ModelSource = self.get_model_source()
        if source and source in ALLOWED_PARAMS:
            allowed = ALLOWED_PARAMS[source]
            invalid_params = set(params.keys()) - allowed

            if invalid_params:
                raise ValueError(
                    f"Invalid provider_params for {source}: {invalid_params}. Allowed: {allowed}"
                )

        return self

__hash__()

Make the object hashable by converting provider_params to a sorted tuple.

Source code in lmm/config/config.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def __hash__(self) -> int:
    """Make the object hashable by converting provider_params to a sorted tuple."""
    # Convert provider_params dict to a sorted tuple of items for hashing
    provider_params_tuple = tuple(
        sorted(self.provider_params.items())
    )
    return hash(
        (
            self.model,
            self.temperature,
            self.max_tokens,
            self.max_retries,
            self.timeout,
            provider_params_tuple,
        )
    )

validate_provider_params()

Validate provider-specific parameters based on the source.

Source code in lmm/config/config.py
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
@model_validator(mode='after')
def validate_provider_params(self) -> Self:
    """Validate provider-specific parameters based on the source."""
    params = self.provider_params

    # Define allowed parameters per provider (keeping it simple)
    ALLOWED_PARAMS = {
        'OpenAI': {
            'frequency_penalty',
            'presence_penalty',
            'top_p',
            'seed',
            'logprobs',
            'top_logprobs',
            'use_responses_api',
        },
        'Anthropic': {'top_p', 'top_k', 'stop_sequences'},
        'Mistral': {'top_p', 'random_seed', 'safe_mode'},
        'Gemini': {'top_p', 'top_k', 'candidate_count'},
    }

    # Get source from the current validation context
    source: ModelSource = self.get_model_source()
    if source and source in ALLOWED_PARAMS:
        allowed = ALLOWED_PARAMS[source]
        invalid_params = set(params.keys()) - allowed

        if invalid_params:
            raise ValueError(
                f"Invalid provider_params for {source}: {invalid_params}. Allowed: {allowed}"
            )

    return self

Settings

Bases: BaseSettings

A pydantic settings object containing the fields with the configuration information.

Settings are saved and read from the configuration file in TOML format.

Attributes:

Name Type Description
server

Server configuration settings

embeddings EmbeddingSettings

Embedding model configuration

major LanguageModelSettings

Primary language model for complex tasks

minor LanguageModelSettings

Secondary language model for simple tasks

aux LanguageModelSettings

Auxiliary language model for specialized tasks

Note

At present, the Settings object only reads from config.toml in the project folder. This path and name can be customized via the model_config.

Source code in lmm/config/config.py
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
class Settings(BaseSettings):
    """
    A pydantic settings object containing the fields with the
    configuration information.

    Settings are saved and read from the configuration file in TOML
    format.

    Attributes:
        server: Server configuration settings
        embeddings: Embedding model configuration
        major: Primary language model for complex tasks
        minor: Secondary language model for simple tasks
        aux: Auxiliary language model for specialized tasks

    Note:
        At present, the Settings object only reads from config.toml in
        the project folder. This path and name can be customized via
        the model_config.
    """

    # Language model embeddings
    embeddings: EmbeddingSettings = Field(
        default_factory=lambda: EmbeddingSettings(
            dense_model="SentenceTransformers/distiluse-base-multilingual-cased-v2",
            sparse_model="Qdrant/bm25",
        ),
        description="Embedding model configuration",
    )

    # Language models with better naming and validation
    major: LanguageModelSettings = Field(
        default_factory=lambda: LanguageModelSettings(
            model="OpenAI/gpt-4.1-mini",
            temperature=0.4,
            max_tokens=2048,
        ),
        description="Primary language model for conceptual exposition",
    )
    minor: LanguageModelSettings = Field(
        default_factory=lambda: LanguageModelSettings(
            model="OpenAI/gpt-4.1-nano",
            temperature=0.1,
        ),
        description="Secondary language model for simple tasks",
    )
    aux: LanguageModelSettings = Field(
        default_factory=lambda: LanguageModelSettings(
            model="Mistral/mistral-small-latest",
            temperature=0,
            max_tokens=128,
        ),
        description="Auxiliary language model for specialized tasks",
    )

    model_config = SettingsConfigDict(
        toml_file=DEFAULT_CONFIG_FILE,
        env_prefix="LMM_",  # Uppercase for environment variables
        frozen=True,
        validate_assignment=True,
        extra='allow',  # Do not prevent unexpected fields
    )

    @classmethod
    def settings_customise_sources(
        cls,
        settings_cls: type[BaseSettings],
        init_settings: PydanticBaseSettingsSource,
        env_settings: PydanticBaseSettingsSource,
        dotenv_settings: PydanticBaseSettingsSource,
        file_secret_settings: PydanticBaseSettingsSource,
    ) -> tuple[PydanticBaseSettingsSource, ...]:
        """Customize the order of settings sources."""
        return (
            init_settings,
            TomlConfigSettingsSource(settings_cls),
            env_settings,
        )

    def __string__(self) -> str:
        return serialize_settings(self)

settings_customise_sources(settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings) classmethod

Customize the order of settings sources.

Source code in lmm/config/config.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
    """Customize the order of settings sources."""
    return (
        init_settings,
        TomlConfigSettingsSource(settings_cls),
        env_settings,
    )

create_default_config_file(file_path=None, settings_class=Settings)

Create a default settings file.

Parameters:

Name Type Description Default
file_path str | Path | None

Target file path (defaults to config.toml)

None
settings_class type[T]

The settings class to instantiate (defaults to Settings). Must be a subclass of pydantic_settings.BaseSettings.

Settings

Raises:

Type Description
ImportError

If tomlkit is not available

OSError

If file cannot be written

ValueError

If settings cannot be serialized

Example
# Creates config.toml in base folder with default values
create_default_settings_file()

# Creates custom config file
create_default_settings_file(file_path="custom_config.toml")

# Creates config file with custom settings class
create_default_settings_file(
    file_path="custom_config.toml",
    settings_class=CustomSettings
)
Source code in lmm/config/config.py
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
def create_default_config_file(
    file_path: str | Path | None = None,
    settings_class: type[T] = Settings,  # type: ignore[assignment]
) -> None:
    """Create a default settings file.

    Args:
        file_path: Target file path (defaults to config.toml)
        settings_class: The settings class to instantiate (defaults to Settings).
            Must be a subclass of pydantic_settings.BaseSettings.

    Raises:
        ImportError: If tomlkit is not available
        OSError: If file cannot be written
        ValueError: If settings cannot be serialized

    Example:
        ```python
        # Creates config.toml in base folder with default values
        create_default_settings_file()

        # Creates custom config file
        create_default_settings_file(file_path="custom_config.toml")

        # Creates config file with custom settings class
        create_default_settings_file(
            file_path="custom_config.toml",
            settings_class=CustomSettings
        )
        ```
    """
    if file_path is None:
        file_path = DEFAULT_CONFIG_FILE

    file_path = Path(file_path)

    if file_path.exists():
        # otherwise, it will be read in
        print("Deleting old configuration file...")
        file_path.unlink()

    settings: T = settings_class()

    print("Saving new config file: " + str(file_path))
    export_settings(settings, file_path)

export_settings(settings, file_path=None)

Save settings to file in TOML format.

Parameters:

Name Type Description Default
settings BaseSettings

A settings object to save

required
file_path str | Path | None

The settings file path (defaults to config.toml)

None

Raises:

Type Description
ImportError

If tomlkit is not available

OSError

If file cannot be written

ValueError

If settings cannot be serialized

Source code in lmm/config/config.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
def export_settings(
    settings: BaseSettings, file_path: str | Path | None = None
) -> None:
    """Save settings to file in TOML format.

    Args:
        settings: A settings object to save
        file_path: The settings file path (defaults to config.toml)

    Raises:
        ImportError: If tomlkit is not available
        OSError: If file cannot be written
        ValueError: If settings cannot be serialized
    """
    if file_path is None:
        file_path = DEFAULT_CONFIG_FILE

    file_path = Path(file_path)

    # Ensure parent directory exists
    file_path.parent.mkdir(parents=True, exist_ok=True)

    with file_path.open("w", encoding="utf-8") as f:
        f.write(serialize_settings(settings))

format_pydantic_error_message(error_message)

Filter out verbose lines from pydantic error messages.

Parameters:

Name Type Description Default
error_message str

Raw pydantic error message

required

Returns:

Type Description
str

Cleaned error message without verbose help text

Source code in lmm/config/config.py
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
def format_pydantic_error_message(error_message: str) -> str:
    """Filter out verbose lines from pydantic error messages.

    Args:
        error_message: Raw pydantic error message

    Returns:
        Cleaned error message without verbose help text
    """
    import re

    lines: list[str] = error_message.split('\n')
    filtered_lines = [
        re.sub(r'\[type=.*?\]', "", line)
        for line in lines
        if "For further information visit" not in line
    ]
    return '\n'.join(filtered_lines)

load_settings(*, file_name=None, logger=ExceptionConsoleLogger(), settings_class=Settings)

Load settings from TOML file.

This function is generic and can load any BaseSettings subclass.

Parameters:

Name Type Description Default
file_name str | Path | None

Path to settings file (defaults to config.toml)

None
logger LoggerBase

logger to use. Defaults to a exception-raising logger.

ExceptionConsoleLogger()
settings_class type[T]

The settings class to instantiate (defaults to Settings). Must be a subclass of pydantic_settings.BaseSettings.

Settings

Returns:

Type Description
T | None

Loaded settings object of type settings_class, or None if exception raised.

Note

Use of an ExceptionConsoleLogger still requires to check that return value is not None to satisfy a type checker.

logger = ExceptionConsoleLogger()
settings = load_settings(logger=logger)
if settings is None:
    raise ValueError("Unreacheable code reached")

Here, the type checker is told that settings is not None, but the condition is always satisfied because load_settings will raise an exception whenever it would be returning None.

Contrast with the following:

logger = ConsoleLogger()
settings = load_settings(logger=logger)
if settings is None:
    raise ValueError("Could not read config.toml")
Example

Using with custom settings class:

class CustomSettings(BaseSettings):
    custom_field: str = "default"

custom = load_settings(
    file_name="custom_config.toml",
    settings_class=CustomSettings
)
Source code in lmm/config/config.py
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
def load_settings(
    *,
    file_name: str | Path | None = None,
    logger: LoggerBase = ExceptionConsoleLogger(),
    settings_class: type[T] = Settings,  # type: ignore[assignment]
) -> T | None:
    """Load settings from TOML file.

    This function is generic and can load any BaseSettings subclass.

    Args:
        file_name: Path to settings file (defaults to config.toml)
        logger: logger to use. Defaults to a exception-raising logger.
        settings_class: The settings class to instantiate (defaults to Settings).
            Must be a subclass of pydantic_settings.BaseSettings.

    Returns:
        Loaded settings object of type settings_class, or None if exception raised.

    Note:
        Use of an ExceptionConsoleLogger still requires to check that
        return value is not None to satisfy a type checker.

        ```python
        logger = ExceptionConsoleLogger()
        settings = load_settings(logger=logger)
        if settings is None:
            raise ValueError("Unreacheable code reached")
        ```

        Here, the type checker is told that settings is not None, but
        the condition is always satisfied because load_settings will
        raise an exception whenever it would be returning None.

        Contrast with the following:

        ```python
        logger = ConsoleLogger()
        settings = load_settings(logger=logger)
        if settings is None:
            raise ValueError("Could not read config.toml")
        ```

    Example:
        Using with custom settings class:

        ```python
        class CustomSettings(BaseSettings):
            custom_field: str = "default"

        custom = load_settings(
            file_name="custom_config.toml",
            settings_class=CustomSettings
        )
        ```

    """
    if file_name is None:
        file_name = DEFAULT_CONFIG_FILE

    file_path = Path(file_name)

    if not file_path.exists():
        logger.error(f"Settings file not found: {file_path}")
        return None

    try:
        # Create a temporary settings class with the specified file
        class TempSettings(settings_class):  # type: ignore[misc, valid-type]
            model_config = SettingsConfigDict(
                toml_file=str(file_path),
                env_prefix="LMM_",
                frozen=True,
                validate_assignment=True,
                extra='allow',
            )

        return cast(T, TempSettings())
    except TOMLDecodeError:
        logger.error(
            "An invalid value was found in the config file "
            "(often, 'None').\nCheck that all values are numbers "
            "or strings.\n"
            "Express None as an empty string or as 'None'."
        )
        return None
    except ValidationError as e:
        logger.error(
            format_pydantic_error_message(f"Invalid settings:\n{e}")
        )
        return None
    except ValueError as e:
        logger.error(f"Invalid settings:\n{e}")
        return None
    except Exception as e:
        logger.error(f"Could not load config settings:\n{e}")
        return None

print_settings(settings)

Print settings in TOML format to stdout.

Parameters:

Name Type Description Default
settings BaseSettings

The settings object to print

required

Raises:

Type Description
ImportError

If tomlkit is not available

ValueError

If settings cannot be serialized

Source code in lmm/config/config.py
486
487
488
489
490
491
492
493
494
495
496
def print_settings(settings: BaseSettings) -> None:
    """Print settings in TOML format to stdout.

    Args:
        settings: The settings object to print

    Raises:
        ImportError: If tomlkit is not available
        ValueError: If settings cannot be serialized
    """
    print(serialize_settings(settings))

serialize_settings(sets)

Transform the settings into a string in TOML format.

Parameters:

Name Type Description Default
sets BaseSettings

The settings object to serialize

required

Returns:

Type Description
str

TOML formatted string representation of settings

Raises:

Type Description
ImportError

If tomlkit is not available

ValueError

If settings cannot be serialized

Source code in lmm/config/config.py
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
def serialize_settings(sets: BaseSettings) -> str:
    """Transform the settings into a string in TOML format.

    Args:
        sets: The settings object to serialize

    Returns:
        TOML formatted string representation of settings

    Raises:
        ImportError: If tomlkit is not available
        ValueError: If settings cannot be serialized
    """
    try:
        import tomlkit
    except ImportError as e:
        raise ImportError(
            "tomlkit is required for TOML serialization"
        ) from e

    # try:
    doc = tomlkit.document()
    doc.add(tomlkit.comment("Configuration file"))
    doc.add(tomlkit.nl())

    data: dict[str, Any] = sets.model_dump()
    for key, value in data.items():
        if isinstance(value, dict):
            # Handle nested dictionaries (from BaseSettings objects)
            tbl = tomlkit.table()
            for kkey, vvalue in value.items():  # type: ignore
                # Make sure wi do not abort writing with a crash
                if not isinstance(kkey, str):
                    print("Warning: invalid key in toml file")
                    kkey = str(key)
                # Skip None values as they can't be serialized to TOML
                if vvalue is not None:
                    try:
                        tbl[kkey] = vvalue
                    except Exception as e:
                        print("Warning: could not write key in toml file:")
                        print(f"{e}")
                        pass
            doc[key] = tbl
        else:
            # Skip None values at top level too
            if value is not None:
                doc[key] = value

    return str(tomlkit.dumps(doc))  # type: ignore