### Build and Install Wheel File Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/CONTRIBUTING.md Builds a distributable wheel file for the library and then installs it using pip. This process creates package artifacts in the `dist/` directory, allowing for efficient installation. ```shell #!/bin/bash $ rye build # or $ python -m build ``` ```shell #!/bin/bash $ pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Add and Run Examples Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/CONTRIBUTING.md Demonstrates how to add executable Python examples to the `examples/` directory and run them. This allows for quick testing of SDK functionality against your API. Ensure the example script is made executable before running. ```python # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` ```shell #!/bin/bash $ chmod +x examples/.py # run the example against your api $ ./examples/.py ``` -------------------------------- ### Setup Environment with Rye Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/CONTRIBUTING.md Installs and synchronizes project dependencies using Rye, a Python environment manager. It automatically provisions the correct Python version and manages features. This is the recommended setup method. ```shell #!/bin/bash $ ./scripts/bootstrap ``` ```shell #!/bin/bash $ rye sync --all-features ``` ```shell # Activate the virtual environment - https://docs.python.org/3/library/venv.html#how-venvs-work $ source .venv/bin/activate # now you can omit the `rye run` prefix $ python script.py ``` -------------------------------- ### Run Mock Server for Tests Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/CONTRIBUTING.md Starts a mock server using Prism against your OpenAPI specification. This is a prerequisite for running most of the project's tests, providing a controlled environment for API interactions. ```shell # you will need npm installed $ npx prism mock path/to/your/openapi.yml ``` -------------------------------- ### Install from Source via Git Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/CONTRIBUTING.md Installs the opencode-sdk-python directly from its Git repository using pip. This is useful for testing unreleased changes or using the library without a local clone. ```shell #!/bin/bash $ pip install git+ssh://git@github.com/sst/opencode-sdk-python.git ``` -------------------------------- ### Setup Environment Without Rye Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/CONTRIBUTING.md Sets up the project environment using standard pip, bypassing Rye. This method requires manual virtual environment creation and ensures dependencies are installed from the development requirements lock file. ```shell #!/bin/bash $ pip install -r requirements-dev.lock ``` -------------------------------- ### Install Opencode Python SDK Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Installs the opencode-ai package from PyPI. Use `--pre` for pre-release versions. This is the basic installation for the synchronous client. ```sh pip install --pre opencode-ai ``` -------------------------------- ### Run All Tests Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/CONTRIBUTING.md Executes the project's test suite. This command runs all defined tests, which may require specific environment configurations such as a running mock server. ```shell #!/bin/bash $ ./scripts/test ``` -------------------------------- ### Install Opencode Python SDK with aiohttp support Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Installs the opencode-ai package along with optional aiohttp support for enhanced asynchronous performance. This is needed for using `DefaultAioHttpClient`. ```sh pip install --pre opencode-ai[aiohttp] ``` -------------------------------- ### Lint and Format Code Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/CONTRIBUTING.md Applies code linting and formatting using Ruff and Black. The `lint` script checks for code style issues, while the `format` script automatically corrects them. ```shell #!/bin/bash $ ./scripts/lint ``` ```shell #!/bin/bash $ ./scripts/format ``` -------------------------------- ### Full Async Workflow with Opencode Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt This example showcases a complete asynchronous workflow using the Opencode SDK, including session creation, sending messages to an AI model, and streaming events. It highlights the use of `AsyncOpencode` with `DefaultAioHttpClient` for efficient async operations. ```python import asyncio from opencode_ai import AsyncOpencode, DefaultAioHttpClient async def main(): # Use aiohttp for better async performance async with AsyncOpencode( http_client=DefaultAioHttpClient(), max_retries=3, timeout=30.0 ) as client: # Create session session = await client.session.create() print(f"Created session: {session.id}") # Send message response = await client.session.chat( id=session.id, model_id="claude-3-5-sonnet-20241022", provider_id="anthropic", parts=[{"type": "text", "text": "Analyze this codebase"}], ) # Process response for part in response.parts: if part.type == "text": print(f"Response: {part.text}") # Stream events stream = await client.event.list() async for event in stream: print(f"Event: {event.type}") if event.type == "session.completed": break asyncio.run(main()) ``` -------------------------------- ### Publish PyPI Release Manually Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/CONTRIBUTING.md Manually publishes a new release of the package to PyPI. This involves setting the `PYPI_TOKEN` environment variable and executing a publish script. This is typically done when not using the automated GitHub workflow. ```shell #!/bin/bash $ PYPI_TOKEN=your_pypi_token ./bin/publish-pypi ``` -------------------------------- ### Get App Configuration with Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Retrieves the current application configuration, including its name, version, default model, and available operational modes. Requires the 'opencode_ai' library. ```python from opencode_ai import Opencode client = Opencode() # Get app configuration app = client.app.get() print(f"App name: {app.name}") print(f"Version: {app.version}") print(f"Default model: {app.default_model}") print(f"Available modes: {app.modes}") ``` -------------------------------- ### Get Available Providers with Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Lists all AI model providers configured within the application. It returns a list of providers, each with an ID, name, and a list of available models. Requires the 'opencode_ai' library. ```python from opencode_ai import Opencode client = Opencode() # Get providers providers = client.app.providers() for provider in providers.providers: print(f"Provider: {provider.id}") print(f" Name: {provider.name}") print(f" Models: {', '.join([m.id for m in provider.models])}") ``` -------------------------------- ### Configure Opencode Client with Custom HTTP Client and Proxy Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt This Python example shows how to configure the Opencode client with a custom `httpx` client, enabling features like proxy support and advanced connection settings such as specifying local addresses and setting retry counts for the transport layer. ```python import httpx from opencode_ai import Opencode, DefaultHttpxClient # Create client with custom configuration client = Opencode( base_url="https://api.opencode.ai", http_client=DefaultHttpxClient( proxy="http://proxy.example.com:8080", transport=httpx.HTTPTransport( local_address="0.0.0.0", retries=3 ), ), max_retries=5, timeout=httpx.Timeout( connect=5.0, read=30.0, write=10.0, pool=5.0 ) ) # Use client with custom configuration sessions = client.session.list() ``` -------------------------------- ### Async API Usage with aiohttp Backend Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Demonstrates asynchronous API usage with the Opencode Python SDK configured to use `aiohttp` as the HTTP backend. This requires `aiohttp` to be installed and `DefaultAioHttpClient` to be instantiated. ```python import asyncio from opencode_ai import DefaultAioHttpClient from opencode_ai import AsyncOpencode async def main() -> None: async with AsyncOpencode( http_client=DefaultAioHttpClient(), ) as client: sessions = await client.session.list() asyncio.run(main()) ``` -------------------------------- ### Get Configuration (Python) Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/api.md Retrieves the overall configuration settings using the client.config.get() method. This method returns a Config object containing various configuration parameters. ```python from opencode_ai.types import Config, KeybindsConfig, McpLocalConfig, McpRemoteConfig, ModeConfig # Example usage: # config: Config = client.config.get() ``` -------------------------------- ### Get Available Modes with Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Retrieves all operational modes supported by the application, such as code editing, chat, or review. Each mode includes its ID, description, and capabilities. Requires the 'opencode_ai' library. ```python from opencode_ai import Opencode client = Opencode() # Get available modes modes = client.app.modes() for mode in modes.modes: print(f"Mode: {mode.id}") print(f" Description: {mode.description}") print(f" Capabilities: {mode.capabilities}") ``` -------------------------------- ### Determine Installed Opencode SDK Version in Python Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Provides a simple Python code snippet to check the currently installed version of the Opencode SDK. This is helpful for debugging version-related issues or ensuring that the expected version is active in the environment. ```python import opencode_ai print(opencode_ai.__version__) ``` -------------------------------- ### Event API Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/api.md Retrieve a list of events. This endpoint is used to get all available events. ```APIDOC ## GET /event ### Description Retrieves a list of events. ### Method GET ### Endpoint /event ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed." } ``` ### Response #### Success Response (200) - **events** (array) - A list of event objects. #### Response Example ```json { "example": "{\n \"events\": [\n {\n \"id\": \"event_1\",\n \"name\": \"New User Registered\"\n }\n ]\n}" } ``` ``` -------------------------------- ### Get File Status with Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Retrieves metadata and status information for all files in the workspace. It returns the total number of files and a list of modified files with their respective statuses. Requires the 'opencode_ai' library. ```python from opencode_ai import Opencode client = Opencode() # Get file status status = client.file.status() print(f"Total files: {status.total_files}") print(f"Modified files: {len(status.modified_files)}") for file in status.modified_files: print(f" - {file.path}: {file.status}") ``` -------------------------------- ### Async Event Streaming with Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Streams events asynchronously for non-blocking event processing in asynchronous Python applications. It handles various event types like tool starts and completion chunks. Requires 'asyncio' and 'opencode_ai'. ```python import asyncio from opencode_ai import AsyncOpencode async def stream_events(): client = AsyncOpencode() # Stream events asynchronously stream = await client.event.list() print("Listening for events...") async for event in stream: print(f"Event: {event.type}") # Process different event types if event.type == "tool.started": print(f" Tool: {event.tool_name}") elif event.type == "completion.chunk": print(f" Chunk: {event.text}", end="", flush=True) asyncio.run(stream_events()) ``` -------------------------------- ### Initialize App with Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Initializes the application, which may involve creating necessary configuration files like AGENTS.md. It returns a success status and the path to the created configuration file. Requires the 'opencode_ai' library. ```python from opencode_ai import Opencode client = Opencode() # Initialize app result = client.app.init() print(f"Initialization status: {result.success}") print(f"Config file created: {result.config_path}") ``` -------------------------------- ### Get Event List (Python) Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/api.md Retrieves a list of events using the client.event.list() method. This method returns an EventListResponse object containing event data. ```python from opencode_ai.types import EventListResponse # Example usage: # response: EventListResponse = client.event.list() ``` -------------------------------- ### Manage HTTP Resources with Context Manager in Python Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Illustrates how to manually manage HTTP client resources using a context manager. The `with Opencode() as client:` syntax ensures that the client's underlying HTTP connections are properly closed upon exiting the block, preventing resource leaks. ```python from opencode_ai import Opencode with Opencode() as client: # make requests here ... # HTTP client is now closed ``` -------------------------------- ### Synchronous API Usage with Opencode Python SDK Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Demonstrates basic synchronous usage of the Opencode Python SDK. It initializes the client and fetches a list of sessions. This requires Python 3.8+. ```python from opencode_ai import Opencode client = Opencode() sessions = client.session.list() ``` -------------------------------- ### Customize HTTP Client per Request in Python Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Shows how to customize the HTTP client on a per-request basis using the `with_options()` method. This is useful for applying specific client configurations to individual API calls without altering the default client settings. ```python client.with_options(http_client=DefaultHttpxClient(...)) ``` -------------------------------- ### Enable Logging in Python Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Shows how to enable logging for the Opencode SDK by setting the OPENCODE_LOG environment variable. Supported levels are 'info' and 'debug'. ```shell $ export OPENCODE_LOG=info ``` -------------------------------- ### Configure HTTP Client with Proxies and Transports in Python Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Demonstrates how to directly override the httpx client to customize it for specific use cases, such as supporting proxies and custom transports. This allows for advanced network configurations when interacting with the Opencode API. ```python import httpx from opencode_ai import Opencode, DefaultHttpxClient client = Opencode( # Or use the `OPENCODE_BASE_URL` env var base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Find Files by Name Pattern with Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Searches for files in the workspace that match a given query pattern (e.g., '*.py'). It returns a list of found files, including their paths and sizes. Requires the 'opencode_ai' library. ```python from opencode_ai import Opencode client = Opencode() # Find files matching a pattern results = client.find.files(query="*.py") print(f"Found {len(results.files)} files:") for file in results.files: print(f" - {file.path}") print(f" Size: {file.size} bytes") ``` -------------------------------- ### Opencode Python SDK: Summarize Session Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Generates a summary of all interactions and changes within a session. This function requires the session ID, model ID, and provider ID. It returns a summary object containing the text summary and a list of key changes. ```python from opencode_ai import Opencode client = Opencode() # Get session summary summary = client.session.summarize( id="session_123", model_id="claude-3-5-sonnet-20241022", provider_id="anthropic" ) print(f"Summary: {summary.text}") print(f"Key changes: {summary.changes}") ``` -------------------------------- ### Python: Session Module Methods Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/api.md Demonstrates the usage of various methods within the Session module of the Opencode AI Python SDK. These methods allow for session creation, listing, deletion, abortion, chat interactions, initialization, message retrieval, reverting, sharing, summarizing, and unsharing. ```python # Create a new session client.session.create() -> Session # List all sessions client.session.list() -> SessionListResponse # Delete a session by ID client.session.delete(id) -> SessionDeleteResponse # Abort a session by ID client.session.abort(id) -> SessionAbortResponse # Send a chat message to a session client.session.chat(id, **params) -> AssistantMessage # Initialize a session client.session.init(id, **params) -> SessionInitResponse # Get messages for a session client.session.messages(id) -> SessionMessagesResponse # Revert a session to a previous state client.session.revert(id, **params) -> Session # Share a session client.session.share(id) -> Session # Summarize a session client.session.summarize(id, **params) -> SessionSummarizeResponse # Unrevert a session client.session.unrevert(id) -> Session # Unshare a session client.session.unshare(id) -> Session ``` -------------------------------- ### App Management Methods (Python) Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/api.md Provides methods for managing applications, including retrieving app details, initializing an app, logging app activity, and fetching available modes and providers. These methods utilize specific response types for their outputs. ```python from opencode_ai.types import ( App, Mode, Model, Provider, AppInitResponse, AppLogResponse, AppModesResponse, AppProvidersResponse, ) # Example usage: # app: App = client.app.get() # init_response: AppInitResponse = client.app.init() # log_response: AppLogResponse = client.app.log(**params) # modes_response: AppModesResponse = client.app.modes() # providers_response: AppProvidersResponse = client.app.providers() ``` -------------------------------- ### Opencode Python SDK: List Sessions Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Retrieves a list of all available coding sessions for the current user using the Opencode Python SDK. It requires the 'opencode_ai' library and iterates through the 'data' field of the response to print session details like ID, creation time, and status. ```python from opencode_ai import Opencode client = Opencode() # List all sessions sessions = client.session.list() # Iterate through sessions for session in sessions.data: print(f"Session ID: {session.id}") print(f"Created at: {session.created_at}") print(f"Status: {session.status}") ``` -------------------------------- ### Opencode Python SDK: Create Session Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Creates a new AI coding session using the Opencode Python SDK. This session can be used for interactive chat and code operations. It requires the 'opencode_ai' library and returns a session object with an ID and status. ```python from opencode_ai import Opencode client = Opencode() # Create a new session session = client.session.create() print(f"Session created with ID: {session.id}") # The session object contains metadata about the created session print(f"Session status: {session.status}") ``` -------------------------------- ### Send Application Logs to Opencode Server Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt This snippet demonstrates how to send application logs with various metadata to the Opencode server for debugging and monitoring purposes. It utilizes the Opencode client to send log data. ```python from opencode_ai import Opencode client = Opencode() # Send log result = client.app.log( level="info", message="User completed code refactoring task", metadata={ "session_id": "session_123", "files_modified": 5, "lines_changed": 142 } ) print(f"Log sent: {result.success}") ``` -------------------------------- ### Session Management API Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt APIs for managing AI coding sessions, including creation, listing, sending messages, deletion, abortion, reversion, sharing, and summarization. ```APIDOC ## POST /session/create ### Description Creates a new AI coding session that can be used for interactive chat and code operations. ### Method POST ### Endpoint /session/create ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```python from opencode_ai import Opencode client = Opencode() # Create a new session session = client.session.create() print(f"Session created with ID: {session.id}") ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created session. - **status** (string) - The current status of the session (e.g., 'active', 'completed'). #### Response Example ```json { "id": "sess_abc123", "status": "active" } ``` ## GET /session/list ### Description Retrieves all available coding sessions for the current user. ### Method GET ### Endpoint /session/list ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```python from opencode_ai import Opencode client = Opencode() # List all sessions sessions = client.session.list() # Iterate through sessions for session in sessions.data: print(f"Session ID: {session.id}") print(f"Created at: {session.created_at}") print(f"Status: {session.status}") ``` ### Response #### Success Response (200) - **data** (array) - A list of session objects. - **id** (string) - The unique identifier for the session. - **created_at** (string) - The timestamp when the session was created. - **status** (string) - The current status of the session. #### Response Example ```json { "data": [ { "id": "sess_abc123", "created_at": "2023-10-27T10:00:00Z", "status": "active" } ] } ``` ## POST /session/{id}/chat ### Description Sends a user message to an existing session and receives an AI assistant response with code suggestions or analysis. ### Method POST ### Endpoint /session/{id}/chat ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the session to send the message to. #### Query Parameters None #### Request Body - **model_id** (string) - Required - The ID of the AI model to use for the response. - **provider_id** (string) - Required - The ID of the AI provider. - **parts** (array) - Required - A list of message parts. - **type** (string) - Required - The type of the part (e.g., 'text', 'tool_code'). - **text** (string) - Optional - The text content of the message part. - **tool_name** (string) - Optional - The name of the tool being used. - **code** (string) - Optional - The code content for a tool code part. - **mode** (string) - Optional - The mode of the chat (e.g., 'code', 'chat'). - **tools** (object) - Optional - Configuration for available tools. - **file_reader** (boolean) - Optional - Whether to enable the file reader tool. - **code_analyzer** (boolean) - Optional - Whether to enable the code analyzer tool. ### Request Example ```python from opencode_ai import Opencode client = Opencode() session = client.session.create() # Assuming session is created response = client.session.chat( id=session.id, model_id="claude-3-5-sonnet-20241022", provider_id="anthropic", parts=[ { "type": "text", "text": "Help me refactor this function to be more efficient" } ], mode="code", tools={ "file_reader": True, "code_analyzer": True } ) for part in response.parts: if part.type == "text": print(f"Assistant: {part.text}") elif part.type == "tool": print(f"Tool used: {part.tool_name}") ``` ### Response #### Success Response (200) - **parts** (array) - A list of response parts from the AI assistant. - **type** (string) - The type of the response part (e.g., 'text', 'tool'). - **text** (string) - The text content of the response part. - **tool_name** (string) - The name of the tool used. #### Response Example ```json { "parts": [ { "type": "text", "text": "Here's a more efficient version of your function..." }, { "type": "tool", "tool_name": "code_analyzer" } ] } ``` ## DELETE /session/{id} ### Description Removes a session and all its associated data permanently. ### Method DELETE ### Endpoint /session/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the session to delete. #### Query Parameters None #### Request Body None ### Request Example ```python from opencode_ai import Opencode import opencode_ai client = Opencode() try: # Delete a session by ID result = client.session.delete(id="session_123") print(f"Session deleted: {result.success}") except opencode_ai.NotFoundError as e: print(f"Session not found: {e.status_code}") except opencode_ai.APIConnectionError as e: print(f"Connection error: {e.__cause__}") ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the session deletion was successful. #### Response Example ```json { "success": true } ``` ## POST /session/{id}/abort ### Description Stops a session that is currently processing a request. ### Method POST ### Endpoint /session/{id}/abort ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the session to abort. #### Query Parameters None #### Request Body None ### Request Example ```python from opencode_ai import Opencode client = Opencode() # Abort a running session result = client.session.abort(id="session_123") print(f"Session aborted: {result.success}") ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the session abortion was successful. #### Response Example ```json { "success": true } ``` ## POST /session/{id}/revert ### Description Reverts specific messages or parts within a session to undo changes. ### Method POST ### Endpoint /session/{id}/revert ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the session to revert. #### Query Parameters - **message_id** (string) - Required - The ID of the message to revert. - **part_id** (string) - Optional - The ID of the specific part within the message to revert. #### Request Body None ### Request Example ```python from opencode_ai import Opencode client = Opencode() # Revert a specific message session = client.session.revert( id="session_123", message_id="msg_456", part_id="part_789" # Optional: revert specific part only ) print(f"Reverted to previous state. Session ID: {session.id}") ``` ### Response #### Success Response (200) - **id** (string) - The ID of the session after reversion. #### Response Example ```json { "id": "sess_abc123" } ``` ## POST /session/{id}/share ### Description Makes a session publicly accessible. ### Method POST ### Endpoint /session/{id}/share ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the session to share. #### Query Parameters None #### Request Body None ### Request Example ```python from opencode_ai import Opencode client = Opencode() # Share a session shared_session = client.session.share(id="session_123") print(f"Share URL: {shared_session.share_url}") ``` ### Response #### Success Response (200) - **share_url** (string) - The URL to access the shared session. #### Response Example ```json { "share_url": "https://opencode.ai/share/sess_abc123" } ``` ## POST /session/{id}/unshare ### Description Revokes public access to a session, making it private. ### Method POST ### Endpoint /session/{id}/unshare ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the session to unshare. #### Query Parameters None #### Request Body None ### Request Example ```python from opencode_ai import Opencode client = Opencode() # Unshare a session unshared_session = client.session.unshare(id="session_123") print(f"Session is now private") ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the session unsharing was successful. #### Response Example ```json { "success": true } ``` ## POST /session/{id}/summarize ### Description Generates a summary of all interactions and changes within a session. ### Method POST ### Endpoint /session/{id}/summarize ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the session to summarize. #### Query Parameters None #### Request Body - **model_id** (string) - Required - The ID of the AI model to use for summarization. - **provider_id** (string) - Required - The ID of the AI provider. ### Request Example ```python from opencode_ai import Opencode client = Opencode() # Get session summary summary = client.session.summarize( id="session_123", model_id="claude-3-5-sonnet-20241022", provider_id="anthropic" ) print(f"Summary: {summary.text}") print(f"Key changes: {summary.changes}") ``` ### Response #### Success Response (200) - **text** (string) - The generated summary of the session. - **changes** (array) - A list of key changes identified in the session. #### Response Example ```json { "text": "The session involved refactoring a Python function...", "changes": [ "Refactored function efficiency", "Added new test cases" ] } ``` ``` -------------------------------- ### Config API Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/api.md Retrieve the overall configuration settings for the application. ```APIDOC ## GET /config ### Description Retrieves the application's configuration settings. ### Method GET ### Endpoint /config ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed." } ``` ### Response #### Success Response (200) - **config** (object) - The application configuration object. #### Response Example ```json { "example": "{\n \"settings\": {\n \"theme\": \"dark\",\n \"fontSize\": 14\n },\n \"keybinds\": {\n \"save\": \"Ctrl+S\"\n }\n}" } ``` ``` -------------------------------- ### Differentiate Null vs. Missing Fields in Python Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Illustrates how to distinguish between a field explicitly set to null and a field that is entirely missing from an API response using the `.model_fields_set` attribute. ```python if response.my_field is None: if 'my_field' not in response.model_fields_set: print('Got json like {}, without a "my_field" key present at all.') else: print('Got json like {"my_field": null}.') ``` -------------------------------- ### Streaming Responses with Synchronous Client Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Shows how to handle streaming responses using the synchronous Opencode Python SDK. The client's event list method returns an iterator that yields events. ```python from opencode_ai import Opencode client = Opencode() stream = client.event.list() for events in stream: print(events) ``` -------------------------------- ### Comprehensive API Error Handling in Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt This Python code snippet demonstrates robust error handling for various Opencode API exceptions, including connection errors, authentication failures, rate limits, not found resources, and server errors. It provides specific messages and recovery advice for each error type. ```python from opencode_ai import Opencode import opencode_ai client = Opencode( max_retries=2, timeout=60.0 ) try: sessions = client.session.list() except opencode_ai.APIConnectionError as e: print(f"Network error: {e.__cause__}") print("Check your internet connection") except opencode_ai.AuthenticationError as e: print(f"Authentication failed: {e.status_code}") print("Please check your API credentials") except opencode_ai.RateLimitError as e: print(f"Rate limit exceeded: {e.status_code}") print("Waiting before retry...") except opencode_ai.NotFoundError as e: print(f"Resource not found: {e.status_code}") except opencode_ai.UnprocessableEntityError as e: print(f"Invalid request: {e.status_code}") print(f"Details: {e.response}") except opencode_ai.InternalServerError as e: print(f"Server error: {e.status_code}") print("Please try again later") except opencode_ai.APIStatusError as e: print(f"API error: {e.status_code}") print(f"Response: {e.response}") ``` -------------------------------- ### Opencode Python SDK: Read File Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Retrieves the contents of a specific file from the workspace using the Opencode Python SDK. This function requires the 'opencode_ai' library and initializes the client. ```python from opencode_ai import Opencode client = Opencode() ``` -------------------------------- ### Configure Request Timeouts in Python Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Demonstrates how to set request timeouts for the Opencode client, both globally and per-request. It accepts float values or httpx.Timeout objects. Timeouts result in an APITimeoutError. ```python from opencode_ai import Opencode import httpx # Configure the default for all requests: client = Opencode( # 20 seconds (default is 1 minute) timeout=20.0, ) # More granular control: client = Opencode( timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), ) # Override per-request: client.with_options(timeout=5.0).session.list() ``` -------------------------------- ### Python: Tui Module Methods Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/api.md Illustrates the methods available in the Tui module of the Opencode AI Python SDK. These methods facilitate interaction with the Tui interface, such as appending prompts and accessing help. ```python # Append a prompt to the Tui client.tui.append_prompt(**params) -> TuiAppendPromptResponse # Open the Tui help interface client.tui.open_help() -> TuiOpenHelpResponse ``` -------------------------------- ### Error Handling with Opencode Python SDK Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Illustrates comprehensive error handling for the Opencode Python SDK. It catches `APIConnectionError`, `RateLimitError`, and general `APIStatusError`, providing specific feedback for each. ```python import opencode_ai from opencode_ai import Opencode client = Opencode() try: client.session.list() except opencode_ai.APIConnectionError as e: print("The server could not be reached") print(e.__cause__) # an underlying Exception, likely raised within httpx. except opencode_ai.RateLimitError as e: print("A 429 status code was received; we should back off a bit.") except opencode_ai.APIStatusError as e: print("Another non-200-range status code was received") print(e.status_code) print(e.response) ``` -------------------------------- ### Make Custom HTTP Requests in Python Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Provides methods for making requests to undocumented endpoints or with custom parameters using `client.post`, `client.get`, `extra_query`, `extra_body`, and `extra_headers`. ```python import httpx response = client.post( "/foo", cast_to=httpx.Response, body={"my_param": True}, ) print(response.headers.get("x-foo")) ``` -------------------------------- ### Streaming Responses with Asynchronous Client Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Demonstrates handling streaming responses with the asynchronous Opencode Python SDK. The async client's event list method returns an async iterator. ```python from opencode_ai import AsyncOpencode client = AsyncOpencode() stream = await client.event.list() async for events in stream: print(events) ``` -------------------------------- ### Opencode Python SDK: Chat with Session Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Sends a user message to an existing session and receives an AI assistant response. This function requires the session ID, model ID, provider ID, and message parts. It supports code analysis and file reading tools. The response is processed to extract text or tool usage information. ```python from opencode_ai import Opencode client = Opencode() # Create a session first session = client.session.create() # Send a chat message response = client.session.chat( id=session.id, model_id="claude-3-5-sonnet-20241022", provider_id="anthropic", parts=[ { "type": "text", "text": "Help me refactor this function to be more efficient" } ], mode="code", tools={ "file_reader": True, "code_analyzer": True } ) # Process the assistant's response for part in response.parts: if part.type == "text": print(f"Assistant: {part.text}") elif part.type == "tool": print(f"Tool used: {part.tool_name}") ``` -------------------------------- ### Stream Server Events with Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Connects to the server's event stream to receive real-time updates on session activities, file changes, and system events. This is a blocking operation. Requires the 'opencode_ai' library. ```python from opencode_ai import Opencode client = Opencode() # Stream events (blocking) stream = client.event.list() print("Listening for events...") for event in stream: print(f"Event type: {event.type}") if event.type == "session.updated": print(f" Session ID: {event.session_id}") print(f" Status: {event.status}") elif event.type == "file.changed": print(f" File: {event.path}") print(f" Action: {event.action}") elif event.type == "message.created": print(f" Message: {event.content}") ``` -------------------------------- ### Configure Retry Settings for Opencode Python SDK Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Shows how to configure or disable automatic retries for API requests made with the Opencode Python SDK. By default, certain errors are retried twice with exponential backoff. ```python from opencode_ai import Opencode # Configure the default for all requests: client = Opencode( # default is 2 max_retries=0, ) ``` -------------------------------- ### Asynchronous API Usage with Opencode Python SDK Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Shows asynchronous usage of the Opencode Python SDK using `AsyncOpencode` and `asyncio`. API calls are `await`ed. This requires Python 3.8+. ```python import asyncio from opencode_ai import AsyncOpencode client = AsyncOpencode() async def main() -> None: sessions = await client.session.list() asyncio.run(main()) ``` -------------------------------- ### Search Text in Files with Python Source: https://context7.com/anomalyco/opencode-sdk-python/llms.txt Searches for specific text patterns within the content of files in the workspace. It supports regex or literal string patterns and returns matches with file path, line number, text content, and context. Requires the 'opencode_ai' library. ```python from opencode_ai import Opencode client = Opencode() # Search for text pattern matches = client.find.text(pattern="def\\s+\\w+\(.*\):") print(f"Found {len(matches.results)} matches:") for match in matches.results: print(f" File: {match.path}") print(f" Line {match.line}: {match.text}") print(f" Context: {match.context}") ``` -------------------------------- ### Access Raw Response Data in Python Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/README.md Explains how to access the raw HTTP response, including headers, by prefixing method calls with `.with_raw_response.`. It returns an APIResponse object. ```python from opencode_ai import Opencode client = Opencode() response = client.session.with_raw_response.list() print(response.headers.get('X-My-Header')) session = response.parse() # get the object that `session.list()` would have returned print(session) ``` -------------------------------- ### Find Functionality Methods (Python) Source: https://github.com/anomalyco/opencode-sdk-python/blob/main/api.md Enables searching for files, symbols, and text using the client.find methods. These methods accept parameters and return specific response types indicating the search results. ```python from opencode_ai.types import Symbol, FindFilesResponse, FindSymbolsResponse, FindTextResponse # Example usage: # files_response: FindFilesResponse = client.find.files(**params) # symbols_response: FindSymbolsResponse = client.find.symbols(**params) # text_response: FindTextResponse = client.find.text(**params) ```