Implementation:Microsoft Autogen Component Schema Gen
| Metadata | Value |
|---|---|
| Sources | Microsoft_Autogen |
| Domains | Schema Generation, Component Configuration, JSON Schema, CLI Tools |
| Last Updated | 2026-02-11 17:00 GMT |
Overview
Description
The component-schema-gen is a command-line tool that generates JSON Schema definitions for AutoGen component configurations. It processes component classes (like OpenAIChatCompletionClient, AzureOpenAIChatCompletionClient, and AzureTokenProvider) and creates comprehensive JSON schemas with provider-specific variants. The tool handles the complex mapping between component types and their configuration schemas, including well-known provider aliases, and generates a unified schema with oneOf discriminators for validation. The output schema can be used for configuration validation, IDE autocompletion, and documentation generation.
Usage
Run as a Python module to generate JSON schema output to stdout:
python -m component_schema_gen > component_schema.json
The tool automatically:
- Processes component classes and their config schemas
- Resolves provider mappings from WELL_KNOWN_PROVIDERS
- Creates provider-specific schema variants
- Combines definitions into a unified schema with oneOf discriminators
- Outputs valid JSON Schema that can validate component configurations
The generated schema supports validating component configurations used throughout AutoGen for model clients, authentication providers, and other pluggable components.
Code Reference
Source Location
Repository: https://github.com/microsoft/autogen
File: python/packages/component-schema-gen/src/component_schema_gen/__main__.py
Lines: 1-106
Signature
def build_specific_component_schema(
component: type[ComponentSchemaType[T]],
provider_str: str
) -> Dict[str, Any]:
"""
Build JSON schema for a specific component with given provider string.
Args:
component: Component class with component_config_schema attribute
provider_str: Provider identifier string for the schema
Returns:
Dict containing JSON schema for the component with provider
"""
pass
def main() -> None:
"""
Main entry point that generates complete component schema.
Processes all registered component types (OpenAIChatCompletionClient,
AzureOpenAIChatCompletionClient, AzureTokenProvider) and outputs
unified JSON schema to stdout.
"""
pass
if __name__ == "__main__":
main()
Import
# Run as module (preferred)
# python -m component_schema_gen
# Or import functions
from component_schema_gen.__main__ import (
build_specific_component_schema,
main
)
I/O Contract
Inputs
Command Line
| Argument | Type | Description | Required |
|---|---|---|---|
| (none) | - | No command-line arguments required | - |
Component Classes (hardcoded)
| Component | Description |
|---|---|
| OpenAIChatCompletionClient | OpenAI chat completion model client |
| AzureOpenAIChatCompletionClient | Azure OpenAI chat completion model client |
| AzureTokenProvider | Azure authentication token provider |
Component Requirements
- Must have component_config_schema attribute containing Pydantic model
- Must have component_type attribute specifying component category
- Must have component_provider_override or determinable provider string
- Must inherit from ComponentToConfig
Outputs
stdout: JSON Schema
{
"type": "object",
"$ref": "#/$defs/ComponentModel",
"$defs": {
"ComponentModel": {
"type": "object",
"oneOf": [
{"$ref": "#/$defs/OpenAIChatCompletionClient_prov:openai"},
{"$ref": "#/$defs/AzureOpenAIChatCompletionClient_prov:azure"},
...
]
},
"OpenAIChatCompletionClient_prov:openai": {
"type": "object",
"properties": {
"provider": {"type": "string", "const": "openai"},
"component_type": {"anyOf": [{"type": "string", "const": "model"}, {"type": "null"}]},
"config": {"$ref": "#/$defs/OpenAIChatCompletionClientConfiguration"}
}
},
"OpenAIChatCompletionClientConfiguration": {
"type": "object",
"properties": {
"model": {"type": "string"},
"api_key": {"type": "string"},
...
}
},
...
}
}
Schema Structure
| Element | Description |
|---|---|
| $ref: #/$defs/ComponentModel | Top-level reference to unified component schema |
| ComponentModel.oneOf | Array of references to all provider-specific component schemas |
| {ComponentName}_prov:{provider} | Provider-specific component schema with constrained provider property |
| properties.provider | String constant matching provider identifier |
| properties.component_type | String constant or null for component category |
| properties.config | Reference to configuration schema for the component |
Usage Examples
Generate Schema to File
# Generate schema and save to file
python -m component_schema_gen > autogen_component_schema.json
# Verify the output
cat autogen_component_schema.json | jq '.["$defs"].ComponentModel.oneOf | length'
Use in Configuration Validation
import json
import jsonschema
from pathlib import Path
import subprocess
# Generate schema
schema_json = subprocess.check_output(
["python", "-m", "component_schema_gen"],
text=True
)
schema = json.loads(schema_json)
# Load component configuration
config = {
"provider": "openai",
"component_type": "model",
"config": {
"model": "gpt-4",
"api_key": "sk-...",
"temperature": 0.7
}
}
# Validate configuration
try:
jsonschema.validate(instance=config, schema=schema)
print("Configuration is valid!")
except jsonschema.ValidationError as e:
print(f"Configuration error: {e.message}")
Programmatic Schema Generation
from component_schema_gen.__main__ import (
build_specific_component_schema,
main
)
from autogen_ext.models.openai import OpenAIChatCompletionClient
import json
# Build schema for specific component and provider
schema = build_specific_component_schema(
OpenAIChatCompletionClient,
"openai"
)
print(json.dumps(schema, indent=2))
# Output includes:
# - provider: "openai" (const)
# - component_type: "model"
# - config: reference to OpenAIChatCompletionClientConfiguration
# - $defs: all nested schema definitions
IDE Integration Example
{
"// .vscode/settings.json": "Configure VS Code JSON schema association",
"json.schemas": [
{
"fileMatch": ["**/components/*.json"],
"url": "./autogen_component_schema.json"
}
]
}
Inspecting Generated Schema
import json
import subprocess
# Generate and parse schema
schema_output = subprocess.check_output(
["python", "-m", "component_schema_gen"],
text=True
)
schema = json.loads(schema_output)
# Inspect available components
component_refs = schema["$defs"]["ComponentModel"]["oneOf"]
print(f"Found {len(component_refs)} component variants:")
for ref in component_refs:
component_key = ref["$ref"].split("/")[-1]
print(f" - {component_key}")
# Inspect specific component schema
openai_schema = schema["$defs"]["OpenAIChatCompletionClient_prov:openai"]
print(f"\nOpenAI client properties:")
print(json.dumps(openai_schema["properties"], indent=2))
Using Schema in Documentation
import json
import subprocess
from typing import Any, Dict
def generate_component_docs() -> None:
"""Generate markdown documentation from component schema."""
schema_output = subprocess.check_output(
["python", "-m", "component_schema_gen"],
text=True
)
schema = json.loads(schema_output)
# Extract component definitions
defs = schema["$defs"]
print("# AutoGen Component Configuration Reference\n")
for key, definition in defs.items():
if "_prov:" in key:
component_name, provider = key.split("_prov:")
print(f"## {component_name} ({provider})\n")
# Extract properties
props = definition.get("properties", {})
config_ref = props.get("config", {}).get("$ref", "")
if config_ref:
config_key = config_ref.split("/")[-1]
config_schema = defs.get(config_key, {})
config_props = config_schema.get("properties", {})
print("### Configuration Properties\n")
for prop_name, prop_schema in config_props.items():
prop_type = prop_schema.get("type", "any")
description = prop_schema.get("description", "")
print(f"- **{prop_name}** ({prop_type}): {description}")
print()
generate_component_docs()
Adding Custom Components
# To add new components to schema generation, modify __main__.py:
from my_custom_package import MyCustomClient
def main() -> None:
outer_model_schema: Dict[str, Any] = {
"type": "object",
"$ref": "#/$defs/ComponentModel",
"$defs": {
"ComponentModel": {
"type": "object",
"oneOf": [],
}
},
}
reverse_provider_lookup_table: DefaultDict[str, List[str]] = DefaultDict(list)
for key, value in WELL_KNOWN_PROVIDERS.items():
reverse_provider_lookup_table[value].append(key)
def add_type(type: type[ComponentSchemaType[T]]) -> None:
# ... existing implementation ...
pass
# Add existing components
add_type(OpenAIChatCompletionClient)
add_type(AzureOpenAIChatCompletionClient)
add_type(AzureTokenProvider)
# Add your custom component
add_type(MyCustomClient)
print(json.dumps(outer_model_schema, indent=2))
Related Pages
- Component Model - Core component configuration system
- Component Config - Component configuration patterns
- Model Clients - OpenAI and Azure model client implementations
- Provider Registry - WELL_KNOWN_PROVIDERS mapping
- JSON Schema Validation - Configuration validation patterns
- Pydantic Models - Schema generation from Pydantic models