AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
docs: convert in-code comments to MkDocs admonitions in block-sdk-gui… (#12819)
slepybear334ec18c3179
diff --git a/docs/platform/block-sdk-guide.md b/docs/platform/block-sdk-guide.mdindex 42fd883251..5e1f694466 100644--- a/docs/platform/block-sdk-guide.md+++ b/docs/platform/block-sdk-guide.md@@ -12,36 +12,37 @@ Blocks are reusable components that perform specific tasks in AutoGPT workflows.First, create a `_config.py` file to configure your provider using the `ProviderBuilder`:-```python-from backend.sdk import BlockCostType, ProviderBuilder--# Simple API key provider-my_provider = (- ProviderBuilder("my_provider")- .with_api_key("MY_PROVIDER_API_KEY", "My Provider API Key")- .with_base_cost(1, BlockCostType.RUN)- .build()-)-```+!!! note "Simple API key provider"+ ```python+ from backend.sdk import BlockCostType, ProviderBuilder++ my_provider = (+ ProviderBuilder("my_provider")+ .with_api_key("MY_PROVIDER_API_KEY", "My Provider API Key")+ .with_base_cost(1, BlockCostType.RUN)+ .build()+ )+ ```For OAuth providers:-```python-from backend.sdk import BlockCostType, ProviderBuilder-from ._oauth import MyProviderOAuthHandler--my_provider = (- ProviderBuilder("my_provider")- .with_oauth(- MyProviderOAuthHandler,- scopes=["read", "write"],- client_id_env_var="MY_PROVIDER_CLIENT_ID",- client_secret_env_var="MY_PROVIDER_CLIENT_SECRET",+!!! note "OAuth provider configuration"+ ```python+ from backend.sdk import BlockCostType, ProviderBuilder+ from ._oauth import MyProviderOAuthHandler++ my_provider = (+ ProviderBuilder("my_provider")+ .with_oauth(+ MyProviderOAuthHandler,+ scopes=["read", "write"],+ client_id_env_var="MY_PROVIDER_CLIENT_ID",+ client_secret_env_var="MY_PROVIDER_CLIENT_SECRET",+ )+ .with_base_cost(1, BlockCostType.RUN)+ .build())- .with_base_cost(1, BlockCostType.RUN)- .build()-)-```+ ```### 2. Create the Block Class@@ -65,73 +66,88 @@ from ._config import my_providerclass MyBlock(Block):class Input(BlockSchemaInput):- # Define input fieldscredentials: CredentialsMetaInput = my_provider.credentials_field(description="API credentials for My Provider")query: str = SchemaField(description="The query to process")limit: int = SchemaField(- description="Number of results",+ description="Number of results",default=10,- ge=1, # Greater than or equal to 1- le=100 # Less than or equal to 100+ ge=1,+ le=100,)advanced_option: str = SchemaField(description="Advanced setting",default="",- advanced=True # Hidden by default in UI+ advanced=True,)class Output(BlockSchemaOutput):- # Define output fieldsresults: list = SchemaField(description="List of results")count: int = SchemaField(description="Total count")- # error output pin is already defined on BlockSchemaOutputdef __init__(self):super().__init__(- id=str(uuid.uuid4()), # Generate unique ID+ id=str(uuid.uuid4()),description="Brief description of what this block does",- categories={BlockCategory.SEARCH}, # Choose appropriate categories+ categories={BlockCategory.SEARCH},input_schema=self.Input,output_schema=self.Output,)async def run(- self,- input_data: Input,- *,+ self,+ input_data: Input,+ *,credentials: APIKeyCredentials,**kwargs) -> BlockOutput:try:- # Your block logic hereresults = await self.process_data(input_data.query,input_data.limit,credentials)-- # Yield outputs+yield "results", resultsyield "count", len(results)-+except Exception as e:yield "error", str(e)async def process_data(self, query, limit, credentials):- # Implement your logic- # Use credentials.api_key.get_secret_value() to access the API keypass```+!!! note "Input Schema Fields"+ - **`credentials`**: Use `my_provider.credentials_field()` to add provider authentication+ - **`query`**: Simple string field with description+ - **`limit`**: Integer field with validation constraints (`ge=1`, `le=100`)+ - **`advanced_option`**: Marked with `advanced=True` to hide from basic UI++!!! note "Output Schema Fields"+ - **`results`**: List of results from the block+ - **`count`**: Total count of results+ - The `error` output pin is already defined on `BlockSchemaOutput`++!!! note "Block Initialization"+ - **`id`**: Generate a unique ID using `uuid.uuid4()`+ - **`description`**: Brief description of what the block does+ - **`categories`**: Choose from `BlockCategory` enum (e.g., SEARCH, AI, PRODUCTIVITY)+ - **`input_schema` / `output_schema`**: Assign the Input and Output classes++!!! note "Run Method"+ - Implement your block logic in `process_data()` helper method+ - Use `credentials.api_key.get_secret_value()` to access the API key+ - Use `yield` to output results+## Key Components Explained### Provider ConfigurationThe `ProviderBuilder` allows you to:- **`.with_api_key()`**: Add API key authentication-- **`.with_oauth()`**: Add OAuth authentication+- **`.with_oauth()`**: Add OAuth authentication- **`.with_base_cost()`**: Set resource costs for the block- **`.with_webhook_manager()`**: Add webhook support- **`.with_user_password()`**: Add username/password auth@@ -155,69 +171,72 @@ The `ProviderBuilder` allows you to:Add test configuration to your block:-```python-def __init__(self):- super().__init__(- # ... other config ...- test_input={- "query": "test query",- "limit": 5,- "credentials": {- "provider": "my_provider",- "id": str(uuid.uuid4()),- "type": "api_key"+!!! note "Test Configuration"+ ```python+ def __init__(self):+ super().__init__(+ # ... other config ...+ test_input={+ "query": "test query",+ "limit": 5,+ "credentials": {+ "provider": "my_provider",+ "id": str(uuid.uuid4()),+ "type": "api_key"+ }+ },+ test_output=[+ ("results", ["result1", "result2"]),+ ("count", 2)+ ],+ test_mock={+ "process_data": lambda *args, **kwargs: ["result1", "result2"]}- },- test_output=[- ("results", ["result1", "result2"]),- ("count", 2)- ],- test_mock={- "process_data": lambda *args, **kwargs: ["result1", "result2"]- }- )-```+ )+ ```### OAuth SupportCreate an OAuth handler in `_oauth.py`:-```python-from backend.integrations.oauth.base import BaseOAuthHandler+!!! note "OAuth Handler Implementation"+ ```python+ from backend.integrations.oauth.base import BaseOAuthHandler-class MyProviderOAuthHandler(BaseOAuthHandler):- PROVIDER_NAME = "my_provider"-- def _get_authorization_url(self, scopes: list[str], state: str) -> str:- # Implementation- pass-- def _exchange_code_for_token(self, code: str, scopes: list[str]) -> dict:- # Implementation- pass-```+ class MyProviderOAuthHandler(BaseOAuthHandler):+ PROVIDER_NAME = "my_provider"++ def _get_authorization_url(self, scopes: list[str], state: str) -> str:+ # Implement URL generation for OAuth flow+ pass++ def _exchange_code_for_token(self, code: str, scopes: list[str]) -> dict:+ # Implement token exchange logic+ pass+ ```### Webhook SupportCreate a webhook manager in `_webhook.py`:-```python-from backend.integrations.webhooks._base import BaseWebhooksManager+!!! note "Webhook Manager Implementation"+ ```python+ from backend.integrations.webhooks._base import BaseWebhooksManager-class MyProviderWebhookManager(BaseWebhooksManager):- PROVIDER_NAME = "my_provider"-- async def validate_event(self, event: dict) -> bool:- # Implementation- pass-```+ class MyProviderWebhookManager(BaseWebhooksManager):+ PROVIDER_NAME = "my_provider"++ async def validate_event(self, event: dict) -> bool:+ # Implement event validation logic+ pass+ ```## File Organization```backend/blocks/my_provider/├── __init__.py # Export your blocks-├── _config.py # Provider configuration+├── _config.py # Provider configuration├── _oauth.py # OAuth handler (optional)├── _webhook.py # Webhook manager (optional)├── _api.py # API client wrapper (optional)@@ -248,13 +267,13 @@ async def run(self, input_data: Input, *, credentials: APIKeyCredentials, **kwar"Authorization": f"Bearer {credentials.api_key.get_secret_value()}","Content-Type": "application/json"}-+response = await Requests().post("https://api.example.com/endpoint",headers=headers,json={"query": input_data.query})-+data = response.json()yield "results", data.get("results", [])```@@ -263,20 +282,24 @@ async def run(self, input_data: Input, *, credentials: APIKeyCredentials, **kwar```pythonasync def run(- self,- input_data: Input,- *,+ self,+ input_data: Input,+ *,credentials: OAuth2Credentials | APIKeyCredentials,**kwargs):if isinstance(credentials, OAuth2Credentials):- # Handle OAuth+ # Handle OAuth credentialstoken = credentials.access_token.get_secret_value()else:- # Handle API key+ # Handle API key credentialstoken = credentials.api_key.get_secret_value()```+!!! note "Authentication Types"+ - **`OAuth2Credentials`**: Access token via `credentials.access_token.get_secret_value()`+ - **`APIKeyCredentials`**: API key via `credentials.api_key.get_secret_value()`+### Handling FilesWhen your block works with files (images, videos, documents), use `store_media_file()`:@@ -311,11 +334,16 @@ async def run(result = await store_media_file(file=generated_url,execution_context=execution_context,- return_format="for_block_output", # workspace:// in CoPilot, data URI in graphs+ return_format="for_block_output",)yield "image_url", result```+!!! note "File Handling Patterns"+ - **PROCESSING**: Use `"for_local_processing"` when you need a local file path for tools like ffmpeg, MoviePy, PIL+ - **EXTERNAL API**: Use `"for_external_api"` when sending content to APIs like Replicate or OpenAI (returns base64 data URI)+ - **OUTPUT**: Use `"for_block_output"` to return results - this automatically adapts: `workspace://` in CoPilot, data URI in graphs+**Return format options:**- `"for_local_processing"` - Local file path for processing tools- `"for_external_api"` - Data URI for external APIs needing base64@@ -350,4 +378,4 @@ poetry run pytest 'backend/blocks/test/test_block.py::test_available_blocks[MyBl- **OAuth + API**: `/backend/blocks/linear/` - OAuth and API key support- **Webhooks**: `/backend/blocks/exa/` - Includes webhook manager-Study these examples to understand different patterns and approaches for building blocks.\ No newline at end of file+Study these examples to understand different patterns and approaches for building blocks.