From dc86bba7634232770705068659add3762769180c Mon Sep 17 00:00:00 2001 From: Mathieu Virbel Date: Fri, 31 Jan 2025 18:03:17 -0600 Subject: [PATCH 1/2] feat(docs): introduce documentation with mkdocs/readthedocs --- .readthedocs.yaml | 15 ++++ docs/api/api_client.md | 19 +++++ docs/api/api_types.md | 5 ++ docs/api/scope3ai.md | 11 +++ docs/api/tracer.md | 8 ++ docs/configuration.md | 51 ++++++++++++ docs/images/favicon.png | Bin 0 -> 1455 bytes docs/images/logo/dark.svg | 11 +++ docs/images/logo/light.svg | 11 +++ docs/index.md | 24 ++++++ docs/quickstart.md | 115 +++++++++++++++++++++++++++ docs/tracer.md | 128 ++++++++++++++++++++++++++++++ mkdocs.yml | 80 +++++++++++++++++++ pyproject.toml | 29 +++++++ scope3ai/__init__.py | 3 +- scope3ai/api/client.py | 11 +++ scope3ai/api/commandsgen.py | 11 ++- scope3ai/api/tracer.py | 21 +++++ scope3ai/api/types.py | 6 ++ scope3ai/lib.py | 30 ++++++- tools/generate-client-commands.py | 8 ++ tools/generate-docs.py | 31 ++++++++ 22 files changed, 624 insertions(+), 4 deletions(-) create mode 100644 .readthedocs.yaml create mode 100644 docs/api/api_client.md create mode 100644 docs/api/api_types.md create mode 100644 docs/api/scope3ai.md create mode 100644 docs/api/tracer.md create mode 100644 docs/configuration.md create mode 100644 docs/images/favicon.png create mode 100644 docs/images/logo/dark.svg create mode 100644 docs/images/logo/light.svg create mode 100644 docs/index.md create mode 100644 docs/quickstart.md create mode 100644 docs/tracer.md create mode 100644 mkdocs.yml create mode 100644 tools/generate-docs.py diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..cb14b5d --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,15 @@ +version: 2 + +build: + os: "ubuntu-24.04" + tools: + python: "3" + # We recommend using a requirements file for reproducible builds. + # This is just a quick example to get started. + # https://docs.readthedocs.io/page/guides/reproducible-builds.html + jobs: + pre_install: + - pip install mkdocs-material + +mkdocs: + configuration: mkdocs.yml diff --git a/docs/api/api_client.md b/docs/api/api_client.md new file mode 100644 index 0000000..39995be --- /dev/null +++ b/docs/api/api_client.md @@ -0,0 +1,19 @@ +## API Client + +The Scope3AI SDK provides both synchronous ([`Client`](#scope3ai.api.client.Client)) and +asynchronous ([`AsyncClient`](#scope3ai.api.client.AsyncClient)) HTTP clients for interacting +with the Scope3AI API. + +All the commands from the [`AsyncClient`](#scope3ai.api.client.AsyncClient) can be invoked with the `await`. + + +::: scope3ai.api.client + options: + heading_level: 1 + show_if_no_docstring: true + inherited_members: false + members: + - Client + - AsyncClient + - ClientBase + - ClientCommands diff --git a/docs/api/api_types.md b/docs/api/api_types.md new file mode 100644 index 0000000..d37d9b4 --- /dev/null +++ b/docs/api/api_types.md @@ -0,0 +1,5 @@ +# API Types + +::: scope3ai.api.types + options: + show_if_no_docstring: true diff --git a/docs/api/scope3ai.md b/docs/api/scope3ai.md new file mode 100644 index 0000000..9c51739 --- /dev/null +++ b/docs/api/scope3ai.md @@ -0,0 +1,11 @@ +# Scope3AI Reference + +The `Scope3AI` class is the central interface for tracking and analyzing the environmental impact of AI model interactions. It provides methods for tracing and logging interactions, as well as calculating key sustainability metrics like energy usage and emissions. + +Core features: +- Initialization with customizable tracking parameters +- Context management for measuring impact across multiple interactions +- Synchronous and asynchronous impact calculation modes +- Metadata support for session, environment and project tracking + +::: scope3ai.lib.Scope3AI diff --git a/docs/api/tracer.md b/docs/api/tracer.md new file mode 100644 index 0000000..737cc0f --- /dev/null +++ b/docs/api/tracer.md @@ -0,0 +1,8 @@ +# Tracer + +Tracer provides a convenient way to aggregate multiple library calls made within +its context, automatically waiting for and aggregating impact data when +accessed, unlike direct API calls which need to be handled individually - see +our [complete guide](../tracer.md) for details and examples. + +::: scope3ai.api.tracer diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..16a2ace --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,51 @@ +# Configuration + +The SDK can be configured either through environment variables or when calling `Scope3AI.init()`. + +The following environment variables are supported: + +| Environment Variable | Description | Scope3AI.init | Tracer | +|---------------------|-------------|---------------|--------------| +| `SCOPE3AI_API_KEY` | Required. Your Scope3AI API key | [api_key](/scope3ai/#scope3ai.lib.Scope3AI.init) | | +| `SCOPE3AI_API_URL` | The API endpoint URL | [api_url](/scope3ai/#scope3ai.lib.Scope3AI.init) | | +| `SCOPE3AI_DEBUG_LOGGING` | Enable debug logging | [enable_debug_logging](/scope3ai/#scope3ai.lib.Scope3AI.init) | | +| `SCOPE3AI_SYNC_MODE` | Enable synchronous mode | [sync_mode](/scope3ai/#scope3ai.lib.Scope3AI.init) | | +| `SCOPE3AI_ENVIRONMENT` | User-defined environment name (e.g. "production", "staging") | [environment](/scope3ai/#scope3ai.lib.Scope3AI.init) | | +| `SCOPE3AI_APPLICATION_ID` | User-defined application identifier | [application_id](/scope3ai/#scope3ai.lib.Scope3AI.init) | [application_id](/tracer/#scope3ai.api.tracer.Tracer) | +| `SCOPE3AI_CLIENT_ID` | User-defined client identifier | [client_id](/scope3ai/#scope3ai.lib.Scope3AI.init) | [client_id](/tracer/#scope3ai.api.tracer.Tracer) | +| `SCOPE3AI_PROJECT_ID` | User-defined project identifier | [project_id](/scope3ai/#scope3ai.lib.Scope3AI.init) | [project_id](/tracer/#scope3ai.api.tracer.Tracer) | + +Example using environment variables: + +```env +SCOPE3AI_API_KEY=your_api_key_here +SCOPE3AI_ENVIRONMENT=staging +SCOPE3AI_APPLICATION_ID=my-app +SCOPE3AI_PROJECT_ID=my-project +``` + +Example using initialization parameters in `Scope3AI.init()`: + +```python +scope3 = Scope3AI.init( + api_key="your_api_key_here", + environment="staging", + application_id="my-app", + project_id="my-project", + sync_mode=True, + enable_debug_logging=True +) +``` + +Example using initialization parameters in `Tracer`: + +```python +scope3 = Scope3AI.init( + api_key="your_api_key_here", +) + +# Override application ID for this specific trace +with scope3.trace(application_id="my-specific-app") as tracer: + # Run operations with "my-specific-app" identifier + interact() +``` diff --git a/docs/images/favicon.png b/docs/images/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..ec38768c635c678f9205d8e997855e34f3db9a79 GIT binary patch literal 1455 zcmV;g1yK5lP)BFg3$ zTMHKlQ8@l8py4M}NQ?zs`xesNXELU@ClYpWIh`MaYjV0iV7I>GTh!Mt@)Q22JO4S+fMZ|HzNukjMNesuJ1U zi3EHbMms&_22l|h2g`bSLH;Hqwid=AopVsn8kT@Kc4WcPF^NaCfQ5;`tT;N6-)#^r z;Q0lKrxehV(vh~ri6fmBCKbu)nc8%aH~aendi;>QAY8!q2Wc$vt;p!u-K#fu*ET|L zWua&R@AkC*9gJPrYpwDm%EHa4-GH{j@RRg}6rBT`Ekn3MsF&f2b2b@>jN2np(?G0% zh#1tvanOr_7^Vkoi2gqEGhxf&FK>U;EK(rhQh z^J9|dVF@^1RejyGfp~Ef6&JL;>c>#Pb3sJY{K#IyxUe)u)Z)dLE@p1hjJ{^X^CJhg zfJp4PKnxDKrkQwPeIq+NtKA_zj?pFp5iy?OvLTKQWBto@@ep~g&upgb{_K34M7uDO z{Px$VAwHB`NSyN!byIJeACs_rv*v(tU{72NBVs;GtMLr9A=PYP*x^2rOEREJw8ko< zk)w>G52)*DA0*ah0)(8JQ2#%_2x`j?%kS(={j5?^5rz%Oq@b5z=W{kNr)~^{>J(Xd z!ucjravi4;h<6OhAOD_RhCiaR(xsMf?;ZYQWz|Y0!`EOfAjE>XxwX?dXW#|l9Qicb zz5DOAzip-FMrWG`IXOGAfDj9(bqL1=Vr!?k(`=xG39U+3=VMx;9EgakxfllGHKL37 zR<)L|&S;seXgvkvKY%&2Eh69Ix_j%MuW!nvY2-Euu~jYMS3)6e{6@TAk0e z?pOl)bVc;;uJL8&4h|?+2u6uX)QfB?t!>nwDPf_d^%}G*G(Vec(-Pa(j1QXQ!XTnc z^kXhB*wyc1YvHY(`j#Uu5=+eX&D41gkLAK$7b_sdYjlK>3!AyuT;P6VgD}l=?GWw8 zG;@R@UQGmpwgU1T?$gTswn6lC*8X8@N4Pe16&@Jm~cqbqZBP*r*aX| zh`;*8Sy2sFMp1j&OF=C?JVdFJYXRdR%J2n2eInkGmOf}MUO)-XbUQ=~C|x|j60nky zFW1{s{0_(n8chy5>NS1a%|6(h(yd%mGvpc{sYn zVF}n>q0~UZKQk?(k)8zhM?b-4pIdY{YT?5v@d0}YV|iizk2`$birPp=HSpq;_`vw% z?=VS#&ki&#^7RIh$2`}LL?6JYT92x4!9nk=MG{V9^%0;jF_%}gb9^1-xycDXech}G zTzrx_A`;d*nm`!Lh6zxF4T6Ic0sm*p8EH#O0WB#7w4@Z!l7FmH1B;=lkcR*O002ov JPDHLkV1k@ws}}$O literal 0 HcmV?d00001 diff --git a/docs/images/logo/dark.svg b/docs/images/logo/dark.svg new file mode 100644 index 0000000..3a650e3 --- /dev/null +++ b/docs/images/logo/dark.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/docs/images/logo/light.svg b/docs/images/logo/light.svg new file mode 100644 index 0000000..1d3da4e --- /dev/null +++ b/docs/images/logo/light.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..a7a949a --- /dev/null +++ b/docs/index.md @@ -0,0 +1,24 @@ +# 👋 Welcome to Scope3AI Python SDK documentation + +Scope3AI is a Python SDK that integrates with popular AI and ML libraries like +OpenAI, Anthropic, HuggingFace, etc. to track, measure, and report on the +environmental impact of AI model usage. It provides an easy interface to the +Scope3AI API for recording interactions and analyzing sustainability metrics +like energy consumption, carbon emissions, and water usage. + +## 📖 Documentation + +- [Quickstart Guide](quickstart.md) - Get up and running quickly with Scope3AI +- [Working with Tracers](tracer.md) - Learn how to work with tracers to measure AI impact +- [API Reference](api/scope3ai.md) - Detailed API documentation + +# Supported libraries + +| Library/SDK | Text generation | TTS | STT | Image Generation | Translation | Multimodal input | Multimodal output | +|-------------|-----------------|----|-----|------------------|-----------|------------------|-------------------| +| Anthropic | ✅ | | | | | | +| Cohere | ✅ | | | | | | +| OpenAI | ✅ | ✅ | ✅ | ✅ | ✅ | Images/Audio | Text/Audio +| Huggingface | ✅ | ✅ | ✅ | ✅ | ✅ | | +| LiteLLM | ✅ | ✅ | ✅ | ✅ | | Images/Audio | Text/Audio +| MistralAi | ✅ | | | | | Images | diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 0000000..6652336 --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,115 @@ +# Quick Start + +The Scope3AI Python SDK helps you track, record and analyze the environmental +impact of your AI model usage. It provides an easy-to-use interface to the +Scope3AI API, which calculates metrics like energy consumption, CO2 emissions, +and water usage for AI model inferences. + +The SDK automatically instruments popular AI libraries and platforms (OpenAI, +Anthropic, Cohere, etc.) to capture metadata about model usage. This allows you +to: + +- Track impact metrics across your AI applications +- Analyze sustainability data by project, client, or environment +- Get real-time feedback on resource consumption + +## Installation + +Install the Scope3AI Python SDK with pip: + +```bash +pip install scope3ai +``` + +Or with uv: + +```bash +uv add scope3ai +``` + +## Initialize the SDK + +Configure your credentials either in code or through environment variables: + +```python +from scope3ai import Scope3AI + +# Initialize with API key +scope3 = Scope3AI.init( + api_key="YOUR_API_KEY", + environment="production", + application_id="my-app" +) +``` + +Or using environment variables: + +```bash +export SCOPE3AI_API_KEY=YOUR_API_KEY +export SCOPE3AI_ENVIRONMENT=production +export SCOPE3AI_APPLICATION_ID=my-app +``` + +```python +from scope3ai import Scope3AI + +scope3 = Scope3AI.init() +``` + +## Enable Specific Providers + +By default, all supported providers are enabled if found in available installed +libraries. You can specify which ones to enable: + +```python +scope3 = Scope3AI.init( + api_key="YOUR_API_KEY", + providers=["openai", "anthropic", "cohere"] +) +``` + +## Using Tracers + +Use the context manager to trace API calls and get their impact: + +```python +with scope3.trace() as tracer: + # Make your API calls here + response = openai.chat.completions.create( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hello!"}] + ) + + # Get impact metrics for all calls in this trace + impact = tracer.impact() + print(f"Total Energy: {impact.total_energy_wh} Wh") + print(f"Total CO2: {impact.total_gco2e} gCO2e") + print(f"Total Water: {impact.total_mlh2o} mL") +``` + +You can also configure metadata per-trace: + +```python +with scope3.trace( + client_id="my-client", + project_id="my-project", + session_id="user-123" +) as tracer: + # Make API calls... +``` + +## Getting Impact Data Synchronously + +Enable sync mode to get impact data immediately: + +```python +scope3.sync_mode = True + +response = openai.chat.completions.create( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hello!"}] +) + +impact = response.scope3ai.impact +print(f"Energy used: {impact.total_energy_wh} Wh") +``` diff --git a/docs/tracer.md b/docs/tracer.md new file mode 100644 index 0000000..56ba3fe --- /dev/null +++ b/docs/tracer.md @@ -0,0 +1,128 @@ +# Using Tracer + +Tracers are the core feature of the Scope3AI SDK that allow you to track the +environmental impact of your AI model usage. Here's a detailed guide on using +tracers effectively: + +## Basic Tracing + +The most basic way to use tracers is with a context manager: + +```python +from scope3ai import Scope3AI + +scope3 = Scope3AI.init(api_key="YOUR_API_KEY") + +with scope3.trace() as tracer: + response = openai.chat.completions.create( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hello"}] + ) + + # Get impact metrics + impact = tracer.impact() + print(f"Energy: {impact.total_energy_wh} Wh") + print(f"CO2: {impact.total_gco2e} gCO2e") + print(f"Water: {impact.total_mlh2o} mL") +``` + +## Nested Traces + +You can nest traces to track different parts of your application: + +```python +with scope3.trace(project_id="outer-project") as outer: + # First API call + response1 = openai.chat.completions.create(...) + + with scope3.trace(project_id="inner-project") as inner: + # Second API call + response2 = openai.chat.completions.create(...) + + # Get impact for inner trace only + inner_impact = inner.impact() + + # Get impact for all calls + total_impact = outer.impact() +``` + +## Per-Trace Metadata + +Each trace can have its own metadata: + +```python +with scope3.trace( + client_id="client-123", + project_id="summarization-project", + application_id="doc-processor", + session_id="user-session-456" +) as tracer: + # API calls will be tagged with this metadata + response = openai.chat.completions.create(...) +``` + +## Async Usage + +The tracer works with async code: + +```python +async def process(): + with scope3.trace() as tracer: + response = await openai.chat.completions.create(...) + await response.scope3ai.wait_impact() + impact = response.scope3ai.impact +``` + +## Direct Impact Access + +Each response object is augmented with a scope3ai attribute: + +```python +response = openai.chat.completions.create(...) + +# Wait for impact calculation if in async mode +response.scope3ai.wait_impact() + +# Access impact metrics +impact = response.scope3ai.impact +print(f"Energy: {impact.total_energy_wh} Wh") +``` + +## Synchronous Mode + +Enable sync mode to get impact data immediately: + +```python +scope3.sync_mode = True + +with scope3.trace() as tracer: + response = openai.chat.completions.create(...) + # Impact is immediately available + print(response.scope3ai.impact.total_energy_wh) +``` + +## Trace Impact Types + +The impact() method returns an object with these metrics: + +- total_energy_wh: Energy usage in watt-hours +- total_gco2e: CO2 emissions in grams of CO2 equivalent +- total_mlh2o: Water usage in milliliters + +Each also includes detailed breakdowns for: +- inference_impact: Impact from model inference +- training_impact: Impact from model training +- total_impact: Combined total impact + +## Error Handling + +Tracers handle errors gracefully: + +```python +with scope3.trace() as tracer: + try: + response = openai.chat.completions.create(...) + except Exception as e: + # Impact is still calculated for any successful calls + impact = tracer.impact() +``` diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 0000000..df6f447 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,80 @@ +site_name: scope3ai-py +site_description: Scope3AI Python SDK Documentation +repo_url: https://github.com/scope3data/scope3ai-py + +theme: + name: material + highlightjs: true + palette: + - media: "(prefers-color-scheme)" + toggle: + icon: material/brightness-auto + name: Switch to light mode + - media: "(prefers-color-scheme: light)" + scheme: default + primary: teal + accent: purple + toggle: + icon: material/weather-sunny + name: Switch to dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + primary: black + accent: lime + toggle: + icon: material/weather-night + name: Switch to system preference + +nav: + - Home: index.md + - Guides: + - Quickstart: quickstart.md + - Tracer: tracer.md + - Configuration: configuration.md + - API reference: + - Scope3AI: api/scope3ai.md + - Tracer: api/tracer.md + - API Client: api/api_client.md + - API Types: api/api_types.md + +plugins: + - search + - mkdocstrings: + handlers: + python: + paths: [.] + options: + docstring_options: + ignore_init_summary: true + docstring_section_style: list + filters: ["!^_"] + heading_level: 2 + inherited_members: true + merge_init_into_class: true + parameter_headings: true + separate_signature: true + show_root_heading: true + show_root_full_path: true + show_signature_annotations: true + show_source: false + show_symbol_type_heading: true + show_symbol_type_toc: true + signature_crossrefs: true + summary: true + +markdown_extensions: + - markdown_include.include: + base_path: . + - admonition + - pymdownx.highlight: + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite + - pymdownx.snippets + - pymdownx.superfences + +extra: + social: + - icon: fontawesome/brands/github + link: https://github.com/pawamoy diff --git a/pyproject.toml b/pyproject.toml index 94ba860..e2f7861 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,6 +60,10 @@ tests = [ openapi = [ "datamodel-code-generator>=0.26.4", ] +dev = [ + "pydoc-markdown>=4.8.2", + "tomli>=2.2.1", +] [tool.semantic_release] assets = [] @@ -126,3 +130,28 @@ insecure = false [tool.semantic_release.publish] dist_glob_patterns = ["dist/*"] upload_to_vcs_release = true + +[tool.pydoc-markdown] +loaders = [ + { type = "python" } +] +processors = [ + { type = "filter" }, + { type = "smart" }, + { type = "crossref" } +] + +[tool.pydoc-markdown.renderer] +type = "markdown" +descriptive_class_title = false +render_toc = false +code_headers = true +docstrings_as_blockquote = false +signature_with_def = true + +[tool.pydoc-markdown.renderer.header_level_by_type] +Module = 1 +Class = 2 +Method = 3 +Function = 3 +Property = 3 diff --git a/scope3ai/__init__.py b/scope3ai/__init__.py index 4521ac7..e3227b9 100644 --- a/scope3ai/__init__.py +++ b/scope3ai/__init__.py @@ -1,5 +1,4 @@ -from .api.client import Client from .lib import Scope3AI -__all__ = ["Client", "Scope3AI"] +__all__ = ["Scope3AI"] __version__ = "0.3.0" diff --git a/scope3ai/api/client.py b/scope3ai/api/client.py index f52e6aa..f54be17 100644 --- a/scope3ai/api/client.py +++ b/scope3ai/api/client.py @@ -15,6 +15,17 @@ class Scope3AIError(Exception): class ClientBase: + """ + Base client class for communicating with the Scope3AI HTTP API. + + Handles authentication and provides core request functionality for both + synchronous and asynchronous clients. + + Attributes: + api_key (Optional[str]): API key for authentication, can be passed in or read from env var + api_url (Optional[str]): URL for the API, defaults to production endpoint + """ + def __init__( self, api_key: Optional[str] = None, diff --git a/scope3ai/api/commandsgen.py b/scope3ai/api/commandsgen.py index f0163a7..dae6cd7 100644 --- a/scope3ai/api/commandsgen.py +++ b/scope3ai/api/commandsgen.py @@ -1,6 +1,6 @@ # generated by generate-client-commands.py # filename: aiapi.yaml -# timestamp: 2025-01-29T02:30:59+00:00 +# timestamp: 2025-02-05T23:50:37+00:00 from typing import Any, Optional @@ -27,7 +27,16 @@ class ClientCommands: + """ + Base class that implements the command methods for interacting with the Scope3AI API. + The execute_request method must be implemented by subclasses to handle the actual HTTP requests. + """ + def execute_request(self, *args, **kwargs) -> Any: + """ + Execute an HTTP request to the Scope3AI API. + Must be implemented by subclasses to handle synchronous or asynchronous requests. + """ raise NotImplementedError def status(self, with_response: Optional[bool] = True) -> StatusResponse: diff --git a/scope3ai/api/tracer.py b/scope3ai/api/tracer.py index ca0a05c..4bde417 100644 --- a/scope3ai/api/tracer.py +++ b/scope3ai/api/tracer.py @@ -5,6 +5,27 @@ class Tracer: + """ + Tracer is responsible for tracking and aggregating environmental impact metrics + from AI model interactions. It supports nested tracing, async operations, and + provides detailed impact breakdowns for energy, emissions and water usage. + + Args: + name (str, optional): Name identifier for the tracer. Defaults to None. + keep_traces (bool, optional): Whether to keep trace history after completion. + Defaults to False. + client_id (str, optional): Client identifier for categorizing traces. + Overrides global `SCOPE3AI_CLIENT_ID` setting. Defaults to None. + project_id (str, optional): Project identifier for categorizing traces. + Overrides global `SCOPE3AI_PROJECT_ID` setting. Defaults to None. + application_id (str, optional): Application identifier for categorizing traces. + Overrides global `SCOPE3AI_APPLICATION_ID` setting. Defaults to None. + session_id (str, optional): Session identifier for tracking user sessions. + Only available at tracer level. Defaults to None. + trace_id (str, optional): Unique identifier for the trace. + Auto-generated if not provided. Defaults to None. + """ + def __init__( self, name: str = None, diff --git a/scope3ai/api/types.py b/scope3ai/api/types.py index 453da36..caae360 100644 --- a/scope3ai/api/types.py +++ b/scope3ai/api/types.py @@ -37,6 +37,12 @@ class Scope3AIContext(BaseModel): + """Context helper for scope3ai. + + Context can be retrieve from object with scope3.context, i.e. response.scope3ai. + This object contains the impact request and response data. + """ + request: Optional[ImpactRow] = Field( None, description="The impact request information. Contains `trace_id` and `record_id`", diff --git a/scope3ai/lib.py b/scope3ai/lib.py index 8f75edd..29ec440 100644 --- a/scope3ai/lib.py +++ b/scope3ai/lib.py @@ -148,6 +148,35 @@ def init( project_id: Optional[str] = None, application_id: Optional[str] = None, ) -> "Scope3AI": + """ + Initialize the Scope3AI SDK with the provided configuration settings. + + Args: + api_key (str, optional): The Scope3AI API key. Can be set via `SCOPE3AI_API_KEY` + environment variable. Required for authentication. + api_url (str, optional): The base URL for the Scope3AI API. Can be set via + `SCOPE3AI_API_URL` environment variable. Defaults to standard API URL. + sync_mode (bool, optional): If True, the SDK will operate synchronously. Can be + set via `SCOPE3AI_SYNC_MODE` environment variable. Defaults to False. + enable_debug_logging (bool, optional): Enable debug level logging. Can be set via + `SCOPE3AI_DEBUG_LOGGING` environment variable. Defaults to False. + providers (List[str], optional): List of providers to instrument. If None, + all available providers will be instrumented. + environment (str, optional): The environment name (e.g. "production", "staging"). + Can be set via `SCOPE3AI_ENVIRONMENT` environment variable. + client_id (str, optional): Client identifier for grouping traces. Can be set via + `SCOPE3AI_CLIENT_ID` environment variable. + project_id (str, optional): Project identifier for grouping traces. Can be set via + `SCOPE3AI_PROJECT_ID` environment variable. + application_id (str, optional): Application identifier. Can be set via + `SCOPE3AI_APPLICATION_ID` environment variable. Defaults to "default". + + Returns: + Scope3AI: The initialized Scope3AI instance. + + Raises: + Scope3AIError: If the instance is already initialized or if required settings are missing. + """ if cls._instance is not None: raise Scope3AIError("Scope3AI is already initialized") cls._instance = self = Scope3AI() @@ -367,7 +396,6 @@ def _pop_tracer(self, tracer: Tracer) -> None: tracer._unlink_parent(self.current_tracer) def _init_providers(self, providers: List[str]) -> None: - """Initialize the specified providers.""" for provider in providers: if provider not in _INSTRUMENTS: raise Scope3AIError( diff --git a/tools/generate-client-commands.py b/tools/generate-client-commands.py index 8915644..8a9afc6 100644 --- a/tools/generate-client-commands.py +++ b/tools/generate-client-commands.py @@ -88,7 +88,15 @@ def generate_imports(self): def generate_start(self): content = [ "class ClientCommands:\n", + ' """\n', + " Base class that implements the command methods for interacting with the Scope3AI API.\n", + " The execute_request method must be implemented by subclasses to handle the actual HTTP requests.\n", + ' """\n', " def execute_request(self, *args, **kwargs) -> Any:\n", + ' """\n', + " Execute an HTTP request to the Scope3AI API.\n", + " Must be implemented by subclasses to handle synchronous or asynchronous requests.\n", + ' """\n', " raise NotImplementedError\n\n", ] self.output.write("".join(content)) diff --git a/tools/generate-docs.py b/tools/generate-docs.py new file mode 100644 index 0000000..fc81886 --- /dev/null +++ b/tools/generate-docs.py @@ -0,0 +1,31 @@ +import sys +from pathlib import Path + +import tomli +from pydoc_markdown import PydocMarkdown +from pydoc_markdown.interfaces import Context + + +def load_config(): + pyproject_path = Path("pyproject.toml") + if not pyproject_path.exists(): + print("Error: pyproject.toml not found") + sys.exit(1) + + with open(pyproject_path, "rb") as f: + return tomli.load(f)["tool"]["pydoc-markdown"] + + +def generate_docs(): + config = load_config() + + for module in config["modules"]["members"]: + module_config = config.copy() + module_config["loaders"][0]["module"] = module + + pydoc = PydocMarkdown(module_config) + pydoc.process(Context(directory=Path.cwd())) + + +if __name__ == "__main__": + generate_docs() From 537dfda19a0afc41f102f9e8fdd8e8166cef8ad8 Mon Sep 17 00:00:00 2001 From: Mathieu Virbel Date: Wed, 5 Feb 2025 18:31:36 -0600 Subject: [PATCH 2/2] fix: remove unused packages --- pyproject.toml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index e2f7861..44ca9f0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,10 +60,6 @@ tests = [ openapi = [ "datamodel-code-generator>=0.26.4", ] -dev = [ - "pydoc-markdown>=4.8.2", - "tomli>=2.2.1", -] [tool.semantic_release] assets = []