### Example LiteLLM warning outputs Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Example console output showing missing dependency warnings during initialization. ```text Output: [92m17:03:50 - LiteLLM:WARNING [0m: common_utils.py:979 - litellm: could not pre-load bedrock-runtime response stream shape — Bedrock event-stream decoding will be unavailable. Error: No module named 'botocore' ``` ```text Output: [92m17:03:50 - LiteLLM:WARNING [0m: common_utils.py:24 - litellm: could not pre-load sagemaker-runtime response stream shape — SageMaker event-stream decoding will be unavailable. Error: No module named 'botocore' ``` -------------------------------- ### Setup test environment Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Imports testing and utility libraries for development. ```python #| hide import yaml from fastcore.test import * from collections import namedtuple from cachy.core import enable_cachy from IPython.display import Markdown from pyskills.core import * ``` -------------------------------- ### Initialize SpecParser instances Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Examples of initializing SpecParser from various OpenAPI and Discovery specifications. ```python gh_ops = SpecParser.from_openapi(gh_spec) stripe_ops = SpecParser.from_openapi(stripe_spec) oai_ops = SpecParser.from_openapi(oai_spec) ant_ops = SpecParser.from_openapi(ant_spec) gem_ops = SpecParser.from_discovery(gem_spec) ``` ```python gh_ops, stripe_ops, oai_ops, ant_ops, gem_ops ``` -------------------------------- ### Inspect OpSpec Examples Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Retrieves and displays specific OpSpec instances for verification. ```python gh_ops[10] ``` ```python stripe_ops[10] ``` ```python oai_ops[0] ``` -------------------------------- ### Install fastspec Source: https://github.com/answerdotai/fastspec/blob/main/nbs/index.ipynb Install the package via pip. ```sh pip install fastspec ``` -------------------------------- ### Load and Inspect API Specifications Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Examples of loading various API specification files and inspecting their structure. ```python oai_spec = dict2obj((specs_path/'openai.with-code-samples.yml').read_yaml()) ``` ```python oai_spec.keys() ``` ```python oai_spec.servers, len(oai_spec.paths) ``` ```python ant_spec = dict2obj((specs_path/'anthropic.yml').read_yaml()) ``` ```python ant_spec.keys() ``` ```python ant_spec.servers, len(ant_spec.paths) ``` ```python gh_spec = dict2obj((specs_path/'github.json').read_json()) stripe_spec = dict2obj((specs_path/'stripe.json').read_json()) stripe_v2_spec = dict2obj((specs_path/'stripe_v2.json').read_json()) gh_spec.keys(), stripe_spec.keys(), stripe_v2_spec.keys() ``` -------------------------------- ### Model Tool Use Output Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Example of a tool_use content block generated by the model. ```json [ { "type": "tool_use", "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "name": "get_stock_price", "input": { "ticker": "^GSPC" } } ] ``` -------------------------------- ### Example: Extracting Batch Cancel Parameters Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Demonstrates parameter extraction for a specific batch cancellation endpoint. ```python path_desc = oai_spec.paths['/batches/{batch_id}/cancel'] ``` ```python _collect_params(path_desc.post, path_desc, oai_spec) ``` -------------------------------- ### Example: Extracting Anthropic File Content Parameters Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Demonstrates parameter extraction for an Anthropic API endpoint including header parameters. ```python path_desc = ant_spec.paths['/v1/files/{file_id}/content?beta=true'] ``` ```python _collect_params(path_desc['get'], path_desc, ant_spec) ``` -------------------------------- ### OpenAI API error handling example Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Demonstrates triggering and parsing an OpenAI authentication error. ```python resp = httpx.post( "https://api.openai.com/v1/chat/completions", headers={"Authorization": "Bearer sk-fake123"}, json={"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]} ) resp.json() ``` ```python resp.error() ``` -------------------------------- ### Usage examples for RequestError Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Demonstrates handling transport-level errors and verifying retry logic. ```python req = httpx.Request("POST", "https://api.openai.com/v1/chat/completions") err = httpx.ConnectError("connection refused", request=req) ae = err.api_error(provider="openai", model="gpt-4o") test_eq(ae.retryable, True) test_eq(ae.error_type, "ConnectError") test_eq(ae.endpoint, "POST /v1/chat/completions") test_eq(ae.provider, "openai") test_eq(ae.model, "gpt-4o") test_is(ae.raw, err) err = httpx.ReadTimeout("read timed out", request=req) test_eq(err.api_error().retryable, True) test_eq(err.api_error().error_type, "ReadTimeout") err = httpx.RemoteProtocolError("server disconnected", request=req) test_eq(err.api_error().retryable, True) err = httpx.UnsupportedProtocol("bad scheme", request=req) test_eq(err.api_error(provider="anthropic").retryable, False) test_eq(err.api_error().error_type, "UnsupportedProtocol") err = httpx.DecodingError("bad gzip", request=req) test_eq(err.api_error().retryable, False) ``` ```python try: httpx.get("http://127.0.0.1:1/nope", timeout=1) except httpx.RequestError as exc: ae = exc.api_error(provider="local") test_eq(ae.retryable, True) test_eq(ae.provider, "local") test_eq(ae.endpoint, "GET /nope") assert isinstance(ae.raw, httpx.RequestError) ``` -------------------------------- ### Test operation grouping Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Setup and verification of nested operation groups. ```python TestOp = namedtuple('TestOp', 'group name op_spec docs_url') ops = [ TestOp("repos", "get", "", ""), TestOp("repos", "list", "", ""), TestOp(["tuned_models"], "get", "", ""), TestOp(["tuned_models", "permissions"], "list", "", ""), TestOp(["tuned_models", "permissions"], "delete", "", ""), ] ``` ```python op_groups = _build_groups(ops); op_groups ``` ```python test_eq(isinstance(op_groups['tuned_models'].permissions, OpGroup), True) ``` ```python op_groups['tuned_models'].get, op_groups['tuned_models'].permissions.delete, op_groups['tuned_models'].permissions.list ``` ```python op_groups['repos'].get, op_groups['repos'].list ``` -------------------------------- ### Model Tool Result Input Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Example of a tool_result content block returned to the model. ```json [ { "type": "tool_result", "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "content": "259.75 USD" } ] ``` -------------------------------- ### GET /repos/{owner}/{repo} Source: https://github.com/answerdotai/fastspec/blob/main/README.md Retrieves details for a specific GitHub repository. ```APIDOC ## GET /repos/{owner}/{repo} ### Description Get a repository from GitHub. ### Parameters #### Path Parameters - **owner** (str) - Required - The account owner of the repository. - **repo** (str) - Required - The name of the repository. ### Request Example ```python resp = await gh_cli.repos.get(owner="AnswerDotAI", repo="fastcore") ``` ``` -------------------------------- ### Usage of SyncTransport Source: https://github.com/answerdotai/fastspec/blob/main/nbs/02_transport.ipynb Example demonstrating a synchronous request and the expected error when attempting to stream via SyncTransport. ```python st = SyncTransport() r = st.request("GET", "https://jsonplaceholder.typicode.com/todos/1") test_eq(r['id'], 1) with expect_fail(Exception, 'iter_sync'): st.stream('GET', 'https://example.com') ``` -------------------------------- ### Google Gemini API error handling example Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Demonstrates triggering and parsing a Google Gemini API error. ```python resp = httpx.post( "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=fake123", json={"contents": [{"parts": [{"text": "hi"}]}]} ) resp.json() ``` ```python resp.error() ``` -------------------------------- ### Stream SSE data from API providers Source: https://github.com/answerdotai/fastspec/blob/main/nbs/01_sse.ipynb Examples of using httpx to stream responses from OpenAI and Anthropic APIs for testing purposes. ```python with httpx.stream("POST", "https://api.openai.com/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"}, json={"model": "gpt-4o-mini", "stream": True, "max_tokens": 20, "messages": [{"role": "user", "content": "Say hello"}]} ) as r: oai_lines = list(r.iter_lines()) oai_lines[:10] ``` ```python with httpx.stream("POST", "https://api.anthropic.com/v1/messages", headers={"x-api-key": os.environ['ANTHROPIC_API_KEY'], "anthropic-version": "2023-06-01"}, json={"model": "claude-sonnet-4-20250514", "stream": True, "max_tokens": 20, "messages": [{"role": "user", "content": "Say hello"}]} ) as r: ant_lines = list(r.iter_lines()) ant_lines[:10] ``` -------------------------------- ### Define Tool Schema Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Example of a JSON schema for a tool definition used in API requests. ```json [ { "name": "get_stock_price", "description": "Get the current stock price for a given ticker symbol.", "input_schema": { "type": "object", "properties": { "ticker": { "type": "string", "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." } }, "required": ["ticker"] } } ] ``` -------------------------------- ### Anthropic API error handling example Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Demonstrates triggering and parsing an Anthropic authentication error. ```python resp = httpx.post( "https://api.anthropic.com/v1/messages", headers={"x-api-key": "sk-fake123", "anthropic-version": "2023-06-01"}, json={"model": "claude-sonnet-4-20250514", "max_tokens": 10, "messages": [{"role": "user", "content": "hi"}]} ) resp.json() ``` ```python resp.error() ``` -------------------------------- ### Execute a request with AsyncTransport Source: https://github.com/answerdotai/fastspec/blob/main/nbs/02_transport.ipynb Example usage of AsyncTransport to perform a POST request to the OpenAI API. ```python t = AsyncTransport() resp = await t.request("POST", "https://api.openai.com/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"}, json_data={"model": "gpt-4o-mini", "max_tokens": 5, "messages": [{"role": "user", "content": "Say hi"}]}) resp ``` -------------------------------- ### Usage examples for HTTPStatusError Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Demonstrates converting HTTP status errors into APIError objects for various API calls. ```python resp = httpx.post( "https://api.anthropic.com/v1/messages", headers={"x-api-key": "sk-fake123", "anthropic-version": "2023-06-01"}, json={"model": "claude-sonnet-4-20250514", "max_tokens": 10, "messages": [{"role": "user", "content": "test api_error_from_http"}]} ) try: resp.raise_for_status() except httpx.HTTPStatusError as exc: print(exc.api_error(provider="anthropic", model="claude-sonnet-4-20250514")) ``` ```python resp = httpx.get( "https://api.github.com/repos/AnswerDotAI/nonexistent-repo-12345", headers={"Authorization": "token ghp_fake123"} ) try: resp.raise_for_status() except httpx.HTTPStatusError as exc: print(exc.api_error()) ``` ```python resp = httpx.post("https://api.anthropic.com/v1/messages", headers={"x-api-key":"sk-fake123","anthropic-version":"2023-06-01"}, json={"model":"claude-sonnet-4-20250514","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}) try: resp.raise_for_status() except httpx.HTTPStatusError as exc: ae = exc.api_error(provider="anthropic") test_eq(ae.status_code, 401) test_eq(ae.retryable, False) test_eq(ae.error_type, "authentication_error") ``` -------------------------------- ### Initialize testing environment Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Imports testing and caching utilities and enables the cachy framework. ```python #| hide from cachy.core import enable_cachy from fastcore.test import * ``` ```python enable_cachy() ``` -------------------------------- ### Initialize synchronous client Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Create a client with sync=True to perform blocking API calls without using await. ```python gh_sync = OpenAPIClient(gh_spec, headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"}, defaults={'owner': 'fastai', 'repo': 'fastcore'}, sync=True) test_eq(gh_sync.repos.get()['full_name'], 'AnswerDotAI/fastcore') ``` -------------------------------- ### Initialize OpenAPIClient Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Instantiate the OpenAPIClient using a provided specification. ```python cli = OpenAPIClient(ant_spec) ``` -------------------------------- ### Gemini API operation grouping Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Example of grouping operations for the Gemini API. ```python ops = [OpFunc(op, None, gem_spec.base_url) for op in gem_spec.ops] ``` ```python ops[:2] ``` ```python gem_groups = _build_groups(ops) ``` ```python len(gem_groups) ``` ```python gem_groups.keys() ``` ```python gem_groups['tuned_models'].permissions.create ``` -------------------------------- ### Initialize OpenAPIClient Source: https://github.com/answerdotai/fastspec/blob/main/nbs/index.ipynb Create an API client instance by providing a parsed spec and necessary authentication headers. ```python ant_cli = OpenAPIClient(ant_spec, headers={"x-api-key": os.environ["ANTHROPIC_API_KEY"], "anthropic-version": "2023-06-01"}) oai_cli = OpenAPIClient(oai_spec, headers={"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"}) gh_cli = OpenAPIClient(gh_spec, headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"}) ``` -------------------------------- ### Usage of SyncOpFunc Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Demonstrates initializing a SyncTransport and executing a synchronous operation. ```python gh_scli = SyncTransport(base_headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"}) gh_sopf = SyncOpFunc(gh_op_spec, gh_scli, gh_spec.base_url) resp = gh_sopf(owner="AnswerDotAI", repo="fastllm") test_eq(resp['private'], False) with expect_fail(Exception, 'async client'): gh_sopf(owner="AnswerDotAI", repo="fastllm", stream=True) ``` -------------------------------- ### Initialize Gemini Client Source: https://github.com/answerdotai/fastspec/blob/main/nbs/index.ipynb Initializes the OpenAPIClient for Gemini using an API key from environment variables. ```python gem_cli = OpenAPIClient(gem_spec, headers={"x-goog-api-key": os.environ["GEMINI_API_KEY"]}) str(gem_cli.models)[:500] ``` -------------------------------- ### Count Schemas and Resources Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Get the total count of defined schemas and resources in the API. ```python len(gem_spec.schemas), len(gem_spec.resources) ``` -------------------------------- ### Initialize OpenAPIClient instance Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Creates an instance of the client using a provided specification. ```python gem_cli = OpenAPIClient(gem_spec) ``` -------------------------------- ### Initialize OpSpec Lists Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Generates OpSpec lists from various provider specifications. ```python oai_ops = openapi_to_ops(oai_spec) ant_ops = openapi_to_ops(ant_spec) gh_ops = openapi_to_ops(gh_spec) stripe_ops = openapi_to_ops(stripe_spec) ``` -------------------------------- ### Handle Authentication and Headers Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Configure the client with required headers like API keys and versioning to avoid authentication or request errors. ```python try: await cli.messages.messages_post(headers={}) except Exception as e: print(e) ``` ```python cli = OpenAPIClient(ant_spec, headers={"x-api-key": os.environ["ANTHROPIC_API_KEY"]}) ``` ```python try: await cli.messages.messages_post(model="claude-sonnet-4-20250514", messages=[{"role":"user","content":"Hi"}], max_tokens=32) except Exception as e: print(e) ``` ```python cli = OpenAPIClient(ant_spec, headers={"x-api-key": os.environ["ANTHROPIC_API_KEY"], "anthropic-version": "2023-06-01"}) ``` ```python await cli.messages.messages_post(model="claude-sonnet-4-20250514", messages=[{"role":"user","content":"Say Hi!"}], max_tokens=32) ``` -------------------------------- ### AsyncTransport Request Execution Source: https://github.com/answerdotai/fastspec/blob/main/nbs/02_transport.ipynb Performs a GET request using AsyncTransport. Redirects are followed by default. ```python r = await AsyncTransport().request("GET", "https://jsonplaceholder.typicode.com/todos/1") test_eq(r['id'], 1) ``` -------------------------------- ### Inspect client models Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Prints documentation for the models group within the client. ```python print(doc(gem_cli.models)) ``` -------------------------------- ### Initialize OpenAPIClient Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Instantiate the client using an OpenAPI specification object. ```python cli = OpenAPIClient(oai_spec) ``` ```python cli = OpenAPIClient(ant_spec) ``` -------------------------------- ### Define OpFunc methods Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb The _prep method resolves arguments into request components, while __call__ executes the request or stream. ```python #| export @patch def _prep(self:OpFunc, args, kwargs): "Resolve call args to (stream, url, headers, query, route, request kwargs)." stream, headers, route, query, body, files = self._split(self._bind(args, kwargs)) url = _join_url(self.base_url, _path(self.path, route_params=route)) if files: kw = dict(body=None, files=files, data=self.form_encoder(body) or None) elif self.request_content_type == "application/x-www-form-urlencoded": kw = dict(body=None, data=self.form_encoder(body)) else: kw = dict(body=body) return stream, url, headers, query, route, kw @patch async def __call__(self:OpFunc, *args, **kwargs): stream, url, headers, query, route, kw = self._prep(args, kwargs) if stream: return self._stream(url, headers=headers, query=query, route=route, **kw) return await self._request(url, headers=headers, query=query, route=route, **kw) ``` -------------------------------- ### Configure Export and Imports Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Sets up the module export and imports necessary dependencies for spec parsing. ```python #| default_exp spec ``` ```python #| export from fastcore.utils import * import pprint from dataclasses import dataclass, field, asdict ``` ```python #| hide import json, yaml from fastcore.test import * ``` -------------------------------- ### Enable caching Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Initializes the caching mechanism. ```python enable_cachy() ``` -------------------------------- ### List Model Methods Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Retrieve all available methods for the models resource. ```python list(gem_spec.resources.models.methods) ``` -------------------------------- ### Access Icons and Documentation Links Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Retrieve icon URLs and the official documentation link from the specification. ```python gem_spec.icons, gem_spec.documentationLink ``` -------------------------------- ### List Schemas and Resources Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Retrieve lists of available schemas and resources defined in the specification. ```python list(gem_spec.schemas)[:10] ``` ```python list(gem_spec.resources) ``` -------------------------------- ### Initialize SSE module dependencies Source: https://github.com/answerdotai/fastspec/blob/main/nbs/01_sse.ipynb Imports necessary modules and enables caching for the SSE parsing module. ```python #| default_exp sse ``` ```python #| export from dataclasses import dataclass import httpx,json from fastcore.utils import * from fastspec.errors import * ``` ```python #| hide from cachy.core import enable_cachy from fastcore.test import * ``` ```python enable_cachy() ``` -------------------------------- ### Initialize and configure imports Source: https://github.com/answerdotai/fastspec/blob/main/nbs/02_transport.ipynb Required imports and default export configuration for the transport module. ```python #| default_exp transport ``` ```python import httpx, json from contextlib import nullcontext from fastspec.errors import ProtocolError from fastspec.sse import aiter_sse ``` -------------------------------- ### Initialize GhApi Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Initializes the GitHub API client for metadata operations. ```python from ghapi.core import GhApi ``` ```python g = GhApi() ``` ```python g.gists ``` -------------------------------- ### Convert Discovery Spec to OpSpec Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Main entry point to transform a full Google Discovery specification into a list of OpSpec objects. ```python #| export def discovery_to_ops(spec): "Convert Google Discovery spec to OpSpec list." schemas = spec.get("schemas", {}) ops = [] def walk(res, group): for mname, m in res.get("methods", {}).items(): verb = m.get("httpMethod", "").upper() if verb.lower() not in _http_verbs: continue path = m.get("path") pdict = _discovery_collect_params(m, spec) bpdict = _discovery_body_params(m, schemas, spec) ops.append(OpSpec( group=group, name=snake(mname), path=path, verb=verb, summary=_clean_desc(m.get("description", "")), route_params=pdict.route_params or _path_params(path), query_params=pdict.query_params, body_params=bpdict.body_params, required_params=sorted(pdict.required_params | bpdict.required_params), param_types={k:v for k,v in merge(pdict.param_types, bpdict.param_types).items() if v}, param_defaults=_plain(merge(pdict.param_defaults, bpdict.param_defaults)), param_docs=merge(pdict.param_docs, bpdict.param_docs), docs_url=str(m.get("documentationLink", "")) )) for rname, child in res.get("resources", {}).items(): walk(child, group + [rname]) for rname, res in spec.get("resources", {}).items(): walk(res, [rname]) return ops ``` -------------------------------- ### Configure library exports and imports Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Sets up the default export module and imports necessary utilities for error handling. ```python #| default_exp errors ``` ```python #| export from fastcore.utils import * import json, httpx ``` -------------------------------- ### Inspect generate_content method Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Prints documentation for the specific generate_content method. ```python print(doc(gem_cli.models.generate_content)) ``` -------------------------------- ### Inspect Image Generation Documentation Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Retrieve the documentation for the image creation tool using the Python interface. ```json { "id": "toolu_012gyhaWFdfVTwJu2fCFb96z", "call": { "function": "python", "arguments": { "code": "doc(cli.images.create_image)" } }, "result": "Creates an image given a prompt. [Learn more](/docs/guides/images).\n\nParameters:\n- prompt (str, required): A text description of the desired image(s). The maximum length is 32000 characters for the GPT image models, 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`.\n- user (str, optional): A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices#end-user-ids).\n- model (str, optional): The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or a GPT image model (`gpt-image-1`, `gpt-image-1-mini`, `gpt-image-1.5`). Defaults to `dall-e-2` unless a parameter specific to the GPT image models is used.\n- n (int, optional): The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported.\n- quality (str, optional): The quality of the image that will be generated. - `auto` (default value) will automatically select the best quality for the given model. - `high`, `medium` and `low` are supported for the GPT image models. - `hd` and `standard` are supported for `dall-e-3`. - `standard` is the only option for `dall-e-2`.\n- response_format (str, optional): The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for the GPT image models, which always return base64-encoded images.\n- output_format (str, optional): The format in which the generated images are returned. This parameter is only supported for the GPT image models. Must be one of `png`, `jpeg`, or `webp`.\n- output_compression (int, optional): The compression level (0-100%) for the generated images. This parameter is only supported for the GPT image models with the `webp` or `jpeg` output formats, and defaults to 100.\n- stream (bool, optional): Generate the image in streaming mode. Defaults to `false`. See the [Image generation guide](/docs/guides/image-generation) for more information. This parameter is only supported for the GPT image models.\n- partial_images (int, optional): The number of partial images to generate. This parameter is used for streaming responses that return partial images. Value must be between 0 and 3. When set to 0, the response will be a single image sent in one streaming event. Note that the final image may be sent before the full number of partial images are generated if the full image is generated more quickly.\n- size (str, optional): The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for the GPT image models, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`.\n- moderation (str, optional): Control the content-moderation level for images generated by the GPT image models. Must be either `low` for less restrictive filtering or `auto` (default value).\n- background (str, optional): Allows to set transparency for the background of the generated image(s). This parameter is only supported for the GPT image models. Must be one of `transparent`, `opaque` or `auto` (default value). When `auto` is used, the model will automatically determine the best background for the image. If `transparent`, the output format needs to support transparency, so it should be set to either `png` (default value) or `webp`.\n- style (str, optional): The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images." } ``` -------------------------------- ### Inspect parameters Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Display the current list of parameters. ```python params ``` -------------------------------- ### Generate Full API Documentation Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Defines and executes a method to generate a complete markdown API reference from the OpenAPI client. ```python #| export def _group_docs(name, g, lvl=2): res = [f"{'#'*lvl} {name}"] if g.__doc__: res.append(g.__doc__) res += [_group_docs(f"{name}.{k}", sub, min(lvl+1, 6)) for k,sub in sorted(g.subgroups.items())] return "\n\n".join(res) @patch def full_docs(self:OpenAPIClient): "Complete markdown API reference: every group and operation." return "\n\n".join(_group_docs(nm, g) for nm,g in sorted(self.groups.items())) ``` ```python fd = gem_cli.full_docs() assert '## tuned_models' in fd assert '### tuned_models.permissions' in fd Markdown(fd[:600]) ``` -------------------------------- ### Execute Conversion Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Run the conversion process on a specification object. ```python gem_ops = discovery_to_ops(gem_spec) ``` -------------------------------- ### Import iter_sync Bridge Source: https://github.com/answerdotai/fastspec/blob/main/nbs/02_transport.ipynb Importing the iter_sync utility from fastcore.aio to bridge async generators. ```python from fastcore.aio import iter_sync ``` -------------------------------- ### Configure default parameters Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Initialize an OpenAPIClient with default values for route parameters to simplify subsequent API calls. ```python gh_api = OpenAPIClient(gh_spec, headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"}, defaults=dict(owner='AnswerDotAI', repo='ghapi')) gh_api.git.get_ref ``` -------------------------------- ### Generate and save an image with the OpenAPI client Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Uses the gpt-image-1 model to generate a logo and save it as a PNG file. ```python resp = await cli.images.create_image( prompt="A clean, modern logo for 'FastSpec' — a developer tool that dynamically generates API clients from OpenAPI specs. Use a lightning bolt integrated with curly braces {}. Minimal, flat design, tech aesthetic, blue and white color scheme.", model="gpt-image-1", size="1024x1024", output_format="png", background="transparent" ) img_data = resp['data'][0]['b64_json'] Path("fastspec_logo.png").write_bytes(base64.b64decode(img_data)) Image.open("fastspec_logo.png").resize((240,240)) ``` -------------------------------- ### Initialize and call OpFunc Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Configure an AsyncTransport and execute an API operation using OpFunc. ```python transport_cli = AsyncTransport(base_headers={"x-api-key": os.environ['ANTHROPIC_API_KEY'],"anthropic-version": "2023-06-01"}) opf = OpFunc(ant_spec.ops[0], transport_cli, ant_spec.base_url) ``` -------------------------------- ### Execute standard API request Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Perform a standard asynchronous request using the initialized OpFunc instance. ```python resp = await opf(model="claude-sonnet-4-20250514", max_tokens=64, messages=[{"role":"user","content":"Hi!"}]) resp ``` -------------------------------- ### Configure access for specific image creation method Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Grant access to the create_image method specifically. ```python allow(cli.images.create_image) assert '__call__' in __pytools__[cli.images.create_image] assert cli.images.create_image_edit not in __pytools__ del __pytools__[cli.images.create_image] ``` -------------------------------- ### Serialize and reconstruct specs Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Demonstrates how to serialize a parsed spec to a dictionary or file and reconstruct it to reduce import-time overhead. ```python sp2 = SpecParser.from_dict(gh_ops.to_dict()) test_eq(sp2.base_url, gh_ops.base_url) test_eq(sp2.ops, gh_ops.ops) test_eq(SpecParser.from_dict(gem_ops.to_dict()).ops, gem_ops.ops) ``` ```python fn = Path('gh_compact.py') gh_ops.save(fn) ns = {} exec(fn.read_text(), ns) test_eq(SpecParser.from_dict(ns['spec']).ops, gh_ops.ops) print(f"{fn.stat().st_size/1e6:.2f}MB, vs {(specs_path/'github.json').stat().st_size/1e6:.1f}MB raw") fn.unlink() ``` -------------------------------- ### Generate Operation Documentation Lines Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Utility to create a formatted documentation line for an operation including its signature and summary. ```python #| export def _op_line(op, sig): head = f"{'.'.join(snake(g) for g in listify(op.group))}.{op.name}" if op.docs_url: head = f"[{head}]({op.docs_url})" s = f"({', '.join(sig.parameters)})" summ = _op_summary(op) return f"{head}{s}: *{summ}*" ``` ```python _op_line(op, sig) ``` -------------------------------- ### Define OpenAPIClient class Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Initializes the client with OpenAPI metadata and configures transport and operation functions. ```python #| export class OpenAPIClient: "Client built from OpenAPI operation metadata; async by default, blocking with `sync=True`." def __init__(self, spec, *, headers=None, timeout=60.0, form_encoder=None, defaults=None, sync=False): tcls,fcls = (SyncTransport,SyncOpFunc) if sync else (AsyncTransport,OpFunc) self.transport = tcls(timeout=timeout, base_headers=headers) enc = ifnone(form_encoder, noop) self.ops = [fcls(o, self.transport, spec.base_url, enc, defaults) for o in spec.ops] self.func_dict = {f"{o.path}:{o.verb.upper()}": o for o in self.ops} self.groups = _build_groups(self.ops) for k,v in self.groups.items(): setattr(self, k, v) ``` -------------------------------- ### Configure access for the entire client Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Grant access to all operations available on the client. ```python allow(cli) assert all('__call__' in __pytools__[o] for o in cli.ops) for o in cli.ops: __pytools__.pop(o, None) ``` -------------------------------- ### Define specifications path Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Sets the base directory for specification files. ```python specs_path = Path('../specs/') ``` -------------------------------- ### Define Discovery Template Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Set a template string for API discovery paths. ```python tmpl = "https://{API}/$discovery/rest?version={VERSION}" ``` -------------------------------- ### cli.images.create_image Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Creates an image based on a provided text prompt. Supports various models, sizes, and output formats. ```APIDOC ## cli.images.create_image ### Description Creates an image given a prompt. This method supports multiple models including DALL-E and GPT image models. ### Parameters - **prompt** (str) - Required - A text description of the desired image(s). - **user** (str) - Optional - A unique identifier representing your end-user. - **model** (str) - Optional - The model to use (e.g., `dall-e-2`, `dall-e-3`, `gpt-image-1`). - **n** (int) - Optional - The number of images to generate (1-10). - **quality** (str) - Optional - The quality of the image (e.g., `auto`, `high`, `hd`). - **response_format** (str) - Optional - Format for DALL-E models (`url` or `b64_json`). - **output_format** (str) - Optional - Format for GPT image models (`png`, `jpeg`, `webp`). - **output_compression** (int) - Optional - Compression level (0-100%) for GPT image models. - **stream** (bool) - Optional - Whether to generate in streaming mode. - **partial_images** (int) - Optional - Number of partial images for streaming (0-3). - **size** (str) - Optional - The dimensions of the generated image. - **moderation** (str) - Optional - Content-moderation level for GPT image models. - **background** (str) - Optional - Background transparency setting for GPT image models. - **style** (str) - Optional - Style for DALL-E 3 (`vivid` or `natural`). ``` -------------------------------- ### Inspect Audio Operations Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Displays the signature and documentation for audio-related operations. ```python cli.audio.create_speech ``` ```python cli.audio ``` -------------------------------- ### Configure access for OpFunc Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Manage permissions for the OpFunc operation. ```python allow({OpFunc: ['__call__']}) assert '__call__' in __pytools__[OpFunc] __pytools__[OpFunc].discard('__call__') ``` -------------------------------- ### Test SSE error parsing Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Demonstrates parsing of sample error events from OpenAI, Anthropic, and Gemini. ```python oai_sse = {"code": "rate_limit_exceeded", "message": "Rate limit exceeded"} ant_sse = {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}} gem_sse = {"error": {"code": 500, "message": "An internal error has occurred", "status": "INTERNAL"}} for name, evt in [("OpenAI", oai_sse), ("Anthropic", ant_sse), ("Gemini", gem_sse)]: error = _parse_sse_error_event(evt) print(f"{name:10s} | msg={error.message!r:45s} | et={error.type!r:25s} | code={error.code!r}") ``` -------------------------------- ### Inspect Endpoint Details Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Access endpoint metadata and path information. ```python cli.responses.create_response ``` ```python cli.responses.create_response.path, cli.responses.create_response.verb ``` -------------------------------- ### List Specification Files Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Lists files located in the local specifications directory. ```python specs_path = Path('../specs/') specs_path.ls() ``` -------------------------------- ### Access Nested Gemini Resources Source: https://github.com/answerdotai/fastspec/blob/main/nbs/index.ipynb Demonstrates accessing nested resource groups via attribute chaining. ```python gem_cli.tuned_models.permissions.create ``` -------------------------------- ### Process provider error events Source: https://github.com/answerdotai/fastspec/blob/main/nbs/00_errors.ipynb Demonstrates parsing error events from OpenAI, Anthropic, and Gemini providers. ```python for name, evt in [("OpenAI", oai_sse), ("Anthropic", ant_sse), ("Gemini", gem_sse)]: err = api_error_from_event(evt, provider=name.lower()) print(err) ``` -------------------------------- ### Generate and Save an Image Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Use the GPT image model to generate a logo, decode the base64 response, and save it to a file. ```python resp = await cli.images.create_image( prompt="A clean, modern logo for 'FastSpec' — a developer tool that dynamically generates API clients from OpenAPI specs. Use a lightning bolt integrated with curly braces {}. Minimal, flat design, tech aesthetic, blue and white color scheme.", model="gpt-image-1", size="1024x1024", output_format="png", background="transparent" ) img_data = json.loads(resp)['data'][0]['b64_json'] Path("fastspec_logo.png").write_bytes(base64.b64decode(img_data)) Image.open("fastspec_logo.png").resize((240,240)) ``` -------------------------------- ### Parse API Specifications Source: https://github.com/answerdotai/fastspec/blob/main/nbs/index.ipynb Load and parse OpenAPI or Google Discovery specifications from local files. ```python specs_path = Path('../specs/') # OpenAPI specs (Anthropic, OpenAI, GitHub, Stripe) ant_spec = SpecParser.from_openapi(dict2obj(yaml.safe_load((specs_path/'anthropic.yml').read_text()))) oai_spec = SpecParser.from_openapi(dict2obj(yaml.safe_load((specs_path/'openai.with-code-samples.yml').read_text()))) gh_spec = SpecParser.from_openapi(dict2obj(json.loads((specs_path/'github.json').read_text()))) # Google Discovery spec (Gemini) gem_spec = SpecParser.from_discovery(dict2obj(json.loads((specs_path/'gemini.json').read_text()))) ant_spec, oai_spec, gh_spec, gem_spec ``` -------------------------------- ### Explore Client Operations Source: https://github.com/answerdotai/fastspec/blob/main/README.md Access endpoint groups and inspect operation signatures. ```python ant_cli.messages ``` ```python ant_cli.models.models_get ``` -------------------------------- ### Generate parameter list Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Iterates through OpenAPI parameters to generate a list of signature parameters. ```python params = [] for pname in op.route_params + op.query_params + op.body_params: params.append(_mk_param(pname, pname in op.required_params, op.param_types.get(pname), op.param_defaults.get(pname))) ``` -------------------------------- ### Verify parameter binding Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Test how default parameters and explicit arguments are bound to API routes. ```python ref_op = gh_api.func_dict['/repos/{owner}/{repo}/git/ref/{ref}:GET'] _,_,route,_,_,_ = ref_op._split(ref_op._bind(('heads/master',), {})) test_eq(route, dict(owner='AnswerDotAI', repo='ghapi', ref='heads/master')) _,_,route,_,_,_ = ref_op._split(ref_op._bind((), dict(owner='fastai', ref='heads/main'))) test_eq(route, dict(owner='fastai', repo='ghapi', ref='heads/main')) ``` -------------------------------- ### Import YAML Source: https://github.com/answerdotai/fastspec/blob/main/nbs/index.ipynb Import the yaml module for processing spec files. ```python import yaml ``` -------------------------------- ### Split OpFunc parameters Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Splits keyword arguments into route, query, body, and file parameters based on the operation definition. ```python @patch def _split(self:OpFunc, kwargs): "Split kwargs into route/query/body/files + control kwargs." stream = kwargs.get("stream", False) headers = kwargs.pop("_headers", {}) # Map sanitized names back to originals rsparams = {v:k for k,v in self.sparams.items()} route, query, body, files = {}, {}, {}, {} for k,v in kwargs.items(): if v is UNSET: continue orig = rsparams.get(k, k) if orig in self.route_params: route[orig] = v elif orig in self.file_params: files[orig] = v elif orig in self.query_params: query[orig] = v elif orig in self.body_params: body[orig] = v for k,v in self.defaults.items(): if k in self.route_params: route.setdefault(k, v) elif k in self.query_params: query.setdefault(k, v) query.update(kwargs.pop("_query", {})) body.update(kwargs.pop("_body", {})) if self.verb in ("GET", "DELETE", "HEAD", "OPTIONS") and not body: body = None return stream, headers, route, query, body, files ``` ```python opf._split({'limit': 2, 'after': 'this'}) ``` -------------------------------- ### Configure AI Tool Access Levels Source: https://github.com/answerdotai/fastspec/blob/main/nbs/index.ipynb Use the allow() function to define the scope of operations available to the AI sandbox, ranging from specific methods to full client access. ```python allow(oai_cli.images.create_image) ``` ```python allow(oai_cli.chat) ``` ```python allow(oai_cli) ``` ```python allow({OpFunc: ['__call__']}) ``` -------------------------------- ### Inspect Operation Signatures Source: https://github.com/answerdotai/fastspec/blob/main/nbs/index.ipynb Retrieve the signature and parameter documentation for a specific API operation. ```python ant_cli.models.models_get ``` -------------------------------- ### Configure access for image operations Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Grant access to image operations and verify permissions. ```python allow(cli.images) assert all('__call__' in __pytools__[o] for o in cli.images.ops) assert cli.audio.create_speech not in __pytools__ for o in cli.images.ops: __pytools__.pop(o, None) ``` -------------------------------- ### Export project notebooks Source: https://github.com/answerdotai/fastspec/blob/main/nbs/01_sse.ipynb Utility command to export notebooks using nbdev. ```python #|hide #|eval: false import nbdev; nbdev.nbdev_export() ``` -------------------------------- ### AI Tool Integration Source: https://github.com/answerdotai/fastspec/blob/main/README.md Methods for exposing fastspec clients to AI assistants within a sandbox environment. ```APIDOC ## AI Tool Integration ### Description Register fastspec operations to allow sandboxed AI code to execute specific network-enabled calls. ### Access Levels - **Single method access**: allow(client.method) - **Single group access**: allow(client.group) - **Single client access**: allow(client) - **Full API access**: allow({OpFunc: ['__call__']}) ``` -------------------------------- ### Render operation docstring with mk_doc Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Generates a formatted docstring for an operation, including summary, documentation URL, and parameter details. ```python #| export def mk_doc(op, sig, sparams): "Render operation docstring with summary, docs URL, and parameter hints." lines = [_op_summary(op)] if op.docs_url: lines.append(f"\nDocs: {op.docs_url}") if sig.parameters: lines.append("\nParameters:") req = set(op.required_params or []) # Reverse map: sparamsitized → original, for looking up docs/required rsparams = {v:k for k,v in sparams.items()} for nm,p in sig.parameters.items(): orig = rsparams.get(nm, nm) r = f"default: {p.default!r}" if p.default not in (Parameter.empty, UNSET) else "required" if orig in req else "optional" ann = '' if p.annotation is Parameter.empty else p.annotation.__name__ desc = (op.param_docs or {}).get(orig, "") lines.append(f"- {nm} ({ann}, {r}){': ' + desc if desc else ''}") return "\n".join(lines) ``` ```python print(mk_doc(op, sig, sparams)) ``` -------------------------------- ### Inspect operation specification Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Retrieves and displays the first operation from the OpenAI specification. ```python op = oai_spec.ops[0]; op ``` -------------------------------- ### Import required dependencies Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Imports necessary libraries for HTTP requests, JSON handling, and specification parsing. ```python #| export import httpx,json,keyword from inspect import Parameter, Signature from urllib.parse import urlparse, urljoin, quote from fastcore.utils import * from fastcore.meta import delegates from fastspec.errors import APIError from fastspec.spec import OpSpec, SpecParser, snake, sanitize_param_name from fastspec.transport import AsyncTransport,SyncTransport ``` -------------------------------- ### Normalize descriptions Source: https://github.com/answerdotai/fastspec/blob/main/nbs/03_spec.ipynb Converts a description string into a compact one-liner. ```python #| export def _clean_desc(v): "Normalize a description string to a compact one-liner." if not isinstance(v, str): return "" return " ".join(v.strip().split()) ``` -------------------------------- ### Retrieve GitHub Repository Data Source: https://github.com/answerdotai/fastspec/blob/main/nbs/index.ipynb Fetches repository details by passing route parameters as function arguments. ```python resp = await gh_cli.repos.get(owner="AnswerDotAI", repo="fastcore") resp['full_name'], resp['description'], resp['stargazers_count'] ``` -------------------------------- ### Create function signature Source: https://github.com/answerdotai/fastspec/blob/main/nbs/04_oapi.ipynb Generates a function signature from the sorted parameter list. ```python Signature(params) ```