diff --git a/apps/docs/src/content/docs/en/pages/architectures/artificial-intelligence/ai-inference-architecture.mdx b/apps/docs/src/content/docs/en/pages/architectures/artificial-intelligence/ai-inference-architecture.mdx index 2194d9596f..249e82b6a1 100644 --- a/apps/docs/src/content/docs/en/pages/architectures/artificial-intelligence/ai-inference-architecture.mdx +++ b/apps/docs/src/content/docs/en/pages/architectures/artificial-intelligence/ai-inference-architecture.mdx @@ -1,8 +1,8 @@ --- title: Catalog-model inference API description: >- - Serve an OpenAI-compatible inference endpoint from your own application - domain, with a function that calls the model with Azion.AI.run. + Serve an OpenAI-compatible inference endpoint from your own Application + domain, with a Function that calls the model with Azion.AI.run. meta_tags: 'reference architecture, catalog-model inference API, AI Inference, Azion.AI.run, functions, applications, OpenAI-compatible endpoint, inference endpoint' namespace: docs_arch_ai_inference permalink: /documentation/use-cases/build-and-run-ai-workloads/ai-inference-architecture/ @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -A client that calls a model needs one address to post to and one response shape to read. This design puts that address on an application you deploy: the application is the inference endpoint, and the model runs behind it. Use it when your team already serves an HTTP API and wants inference to be one more path on it. You own the domain, and no inference server stays running. The design implements the use case [Add AI features to existing applications](/en/documentation/use-cases/build-and-run-ai-workloads/add-ai-features-to-existing-applications/). +A client that calls a model needs one address to post to and one response shape to read. This design puts that address on an Application you deploy: the Application is the inference endpoint, and the model runs behind it. Use it when your team already serves an HTTP API and wants inference to be one more path on it. You own the domain, and no inference server stays running. The design implements the use case [Add AI features to existing applications](/en/documentation/use-cases/build-and-run-ai-workloads/add-ai-features-to-existing-applications/). [How AI Inference works](/en/documentation/platform/ai-inference/how-it-works/) covers the hand-offs inside a single call. This page describes the shape you deploy around them. @@ -26,10 +26,12 @@ Solid arrows carry the request, and dotted arrows carry the response. Each label %%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% flowchart TD Client(["OpenAI-compatible client"]) - App["application"] - Fn["function with the prompt and the model id"] + WL["Workload"] + App["Application"] + Fn["Function"] AI["AI Inference"] - Client -->|"1, 2. POST /v1/chat/completions"| App + Client -->|"1. POST /v1/chat/completions"| WL + WL -->|"2. request"| App App -->|"3. Run Function"| Fn Fn -->|"4. Azion.AI.run"| AI AI -.->|"5. generated response"| Fn @@ -39,29 +41,29 @@ flowchart TD ### Dataflow -1. A client posts an OpenAI-compatible request to `/v1/chat/completions` on the application domain. -2. The nearest data center receives the request and hands it to the application. -3. The application applies its policies, checks the authentication you configured, and calls the function. -4. The function preprocesses the input and calls the model with `Azion.AI.run`, which reaches AI Inference through the Azion Cells API. -5. AI Inference runs the model and returns the generated response to the function. -6. The function shapes that response and returns it to the client along the same path. +1. A client posts an OpenAI-compatible request to `/v1/chat/completions` on a domain of the Workload. +2. A data center near the client receives the request, and the Workload's deployment sets the Application that handles it. +3. The Application runs its rules, including any authentication check you add, and a rule runs the Function with the _Run Function_ behavior. +4. The Function builds the request body and calls the model with `Azion.AI.run`. +5. AI Inference runs the model and returns the generated response to the Function. +6. The Function shapes that response and returns it to the client along the same path. -The client knows nothing about Azion. It posts JSON to a URL and reads JSON back, as it would against any OpenAI-compatible service. Behind the domain, one execution does the rest, and the function holds the request open until the model responds. No arrow leaves for an inference host, because the function configures no base URL and names no host. It passes a model id, and Azion places the call. +The client knows nothing about Azion. It posts JSON to a URL and reads JSON back, as it would against any OpenAI-compatible service. Behind the domain, one execution does the rest, and the Function holds the request open until the model responds. No arrow leaves for an inference host, because the Function passes no base URL and names no host. It passes a model id, and Azion places the call. --- ## Components -- [Applications](/en/documentation/platform/applications/): receives the request on your domain and applies its policies before any of your code runs. It is what makes the endpoint yours, because the domain, the path, and the authentication in front of the function are all configured here. Azion issues no credential for a model call, so an endpoint with no check of its own answers anyone who finds it. +- [Workloads](/en/documentation/platform/workloads/): receives the request on its domains, the workload domain or a custom domain, and its deployment sets the Application. The address the client posts to belongs to the Workload. +- [Applications](/en/documentation/platform/applications/): runs its rules on the request before any of your code runs. The path the Function answers and any authentication in front of it are set in those rules. `Azion.AI.run` takes no credential, so an endpoint with no check of its own answers anyone who finds it. - [Functions](/en/documentation/platform/functions/): holds the inference logic and issues the model call. Your code runs nowhere else in the design, so the prompt, the model id, the context retrieved from a store, and any external service the call needs all sit in one execution. -- [AI Inference](/en/documentation/platform/ai-inference/): runs the model, which is what removes the inference server from the design. You load no model and size no cluster, and the id from [AI models](/en/documentation/platform/ai-inference/models/) is the only address the function needs. -- [Orchestrator](/en/documentation/platform/orchestrator/): manages the requests for Azion Cells execution. `Azion.AI.run` reaches a model through the Azion Cells API, which is the part of Orchestrator this design depends on. -- **Azion's distributed infrastructure**: runs every part above. It is why the design has no region to choose. The data center nearest the client answers the request, and you select none of them. -- [Real-Time Metrics](/en/documentation/platform/real-time-metrics/): reports the traffic and performance of the application that serves the endpoint. A design with no inference server of your own still needs a view of what the endpoint carried. +- [AI Inference](/en/documentation/platform/ai-inference/): runs the model, which is what removes the inference server from the design. You load no model and size no cluster, and the id from [AI models](/en/documentation/platform/ai-inference/models/) is the only address the Function needs. +- **Azion's distributed infrastructure**: runs every part above. It is why the design has no region to choose. A data center near the client answers the request, and you select none of them. +- [Real-Time Metrics](/en/documentation/platform/real-time-metrics/): reports the traffic and performance of the Application that serves the endpoint. A design with no inference server of your own still needs a view of what the endpoint carried. - [Real-Time Events](/en/documentation/platform/real-time-events/): tracks individual requests, raw data, and logs. When a response is wrong, the request that produced it is what you read here. :::note -Azion Cells is an advanced feature that is part of Orchestrator. To activate it, contact Azion's sales team to verify the requirements and enable the product in your account. +On the Hobby and Pro plans, AI Inference is available upon request, subject to approval. For the access each plan gives, refer to [AI Inference limits](/en/documentation/platform/ai-inference/limits/). ::: --- @@ -70,7 +72,7 @@ Azion Cells is an advanced feature that is part of Orchestrator. To activate it, - [Add AI features to existing applications](/en/documentation/use-cases/build-and-run-ai-workloads/add-ai-features-to-existing-applications/) - builds this design end to end, with the summarization function and the API route. - [AI Inference quickstart](/en/documentation/platform/ai-inference/quickstart/) - deploys the design and posts a first request to a model on the domain it assigns. -- [How to deploy the AI Inference Starter Kit template](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) - creates the application, the function, and the domain this page describes, in one deployment. +- [How to deploy the AI Inference Starter Kit template](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) - creates the Workload with its deployment, the Application, and the Function this page describes, in one deployment. - [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) - carries the request body both interfaces accept, and the `curl` form for the HTTP endpoint. --- @@ -82,7 +84,7 @@ Azion Cells is an advanced feature that is part of Orchestrator. To activate it, The invocation chain hand-off by hand-off, and where Azion's part ends. The id to pass, and what each model accepts. The ceilings a model call runs against, and when Azion deprovisions a model. - The store a function reads context from before it calls a model. + The store a Function reads context from before it calls a model. The embedding queries that build the context a prompt carries. diff --git a/apps/docs/src/content/docs/en/pages/build/functions/glossary.mdx b/apps/docs/src/content/docs/en/pages/build/functions/glossary.mdx index ae75cef242..692cc64f1f 100644 --- a/apps/docs/src/content/docs/en/pages/build/functions/glossary.mdx +++ b/apps/docs/src/content/docs/en/pages/build/functions/glossary.mdx @@ -15,7 +15,6 @@ Definitions for the terms the [Functions](/en/documentation/platform/functions/) | Args | The JSON object a [function instance](/en/documentation/platform/applications/functions-instances/) passes into the execution context of the function. An instance that sets Args replaces the default Args of the function as a whole. [How it works](/en/documentation/platform/functions/how-it-works/) shows which Args the function receives. | | Azion Bundler | The open-source framework adapter that transforms a framework project into functions that run on Azion Runtime. [How it works](/en/documentation/platform/functions/how-it-works/) describes the four stages of the build, from framework detection to the deployment of the generated functions. | | Azion Runtime | The environment that executes the handler of a function. [Azion Runtime](/en/documentation/devtools/runtime/) runs JavaScript built on Web standards. A function also calls the [Azion APIs](/en/documentation/devtools/runtime/api-reference/azion-runtime-globals/), which reach environment variables, stores, and AI Inference. | -| Cell | The isolation environment a function runs inside, based on V8 isolates. Each Cell is a lightweight execution context with no direct access to the underlying operating system, which is why a function cannot read OS properties, resolve DNS through native system calls, or open low-level sockets. [Node.js compatibility](/en/documentation/devtools/runtime/node/) lists what that excludes. | | code editor | The editor in Azion Console where you write and edit the code of a function. The [code editor](/en/documentation/platform/functions/code-editor/) runs the Monaco editor from VS Code, and shows the output of the function through Preview deployment. | | CPU time | The active computation a single invocation performs, capped at 2 seconds. It excludes time spent waiting on `fetch()`, so a function that waits on an origin stays far from this ceiling however long the request takes. A function that exceeds it is terminated. Compare wall-clock time, and refer to [Limits](/en/documentation/platform/functions/limits/). | | environment variable | A value stored outside the code of a function and read with `Azion.env.get()` or `process.env`. In a deployed function, the `env` parameter of the handler is an empty object. [Environment variables](/en/documentation/platform/functions/environment-variables/) keep API keys, credentials, and access tokens out of the codebase. | diff --git a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/api-reference/ai/ai.mdx b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/api-reference/ai/ai.mdx index be50e9292d..b0eb949527 100644 --- a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/api-reference/ai/ai.mdx +++ b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/api-reference/ai/ai.mdx @@ -1,7 +1,7 @@ --- title: AI Inference API description: >- - Call the Azion.AI.run binding inside a function to invoke an AI Inference + Call the Azion.AI.run binding inside a Function to invoke an AI Inference model, and look up its parameters and return value. meta_tags: 'AI Inference, Azion.AI.run, runtime binding, model invocation, functions, runtime api' namespace: documentation_runtime_ai @@ -12,22 +12,22 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -`Azion.AI.run` is the binding a [function](/en/documentation/platform/functions/) calls to invoke a model on [AI Inference](/en/documentation/platform/ai-inference/). It is a global of [Azion Runtime](/en/documentation/devtools/runtime/), so a function reaches it with no import line and no credential. The binding carries the model id and the request body. The fields that body accepts, and the object the model returns, are the same over the HTTP endpoint and are documented in [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +`Azion.AI.run` is the binding a [Function](/en/documentation/platform/functions/) calls to invoke a model on [AI Inference](/en/documentation/platform/ai-inference/). It is a global of [Azion Runtime](/en/documentation/devtools/runtime/), so a Function reaches it with no import line and no credential. The binding carries the model id and the request body. The fields that body accepts, and the object the model returns, are the same over the HTTP endpoint and are documented in [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). :::note -Under `azion dev`, `Azion.AI` is `undefined`, and a call to `Azion.AI.run` throws `TypeError: Cannot read properties of undefined (reading 'run')`. Test model calls on a deployed function. +Under `azion dev`, `Azion.AI` is `undefined`, and a call to `Azion.AI.run` throws `TypeError: Cannot read properties of undefined (reading 'run')`. Test model calls on a deployed Function. ::: --- ## Parameters -`Azion.AI.run` takes two parameters, and the call is asynchronous: a function awaits it and reads the model response from the resolved value. +`Azion.AI.run` takes two parameters, and the call is asynchronous: a Function awaits it and reads the model response from the resolved value. | Parameter | Type | Description | | --- | --- | --- | | Model id | string | The id of the model to invoke, in the form its model page states. | -| Request body | object | The request fields for the operation. The model id is not repeated inside it. | +| Request body | object | The request fields for the operation. A `model` field inside it is ignored, and so is a field the model does not know. | Model ids differ in form between models, so copy the id from the model's own page in [AI models](/en/documentation/platform/ai-inference/models/) rather than deriving it from the model name. @@ -35,7 +35,7 @@ Model ids differ in form between models, so copy the id from the model's own pag ## Call a model -A call to a chat model inside a function: +A call to a chat model inside a Function: ```ts const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { @@ -52,7 +52,19 @@ return modelResponse ## Return value -The resolved value is the object the model returns. A chat model returns a `chat.completion` object, an embedding model returns a `list` of embeddings, and a reranking model returns the ranked results. The generated text of a chat model sits at `modelResponse?.choices?.[0]?.message?.content`, which is the content of the first entry in `choices`. Every field of the three shapes is listed in [Model invocation](/en/documentation/platform/ai-inference/model-invocation/#response-fields). +The resolved value is the object the model returns. A chat model returns a `chat.completion` object, an embedding model returns a `list` of embeddings, and a reranking model returns the ranked results. With `stream` set to `true` in the body, the call resolves to an async iterator of `chat.completion.chunk` objects instead, which the Function reads with `for await`. The `model` field of a response is the account's internal id for the model, which can differ from the id the call passed. The generated text of a chat model sits at `modelResponse?.choices?.[0]?.message?.content`, which is the content of the first entry in `choices`. Every field of the three shapes is listed in [Model invocation](/en/documentation/platform/ai-inference/model-invocation/#response-fields). + +--- + +## List models + +`Azion.AI.models()` returns the ids of the models your account can call, as an array of strings. It takes no argument, and the call is asynchronous: + +```ts +const modelIds = await Azion.AI.models() +``` + +The list can hold two forms of one model's id, a repository path and a lowercase form, and either one selects that model in `Azion.AI.run`. --- diff --git a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/compatibility/node-polyfills/cells-node.mdx b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/compatibility/node-polyfills/cells-node.mdx index 49c49ab77f..1ebfcac22c 100644 --- a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/compatibility/node-polyfills/cells-node.mdx +++ b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/compatibility/node-polyfills/cells-node.mdx @@ -43,10 +43,10 @@ The table lists each module with its status. Where a module page exists, the mod - 🟡 **Partially supported**: only some methods or features are available. - 🔴 **Build-only**: the module is included so the build completes without errors, but its API calls do not work at runtime. -:::note[About the Azion Cells runtime environment] -A function on Azion runs inside a **Cell**, the isolation environment Azion builds on **V8 isolates**. A Cell is a lightweight, secure execution context, and the code inside it has no direct access to the operating system underneath. +:::note[About the isolation environment] +A function on Azion runs inside an isolation environment that Azion builds on **V8 isolates**. It is a lightweight, secure execution context, and the code inside it has no direct access to the operating system underneath. -For multi-tenant security and infrastructure integrity, a Cell does not give a function: +For multi-tenant security and infrastructure integrity, the isolation environment does not give a function: - The properties of the machine that runs it. `node:os` and `process` return fixed values instead, such as `linux` for `os.platform()`, an empty string for `os.hostname()`, and `0` for `os.totalmem()`. - DNS resolution through native system calls (`node:dns`, `node:dns/promises`). diff --git a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/debugging/debugging.mdx b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/debugging/debugging.mdx index 7c5fa3e470..637d2b2a61 100644 --- a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/debugging/debugging.mdx +++ b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/debugging/debugging.mdx @@ -43,7 +43,7 @@ To read the output from the terminal with Azion CLI: azion logs cells --tail ``` -The terminal prints the console messages of the last 5 minutes and keeps printing new ones. Add `--function-id` to restrict the output to one function. The subcommand is named `cells` because a function runs inside a Cell, the isolation environment Azion builds on V8 isolates. +The terminal prints the console messages of the last 5 minutes and keeps printing new ones. Add `--function-id` to restrict the output to one function. To send the same output to an endpoint you own: diff --git a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/glossary.mdx b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/glossary.mdx index 5e5f062254..86455cdf37 100644 --- a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/glossary.mdx +++ b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/glossary.mdx @@ -8,7 +8,7 @@ namespace: documentation_runtime_glossary permalink: /documentation/devtools/runtime/glossary/ --- -This glossary defines the terms that [Azion Runtime](/en/documentation/devtools/runtime/) uses in its own way. For the terms it shares with Functions, such as handler, Cell, and wall-clock time, refer to the [Functions glossary](/en/documentation/platform/functions/glossary/). +This glossary defines the terms that [Azion Runtime](/en/documentation/devtools/runtime/) uses in its own way. For the terms it shares with Functions, such as handler and wall-clock time, refer to the [Functions glossary](/en/documentation/platform/functions/glossary/). | Term | Definition | | --- | --- | diff --git a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/how-it-works.mdx b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/how-it-works.mdx index 12178b05aa..9f02fb59bc 100644 --- a/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/how-it-works.mdx +++ b/apps/docs/src/content/docs/en/pages/devtools/azion-edge-runtime/how-it-works.mdx @@ -19,9 +19,9 @@ The sections cover the execution model, the request lifecycle, handler shapes, t ## Execution model -Each invocation of a function runs in an isolate, a V8 execution context. Functions run inside Cells, an isolation environment based on V8 isolates. Each Cell is a lightweight execution context with no direct access to the underlying operating system. The memory limit of a function applies per isolate, and a function that exceeds its CPU time is terminated. For the values, refer to [Functions limits](/en/documentation/platform/functions/limits/). +Each invocation of a function runs in an isolate, a V8 execution context, inside an isolation environment based on V8 isolates. That environment gives the code no direct access to the underlying operating system. The memory limit of a function applies per isolate, and a function that exceeds its CPU time is terminated. For the values, refer to [Functions limits](/en/documentation/platform/functions/limits/). -For multi-tenant security and infrastructure integrity, a Cell keeps three things from the code: +For multi-tenant security and infrastructure integrity, the isolation environment keeps three things from the code: - The properties of the host operating system. `node:os` returns empty strings or zeros for the hostname, the release, and the memory fields, while its `platform()` and `type()` calls return the generic values `linux` and `Linux`. - DNS resolution through native system calls. A call such as `dns.lookup()` from `node:dns` throws `Error: [unenv] dns.lookup is not implemented yet!`. diff --git a/apps/docs/src/content/docs/en/pages/guides/agents-and-rag/embed-documents-into-a-vector-table.mdx b/apps/docs/src/content/docs/en/pages/guides/agents-and-rag/embed-documents-into-a-vector-table.mdx index 9133e6b1f2..b735335aa8 100644 --- a/apps/docs/src/content/docs/en/pages/guides/agents-and-rag/embed-documents-into-a-vector-table.mdx +++ b/apps/docs/src/content/docs/en/pages/guides/agents-and-rag/embed-documents-into-a-vector-table.mdx @@ -47,7 +47,7 @@ The examples read the bucket `my-bucket`, embed with `Qwen/Qwen3-Embedding-4B` a ## Create the vector table -The vector column declares the width of the vectors it holds, and the embedding request asks for the same width. `Qwen/Qwen3-Embedding-4B` returns one of five widths, `256`, `512`, `1024`, `2048`, or `4096`, through the `dimensions` field, so a `F32_BLOB(1024)` column matches a request for `1024`. A vector index needs a table with a `ROWID` or a single-column primary key, and its second argument sets the distance metric. +The vector column declares the width of the vectors it holds, and the embedding request asks for the same width. `Qwen/Qwen3-Embedding-4B` returns the width the `dimensions` field asks for, `256`, `512`, `1024`, or `2048`, so a `F32_BLOB(1024)` column matches a request for `1024`. With `dimensions` set to `4096`, or left out, the vector is `2560` wide. A vector index needs a table with a `ROWID` or a single-column primary key, and its second argument sets the distance metric. To create the table and its index, send both statements to the query endpoint: diff --git a/apps/docs/src/content/docs/en/pages/guides/getting-to-know-azion-console/getting-to-know-azion-console.mdx b/apps/docs/src/content/docs/en/pages/guides/getting-to-know-azion-console/getting-to-know-azion-console.mdx index 184829caa2..aada9ed7ba 100644 --- a/apps/docs/src/content/docs/en/pages/guides/getting-to-know-azion-console/getting-to-know-azion-console.mdx +++ b/apps/docs/src/content/docs/en/pages/guides/getting-to-know-azion-console/getting-to-know-azion-console.mdx @@ -1,11 +1,11 @@ --- title: About Azion Console description: >- - Find where Azion Console keeps each product, the Create modal, help, and the + Find where Azion Console keeps each product, Creation Center, help, and the account pages, from the homepage to the account menu. meta_tags: >- Azion, Azion Console, applications, journey, onboarding, build from scratch, - domain, traffic, Console menu, products menu, account menu + domain, traffic, Console menu, products menu, Creation Center, account menu namespace: documentation_getting_to_know_azion_console permalink: /documentation/guides/platform/account-and-billing/getting-to-know-azion-console/ --- @@ -15,7 +15,7 @@ import DocItem from '@aziontech/webkit/doc-item' Every product, resource, and account setting you use at Azion is configured from one web interface. Its header carries the menus and buttons that open each area, and its homepage carries shortcuts to the first tasks. That interface is [Azion Console](https://console.azion.com/). -In it, you set up your [Azion account](/en/documentation/fundamentals/creating-account/), [build and deploy applications](/en/documentation/platform/applications/), [manage the main settings of an application](/en/documentation/guides/application-development/getting-started/configure-main-settings/), and configure every Azion product. The [Guides](/en/documentation/guides/) cover the tasks of each one. The sections below cover the homepage, the Console menu, the Create modal, the help, feedback, and Copilot buttons, and the account menu, in that order. To sign up or sign in, refer to [Access Azion Console](/en/documentation/guides/platform/account-and-billing/how-to-access-azion-console/). +In it, you set up your [Azion account](/en/documentation/fundamentals/creating-account/), [build and deploy applications](/en/documentation/platform/applications/), [manage the main settings of an application](/en/documentation/guides/application-development/getting-started/configure-main-settings/), and configure every Azion product. The [Guides](/en/documentation/guides/) cover the tasks of each one. The sections below cover the homepage, the Console menu, Creation Center, the help, feedback, and Copilot buttons, and the account menu, in that order. To sign up or sign in, refer to [Access Azion Console](/en/documentation/guides/platform/account-and-billing/how-to-access-azion-console/). --- @@ -58,11 +58,14 @@ Selecting an entry opens that product with its settings. The sections can change --- -## Create modal +## Creation Center -The **+ Create** button sits in the Console header and in the **Get Started** block of the homepage. It opens a modal with four tabs: **Recommended**, **Templates**, **Resources**, and **Import from GitHub**. On some accounts, only the **Resources** tab shows. +The **+ Create** button sits in the Console header and in the **Get Started** block of the homepage. It opens **Creation Center**, a page with two sections: -The **Resources** tab creates one resource at a time, such as a workload, an application, a firewall, a function, or a digital certificate. The other tabs start a whole application from a template or from a GitHub repository. For what each tab offers, refer to [Use the + Create button](/en/documentation/guides/platform/account-and-billing/create-button/). +- **Import from GitHub** starts an application from a repository of a GitHub account you connect. +- **Start from Template** lists the **Recommended** templates and the **Azion Templates** available to your account, with a search and filters by technology and use case. + +For what each option offers, refer to [Use the + Create button](/en/documentation/guides/platform/account-and-billing/create-button/). --- diff --git a/apps/docs/src/content/docs/en/pages/guides/inference/route-model-calls-through-a-gateway-function.mdx b/apps/docs/src/content/docs/en/pages/guides/inference/route-model-calls-through-a-gateway-function.mdx index 9da8e475bd..a8925a6142 100644 --- a/apps/docs/src/content/docs/en/pages/guides/inference/route-model-calls-through-a-gateway-function.mdx +++ b/apps/docs/src/content/docs/en/pages/guides/inference/route-model-calls-through-a-gateway-function.mdx @@ -92,7 +92,7 @@ const ROUTES = { { kind: "provider" } ], "long-context": [ - { kind: "azion", model: "gpt-oss-20b" }, + { kind: "azion", model: "openai/gpt-oss-20b" }, { kind: "provider" } ], "fallback-test": [ diff --git a/apps/docs/src/content/docs/en/pages/guides/marketplace/templates/edge-ai-starter-kit.mdx b/apps/docs/src/content/docs/en/pages/guides/marketplace/templates/edge-ai-starter-kit.mdx index a7c4752f67..921bee48ff 100644 --- a/apps/docs/src/content/docs/en/pages/guides/marketplace/templates/edge-ai-starter-kit.mdx +++ b/apps/docs/src/content/docs/en/pages/guides/marketplace/templates/edge-ai-starter-kit.mdx @@ -13,7 +13,7 @@ import DocCard from '@aziontech/webkit/doc-card' import DocSteps from '@aziontech/webkit/doc-steps' import DocStep from '@aziontech/webkit/doc-step' -You can deploy the **AI Inference Starter Kit** template and manage what it creates from Azion Console. The template creates an application with a function and a domain, and the function serves an OpenAI-compatible endpoint. +You can deploy the **AI Inference Starter Kit** template and manage what it creates from Azion Console. The template creates a Workload with its deployment, an Application, and a Function with its Function Instance, and the Function serves an OpenAI-compatible endpoint on the workload domain of the Workload. The [AI Inference quickstart](/en/documentation/platform/ai-inference/quickstart/) covers the same deployment and adds a first request to the model. @@ -25,7 +25,7 @@ The template uses [Application Accelerator](/en/documentation/platform/applicati ## Deploy the template -To create the application, the function, and the domain from one template: +To create these entities from one template: @@ -35,12 +35,12 @@ To create the application, the function, and the domain from one template: - Select the **AI Inference Starter Kit** template. + Under **Start from Template**, select **AI Inference Starter Kit**. - Enter a name for the application. + In **Application Name**, enter a name made of letters, numbers, and underscores, such as the default `ai_inference_starter_kit`. A hyphen is refused with "The use of accents and/or special characters is not allowed." @@ -50,13 +50,13 @@ To create the application, the function, and the domain from one template: -A window shows the deployment logs while the deployment runs. When it finishes, the page shows information about the application and the options to continue. +A window shows the deployment logs while the deployment runs. When it finishes, the page shows the domain under **Visit site**, the **Add custom domain** option, the **Deployment logs**, and **Resources created**, which lists the Workload and the Application. :::note -The deployment page shows a link to the application. The application takes a few minutes to propagate to Azion's data centers, and the domain does not resolve until it does. Wait a few minutes, then select the link again. +The deployment takes several minutes to propagate to Azion's data centers. Until it propagates, the domain answers with Azion's placeholder `404`. Wait a few minutes, then select **Visit site** again. ::: -The application answers on the Workload Domain of the workload that serves it, in the form `xxxxxxxxxx.map.azionedge.net/`, and it serves an OpenAI-compatible endpoint on that domain. For the path a request takes from the domain to the model, refer to the architecture of [Add AI features to existing applications](/en/documentation/use-cases/build-and-run-ai-workloads/add-ai-features-to-existing-applications/). +The Application answers on the workload domain of the Workload, in the form `xxxxxxxxxx.map.azionedge.net`, and the Function serves an OpenAI-compatible endpoint on any path of that domain. For the path a request takes from the domain to the model, refer to the architecture of [Add AI features to existing applications](/en/documentation/use-cases/build-and-run-ai-workloads/add-ai-features-to-existing-applications/). --- @@ -78,7 +78,7 @@ To change the function: - Select the function that carries the same name as the application. The list is alphabetical, and the **search bar** filters it by **Function Name** only. + Select the Function that carries the name you entered during the deployment, followed by a "(Build at …)" suffix. The list is alphabetical, and the **search bar** filters it by **Function Name** only. @@ -95,60 +95,17 @@ To change the function: The function has the changes you saved. For every setting a function holds, refer to [Functions](/en/documentation/platform/functions/). -The **Code** tab opens on a function ready to run. It receives a POST request, calls the model, and returns the response. The call below sets `stream` to `false`, so the model returns the response whole: - -```ts -const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are a helpful assistant." - }, - { - "role": "user", - "content": "Name the European capitals." - } - ] -}) -return modelResponse -``` - -The model answers with one entry in `choices`, and the generated text sits at `choices[0].message.content`: - -```json -{ - "id": "chatcmpl-example", - "object": "chat.completion", - "created": 1767268800, - "model": "Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", - "choices": [ - { - "index": 0, - "message": { - "role": "assistant", - "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", - "tool_calls": [] - }, - "logprobs": null, - "finish_reason": "stop", - "stop_reason": null - } - ], - "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, - "prompt_tokens_details": null - }, - "prompt_logprobs": null -} -``` - -This example calls the [Qwen3 model](/en/documentation/platform/ai-inference/qwen3-30ba3b/). To call another model, change the first argument of `Azion.AI.run` to its id, listed in [AI models](/en/documentation/platform/ai-inference/models/). The body also accepts `stream`, which streams the response instead of returning it whole. For every field the body accepts, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). - -Before you change the call, read [AI Inference best practices](/en/documentation/platform/ai-inference/best-practices/) for the request patterns Azion recommends, and [AI Inference limits](/en/documentation/platform/ai-inference/limits/) for the conditions under which Azion terminates a model. +The **Code** tab holds the code the template installs. On each request, the Function: + +- Accepts only a `POST` request whose `Content-Type` header is exactly `application/json`. Any other request receives `400` with `{"error":"Request must be a POST request with JSON body"}`. +- Reads the model id from the `model` field of the request body. A body without it receives `400` with `{"error":"Missing 'model' field in request body"}`. +- Passes the whole body to `Azion.AI.run` and returns the model response. With `stream` set to `true`, it streams the response as server-sent events, one `data:` line per chunk, ending with `data: [DONE]`. + +The code holds no model id. To call another model, change the `model` field of the request to its id, listed in [AI models](/en/documentation/platform/ai-inference/models/). For every field the body accepts, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). + +The model response keeps the chat completion shape, and the generated text sits at `choices[0].message.content`. Its `model` field carries the account's internal id for the model, which can differ from the id the request sent: `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` returns `qwen-qwen3-30b-a3b-instruct-2507-fp8`. To send a first request and read a full response, refer to the [AI Inference quickstart](/en/documentation/platform/ai-inference/quickstart/). + +Before you change the code, read [AI Inference best practices](/en/documentation/platform/ai-inference/best-practices/) for the request patterns Azion recommends, and [AI Inference limits](/en/documentation/platform/ai-inference/limits/) for the conditions under which Azion terminates a model. --- @@ -177,5 +134,5 @@ The application page opens on the settings you can adjust. For what each setting - + diff --git a/apps/docs/src/content/docs/en/pages/hubs/guides/ai-inference.mdx b/apps/docs/src/content/docs/en/pages/hubs/guides/ai-inference.mdx index 0a8629c9dc..8cfc4f659f 100644 --- a/apps/docs/src/content/docs/en/pages/hubs/guides/ai-inference.mdx +++ b/apps/docs/src/content/docs/en/pages/hubs/guides/ai-inference.mdx @@ -7,4 +7,4 @@ permalink: /documentation/platform/ai-inference/guides/ guides_hub: ai-inference --- -Every guide and tutorial for AI Inference, each covering one task. Open one and it takes you to the Guides section, where every guide lives. +Each guide opens in the Guides section, where every guide lives. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/Qwen3-30b-a3b-Instruct-2507-fp8.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/Qwen3-30b-a3b-Instruct-2507-fp8.mdx index 21e81e9852..98043ea233 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/Qwen3-30b-a3b-Instruct-2507-fp8.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/Qwen3-30b-a3b-Instruct-2507-fp8.mdx @@ -1,7 +1,7 @@ --- title: Qwen3 30B A3B Instruct 2507 FP8 description: >- - Invoke Qwen3 30B A3B Instruct 2507 FP8, a 30B-parameter language model with a + Invoke Qwen3 30B A3B Instruct 2507 FP8, a 30.5B-parameter language model with a 64k-token context length, tool calling, and LoRA support. meta_tags: 'AI Inference, AI models, Qwen3 30B A3B Instruct 2507 FP8, large language model, tool calling, LoRA, Azion.AI.run' namespace: docs_edge_ai_models_qwen_3_30ba3b @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Qwen3 30B A3B Instruct 2507 FP8** is an instruction-tuned large language model with 30 billion parameters, in FP8 precision. It reads text and returns text, for chat and question answering, summarization, multilingual tasks, mathematics and science problems, coding, and workflows that call tools. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`. +**Qwen3 30B A3B Instruct 2507 FP8** is an instruction-tuned large language model with 30.5 billion parameters, in FP8 precision. It reads text and returns text, for tasks that need instruction following, logical reasoning, text comprehension, mathematics, science, coding, or tool use. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`. ## Model details @@ -24,7 +24,7 @@ The id is the string a request passes to select this model, and `Azion.AI.run` t | Version | 30B - FP8 | | Model category | Large Language Model (LLM) | | Model id | `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` | -| Size | 30B parameters | +| Size | 30.5B parameters | | HuggingFace model | [Qwen/Qwen3-30B-A3B-Instruct-2507-FP8](https://huggingface.co/Qwen/Qwen3-30B-A3B-Instruct-2507-FP8) | | OpenAI-compatible endpoint | [OpenAI Chat API](https://developers.openai.com/api/reference/overview) | | License | [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) | @@ -46,7 +46,7 @@ The model's native context window upstream is larger, and 64k tokens is the cont ## Usage -The examples below call the model from a [function](/en/documentation/platform/functions/) with `Azion.AI.run`. The binding takes the model id as its first argument and the request body as its second, so the body never repeats the id. To send the same body to the OpenAI-compatible HTTP endpoint instead, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +The examples below call the model from a [Function](/en/documentation/platform/functions/) with `Azion.AI.run`. The binding takes the model id as its first argument and the request body as its second, so the body does not need the id: the first argument decides the model, and a `model` field in the body is ignored. Over HTTP, an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves an endpoint that takes the same body, with the id in its `model` field. For that endpoint, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). ### Chat completion @@ -97,7 +97,57 @@ const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", }) ``` -When the model selects a tool, the assistant message carries a `tool_calls` array instead of text, and each entry names the function and the arguments the model generated for it. +When the model selects a tool, the assistant message carries `content` as `null` and a `tool_calls` array, and `finish_reason` is `tool_calls`. Each entry of `tool_calls` names the function, the arguments the model generated for it, and an `id`. + +To return the result of the call, send the conversation back with two more messages: the assistant message as the model returned it, and a `tool` message that carries the `id` of the call in `tool_call_id` and the result in `content`: + +```ts +const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { + "stream": false, + "max_tokens": 64, + "messages": [ + { "role": "system", "content": "You are a helpful assistant with access to tools." }, + { "role": "user", "content": "What is the weather in London?" }, + { + "role": "assistant", + "content": null, + "tool_calls": [ + { + "id": "chatcmpl-tool-789b0d0737f84d09b61eee169a3bea75", + "type": "function", + "function": { "name": "get_weather", "arguments": "{\"location\": \"London\"}" } + } + ] + }, + { + "role": "tool", + "tool_call_id": "chatcmpl-tool-789b0d0737f84d09b61eee169a3bea75", + "content": "{\"temperature_c\": 14, \"condition\": \"light rain\"}" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state" + } + }, + "required": ["location"] + } + } + } + ] +}) +``` + +The model answers in text, with `finish_reason` set to `stop`: `The current weather in London is 14°C with light rain.` --- @@ -107,9 +157,7 @@ When the model selects a tool, the assistant message carries a `tool_calls` arra The fields a request body carries, and the HTTP form of the same call. The rest of the catalog, with the id and the capabilities each model states. - The product this model runs on. - The runtime that holds the binding the examples on this page call. The extension of AI Inference that adapts a model with LoRA, and the models that accept it. - Definitions for model id, context length, and the other terms this page uses. + Definitions for model id, `Azion.AI.run`, and the other terms this page uses. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/baai-bge-reranker-v2-m3.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/baai-bge-reranker-v2-m3.mdx index e5143058d4..86f8408631 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/baai-bge-reranker-v2-m3.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/baai-bge-reranker-v2-m3.mdx @@ -42,7 +42,7 @@ These values describe the model itself and are not fields of the request body. F ## Usage -A [function](/en/documentation/platform/functions/) calls the model with `Azion.AI.run`, passing the id as the first argument and the request body as the second. This model takes no `messages` array: each of the two operations below has its own body. To send the same body over HTTP instead, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +A [Function](/en/documentation/platform/functions/) calls the model with `Azion.AI.run`, passing the id as the first argument and the request body as the second. This model takes no `messages` array. A body without `query` and `documents`, such as one that carries `text_1` and `text_2`, is refused with `AIError: validation error: Required` on `/query` and `/documents`. Over HTTP, an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves an endpoint that takes the same body, with the id in its `model` field. For that endpoint, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). ### Reranking @@ -73,28 +73,32 @@ The model returns a `results` array ordered from the highest `relevance_score` t { "index": 0, "document": { - "text": "Deep learning is a subset of machine learning that uses neural networks with many layers" + "text": "Deep learning is a subset of machine learning that uses neural networks with many layers", + "multi_modal": null }, "relevance_score": 0.99951171875 }, { "index": 2, "document": { - "text": "Deep learning enables computers to learn from large amounts of data" + "text": "Deep learning enables computers to learn from large amounts of data", + "multi_modal": null }, "relevance_score": 0.98291015625 }, { "index": 3, "document": { - "text": "I like pizza" + "text": "I like pizza", + "multi_modal": null }, "relevance_score": 0.00001621246337890625 }, { "index": 1, "document": { - "text": "The weather is nice today" + "text": "The weather is nice today", + "multi_modal": null }, "relevance_score": 0.000016033649444580078 } @@ -102,24 +106,6 @@ The model returns a `results` array ordered from the highest `relevance_score` t } ``` -### Scoring - -A scoring request carries `text_1` and the `text_2` array the model scores against it: - -```ts -const modelResponse = await Azion.AI.run("baai-bge-reranker-v2-m3", { - "text_1": "What is deep learning?", - "text_2": [ - "Deep learning is a subset of machine learning that uses neural networks with many layers", - "The weather is nice today", - "Deep learning enables computers to learn from large amounts of data", - "I like pizza" - ] -}) -``` - -The response carries the same `results` array, with one entry and one `relevance_score` for every text in `text_2`. - --- ## Related resources @@ -128,9 +114,7 @@ The response carries the same `results` array, with one entry and one `relevance Every field a reranking request accepts, and the HTTP endpoint that takes the same body. The other models AI Inference runs, and the id each one answers to. - The product that runs this model. - The product whose runtime holds the binding the examples on this page call. The conditions under which Azion terminates or deprovisions a model. - Where model id, context length, and the rest of the AI Inference vocabulary are defined. + Where model id, `Azion.AI.run`, and the rest of the AI Inference vocabulary are defined. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/gpt-oss-20b.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/gpt-oss-20b.mdx index f0da15abf3..ef3f1b2a88 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/gpt-oss-20b.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/gpt-oss-20b.mdx @@ -1,7 +1,7 @@ --- title: GPT-OSS 20B description: >- - Invoke GPT-OSS 20B, a 20B-parameter large language model with a 131k-token + Invoke GPT-OSS 20B, an open-weight large language model with a 131k-token context length, and send it a tool-calling request. meta_tags: 'AI Inference, AI models, GPT-OSS 20B, large language model, tool calling, context length, Azion.AI.run' namespace: docs_edge_ai_models_gpt_oss_20b @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**GPT-OSS 20B** is an open-source large language model with 20 billion parameters, built for text generation, conversation, and other natural language processing tasks. It reads text, returns text, and accepts tool definitions in the request. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `gpt-oss-20b`. +**GPT-OSS 20B** is an open-weight large language model with 21 billion parameters, designed for reasoning and agentic tasks. It reasons before it answers, reads text, returns text, and accepts tool definitions in the request. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `openai/gpt-oss-20b`. ## Model details @@ -23,8 +23,8 @@ The model id is the string that selects this model, and it is the first argument | Model name | GPT-OSS 20B | | Version | 20B | | Model category | Large Language Model (LLM) | -| Model id | `gpt-oss-20b` | -| Size | 20B parameters | +| Model id | `openai/gpt-oss-20b` | +| Size | 21B parameters | | HuggingFace model | [openai/gpt-oss-20b](https://huggingface.co/openai/gpt-oss-20b) | | OpenAI-compatible endpoint | [OpenAI Chat API](https://developers.openai.com/api/reference/overview) | | License | [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) | @@ -44,26 +44,22 @@ These values belong to the model and are not part of the request body. For the f ## Usage -A [function](/en/documentation/platform/functions/) invokes the model with `Azion.AI.run`, passing the id as the first argument and an OpenAI-compatible request body as the second. The examples below use that binding. To send the same body to the OpenAI-compatible HTTP endpoint instead, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +A [Function](/en/documentation/platform/functions/) invokes the model with `Azion.AI.run`, passing the id as the first argument and an OpenAI-compatible request body as the second. The examples below use that binding. Over HTTP, an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves an endpoint that takes the same body, with the id in its `model` field. For that endpoint, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). ### Chat completion -This request carries a system message, a user message, and the sampling fields that shape the output: +This request carries one user message and caps the output with `max_tokens`: ```ts -const modelResponse = await Azion.AI.run("gpt-oss-20b", { - "stream": false, - "max_tokens": 1024, - "temperature": 0.7, - "top_p": 0.9, +const modelResponse = await Azion.AI.run("openai/gpt-oss-20b", { + "max_tokens": 64, "messages": [ - { "role": "system", "content": "You are a helpful assistant." }, - { "role": "user", "content": "Name the European capitals." } + { "role": "user", "content": "Reply with the word: ready" } ] }) ``` -The model answers with one entry in `choices`, and the generated text sits at `choices[0].message.content`: +The model answers with one entry in `choices`. The generated text sits at `choices[0].message.content`, and the reasoning that preceded it sits at `reasoning_content`, which the message also carries as `reasoning`: ```json { @@ -76,8 +72,9 @@ The model answers with one entry in `choices`, and the generated text sits at `c "index": 0, "message": { "role": "assistant", - "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", + "reasoning": "User: \"Reply with the word: ready\". They want the reply the word \"ready\". Probably just \"ready\".", + "reasoning_content": "User: \"Reply with the word: ready\". They want the reply the word \"ready\". Probably just \"ready\".", + "content": "ready", "tool_calls": [] }, "logprobs": null, @@ -86,21 +83,25 @@ The model answers with one entry in `choices`, and the generated text sits at `c } ], "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 75, + "total_tokens": 110, + "completion_tokens": 35, "prompt_tokens_details": null }, "prompt_logprobs": null } ``` +The reasoning comes out of the `max_tokens` budget. With a small budget, the reasoning can use all of it, and the response then carries `content` as `null` and `finish_reason` as `length`. + +The `model` field of the response reads `gpt-oss-20b`, an id that `Azion.AI.run` refuses as input. To call the model again, pass `openai/gpt-oss-20b`, not the value of that field. + ### Tool calling A tool-calling request adds a `tools` array to the body. Each entry sets `type` to `function` and carries a `function` object holding the name the model calls, a description of what it does, and its `parameters` in JSON Schema form: ```ts -const modelResponse = await Azion.AI.run("gpt-oss-20b", { +const modelResponse = await Azion.AI.run("openai/gpt-oss-20b", { "stream": false, "max_tokens": 1024, "messages": [ @@ -142,7 +143,8 @@ When the model selects a tool, it returns `content` as `null`, names the call in "index": 0, "message": { "role": "assistant", - "reasoning_content": null, + "reasoning": "We should call get_weather function.", + "reasoning_content": "We should call get_weather function.", "content": null, "tool_calls": [ { @@ -157,13 +159,13 @@ When the model selects a tool, it returns `content` as `null`, names the call in }, "logprobs": null, "finish_reason": "tool_calls", - "stop_reason": null + "stop_reason": 200012 } ], "usage": { - "prompt_tokens": 293, - "total_tokens": 313, - "completion_tokens": 20, + "prompt_tokens": 147, + "total_tokens": 178, + "completion_tokens": 31, "prompt_tokens_details": null }, "prompt_logprobs": null @@ -178,9 +180,7 @@ When the model selects a tool, it returns `content` as `null`, names the call in Every field a request body accepts, and the HTTP endpoint that takes the same body. The other models AI Inference runs, and the id each one answers to. - The product that runs this model. - The product whose runtime holds the binding the examples on this page call. The conditions under which Azion terminates or deprovisions a model. - Where model id, context length, and the rest of the AI Inference vocabulary are defined. + Where model id, `Azion.AI.run`, and the rest of the AI Inference vocabulary are defined. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/mistral-3-small.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/mistral-3-small.mdx index 857987b11b..3435e89705 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/mistral-3-small.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/mistral-3-small.mdx @@ -12,11 +12,11 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Mistral 3 Small** is a large language model with 24 billion parameters, built for conversational agents, text generation, and tool calling. It reads text, returns text, and accepts tool definitions in the request. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `casperhansen-mistral-small-24b-instruct-2501-awq`. +**Mistral 3 Small** is a large language model with 24 billion parameters, built for conversational agents and tool calling. It reads text, returns text, and accepts tool definitions in the request. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `casperhansen-mistral-small-24b-instruct-2501-awq`. ## Model details -The model id is the string that selects this model, and it is the first argument `Azion.AI.run` takes. The HuggingFace repository holds the model card. +The model id is the string that selects this model, and it is the first argument `Azion.AI.run` takes. The HuggingFace repository below holds the weights quantized with AWQ (Activation-aware Weight Quantization) and carries no model card. The description and the license on this page follow the card of [Mistral Small 24B Instruct 2501](https://huggingface.co/mistralai/Mistral-Small-24B-Instruct-2501), the model those weights quantize. | Detail | Value | | --- | --- | @@ -44,7 +44,7 @@ These values belong to the model and are not part of the request body. For the f ## Usage -A [function](/en/documentation/platform/functions/) invokes the model with `Azion.AI.run`, passing the id as the first argument and an OpenAI-compatible request body as the second. The examples below use that binding. To send the same body to the OpenAI-compatible HTTP endpoint instead, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +A [Function](/en/documentation/platform/functions/) invokes the model with `Azion.AI.run`, passing the id as the first argument and an OpenAI-compatible request body as the second. The examples below use that binding. Over HTTP, an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves an endpoint that takes the same body, with the id in its `model` field. For that endpoint, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). ### Chat completion @@ -53,7 +53,7 @@ This request carries a system message and a user message, and caps the length of ```ts const modelResponse = await Azion.AI.run("casperhansen-mistral-small-24b-instruct-2501-awq", { "stream": false, - "max_tokens": 1024, + "max_tokens": 64, "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Name the European capitals." } @@ -75,24 +75,26 @@ The model answers with one entry in `choices`, and the generated text sits at `c "message": { "role": "assistant", "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", + "content": "Sure, here are the capitals of the European countries:\n\n1. **Albania** - Tirana\n2. **Andorra** - Andorra la Vella\n3. **Armenia** - Yerevan (located in the Caucasus region, which is also geopolitically considered part of", "tool_calls": [] }, "logprobs": null, - "finish_reason": "stop", + "finish_reason": "length", "stop_reason": null } ], "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 17, + "total_tokens": 81, + "completion_tokens": 64, "prompt_tokens_details": null }, "prompt_logprobs": null } ``` +The answer stops at the 64 tokens that `max_tokens` allows, so `finish_reason` reads `length`. + ### Tool calling A tool-calling request adds a `tools` array to the body. Each entry sets `type` to `function` and carries a `function` object holding the name the model calls, a description of what it does, and its `parameters` in JSON Schema form: @@ -144,11 +146,11 @@ When the model selects a tool, it returns `content` as `null`, names the call in "content": null, "tool_calls": [ { - "id": "chatcmpl-tool-0123456789abcdef0123456789abcdef", + "id": "kpkde3q4d", "type": "function", "function": { "name": "get_weather", - "arguments": "{\"location\": \"London\"}" + "arguments": "{\"location\": \"london\"}" } } ] @@ -159,9 +161,9 @@ When the model selects a tool, it returns `content` as `null`, names the call in } ], "usage": { - "prompt_tokens": 293, - "total_tokens": 313, - "completion_tokens": 20, + "prompt_tokens": 93, + "total_tokens": 115, + "completion_tokens": 22, "prompt_tokens_details": null }, "prompt_logprobs": null @@ -176,9 +178,7 @@ When the model selects a tool, it returns `content` as `null`, names the call in Every field a request body accepts, and the HTTP endpoint that takes the same body. The other models AI Inference runs, and the id each one answers to. - The product that runs this model. - The product whose runtime holds the binding the examples on this page call. The conditions under which Azion terminates or deprovisions a model. - Where model id, context length, and the rest of the AI Inference vocabulary are defined. + Where model id, `Azion.AI.run`, and the rest of the AI Inference vocabulary are defined. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/nanonets-ocr-r.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/nanonets-ocr-r.mdx index 672ca3bcfe..28446d3fe8 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/nanonets-ocr-r.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/nanonets-ocr-r.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Nanonets-OCR-s** is an optical character recognition (OCR) model that converts a document image into structured Markdown. The output keeps the layout of the source, including headings, lists, tables, and basic tags, so another model can parse it. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `nanonets/Nanonets-OCR-s`. +**Nanonets-OCR-s** is an optical character recognition (OCR) model that converts a document image into structured Markdown. The output keeps tables, writes equations in LaTeX, and wraps image descriptions, signatures, and watermarks in tags, so another model can process it. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `nanonets/Nanonets-OCR-s`. ## Model details @@ -31,12 +31,13 @@ The values here describe the model itself, and none of them is a field in the re | --- | --- | | Input data | Text and image | | Context length | 32k tokens | +| Tool calling | No | --- ## Usage -`Azion.AI.run` runs the model from inside a [function](/en/documentation/platform/functions/): the id goes in the first argument, and an OpenAI-compatible request body goes in the second. The example on this page calls it that way. To send the same body over HTTP instead, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +`Azion.AI.run` runs the model from inside a [Function](/en/documentation/platform/functions/): the id goes in the first argument, and an OpenAI-compatible request body goes in the second. The example on this page calls it that way. Over HTTP, an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves an endpoint that takes the same body, with the id in its `model` field. For that endpoint, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). ### OCR @@ -53,7 +54,7 @@ const modelResponse = await Azion.AI.run("nanonets/Nanonets-OCR-s", { { "type": "image_url", "image_url": { - "url": "data:image/png;base64,{img_base64}" + "url": "data:image/png;base64," } }, { @@ -66,21 +67,23 @@ const modelResponse = await Azion.AI.run("nanonets/Nanonets-OCR-s", { }) ``` -The model returns one entry in `choices`, and the transcribed text sits at `choices[0].message.content`: +Replace `` with the PNG file encoded in base64. The `image_url.url` field also takes an `https` URL that serves an image. When the URL serves no image, `Azion.AI.run` throws `Error: Request failed with status 500`. + +The model returns one entry in `choices`, and the transcribed text sits at `choices[0].message.content`. For a PNG that shows the word AZION, the response is: ```json { "id": "chatcmpl-0123456789abcdef0123456789abcdef", "object": "chat.completion", "created": 1767268800, - "model": "nanonets/Nanonets-OCR-s", + "model": "nanonets-nanonets-ocr-s", "choices": [ { "index": 0, "message": { "role": "assistant", "reasoning_content": null, - "content": "E = mc^2", + "content": "AZION", "tool_calls": [] }, "logprobs": null, @@ -89,9 +92,9 @@ The model returns one entry in `choices`, and the transcribed text sits at `choi } ], "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 182, + "total_tokens": 185, + "completion_tokens": 3, "prompt_tokens_details": null }, "prompt_logprobs": null @@ -106,9 +109,7 @@ The model returns one entry in `choices`, and the transcribed text sits at `choi Every field a request body accepts, and the HTTP endpoint that takes the same body. The other models AI Inference runs, and the id each one answers to. - The product that runs this model. - The product whose runtime holds the binding the example on this page calls. The conditions under which Azion terminates or deprovisions a model. - Where model id, context length, and the rest of the AI Inference vocabulary are defined. + Where model id, `Azion.AI.run`, and the rest of the AI Inference vocabulary are defined. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen-2-5-vl-3b.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen-2-5-vl-3b.mdx index af61b5b3ad..88aad0d2c0 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen-2-5-vl-3b.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen-2-5-vl-3b.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Qwen2.5 VL AWQ 3B** is a vision-language model with 3 billion parameters. It reads text and images, returns text, and handles visual analysis, agentic reasoning, long video comprehension, visual localization, and structured output generation. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `qwen-qwen25-vl-3b-instruct-awq`. +**Qwen2.5 VL AWQ 3B** is a vision-language model with 3 billion parameters. It reads text and images, returns text, and handles visual analysis, agentic reasoning, visual localization, and structured output generation. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `qwen-qwen25-vl-3b-instruct-awq`. ## Model details @@ -27,7 +27,7 @@ The id is what a request sends to reach this model, and `Azion.AI.run` takes it | Size | 3B parameters | | HuggingFace model | [Qwen/Qwen2.5-VL-3B-Instruct-AWQ](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct-AWQ) | | OpenAI-compatible endpoint | [OpenAI Chat API](https://developers.openai.com/api/reference/overview) | -| License | [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) | +| License | [Qwen Research License](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct-AWQ/blob/main/LICENSE) | ## Capabilities @@ -37,22 +37,23 @@ These capabilities are properties of the model, and a request body does not set | --- | --- | | Input data | Text and image | | Context length | 32k tokens | -| Tool calling | Yes | +| Tool calling | Named tool only | | Supports LoRA | Yes | --- ## Usage -You call this model from a [function](/en/documentation/platform/functions/), through the `Azion.AI.run` binding. The first argument is the model id, and the second is an OpenAI-compatible request body. Each example on this page uses that binding. For the HTTP form of the same request, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +You call this model from a [Function](/en/documentation/platform/functions/), through the `Azion.AI.run` binding. The first argument is the model id, and the second is an OpenAI-compatible request body. Each example on this page uses that binding. Over HTTP, an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves an endpoint that takes the same body, with the id in its `model` field. For that endpoint, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). ### Chat completion -This request carries a system message that sets the behavior of the model and a user message that holds the prompt: +This request carries a system message that sets the behavior of the model and a user message that holds the prompt, and caps the answer with `max_tokens`: ```ts const modelResponse = await Azion.AI.run("qwen-qwen25-vl-3b-instruct-awq", { "stream": false, + "max_tokens": 64, "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Name the European capitals." } @@ -74,31 +75,36 @@ One entry arrives in `choices`, and the text the model generated sits at `choice "message": { "role": "assistant", "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", + "content": "Here are some of the European capitals:\n\n1. Berlin, Germany\n2. Paris, France\n3. Madrid, Spain\n4. Rome, Italy\n5. Vienna, Austria\n6. Stockholm, Sweden\n7. Copenhagen, Denmark\n8. Helsinki, Finland\n9. Oslo, Norway\n10", "tool_calls": [] }, "logprobs": null, - "finish_reason": "stop", + "finish_reason": "length", "stop_reason": null } ], "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 24, + "total_tokens": 88, + "completion_tokens": 64, "prompt_tokens_details": null }, "prompt_logprobs": null } ``` +The answer stops at the 64 tokens that `max_tokens` allows, so `finish_reason` reads `length`. + ### Tool calling -A `tools` array declares the functions the model may call. Every entry sets `type` to `function` and carries a `function` object. That object has three fields: the `name` the model returns, a `description` of what the function does, and the `parameters` it accepts, written as a JSON Schema object: +A `tools` array declares the functions the model may call. Every entry sets `type` to `function` and carries a `function` object. That object has three fields: the `name` the model returns, a `description` of what the function does, and the `parameters` it accepts, written as a JSON Schema object. + +This model returns `tool_calls` when the request names the tool in `tool_choice`. A request that carries `tools` and leaves the choice to the model fails, and `Azion.AI.run` throws `Error: Request failed with status 400`. This request names `get_weather`: ```ts const modelResponse = await Azion.AI.run("qwen-qwen25-vl-3b-instruct-awq", { "stream": false, + "max_tokens": 64, "messages": [ { "role": "system", "content": "You are a helpful assistant with access to tools." }, { "role": "user", "content": "What is the weather in London?" } @@ -121,11 +127,12 @@ const modelResponse = await Azion.AI.run("qwen-qwen25-vl-3b-instruct-awq", { } } } - ] + ], + "tool_choice": { "type": "function", "function": { "name": "get_weather" } } }) ``` -A response that selects a tool carries `null` in `content`, one entry in `tool_calls` holding the function name and the arguments the model chose, and `tool_calls` in `finish_reason`: +The response carries one entry in `tool_calls` holding the function name and the arguments the model chose. `content` is an empty string, and `finish_reason` is `stop`, not `tool_calls`: ```json { @@ -139,10 +146,10 @@ A response that selects a tool carries `null` in `content`, one entry in `tool_c "message": { "role": "assistant", "reasoning_content": null, - "content": null, + "content": "", "tool_calls": [ { - "id": "chatcmpl-tool-0123456789abcdef0123456789abcdef", + "id": "chatcmpl-tool-213ac5dfd9d1487b8456755f291e95a4", "type": "function", "function": { "name": "get_weather", @@ -152,14 +159,14 @@ A response that selects a tool carries `null` in `content`, one entry in `tool_c ] }, "logprobs": null, - "finish_reason": "tool_calls", + "finish_reason": "stop", "stop_reason": null } ], "usage": { - "prompt_tokens": 293, - "total_tokens": 313, - "completion_tokens": 20, + "prompt_tokens": 30, + "total_tokens": 37, + "completion_tokens": 7, "prompt_tokens_details": null }, "prompt_logprobs": null @@ -181,13 +188,15 @@ const modelResponse = await Azion.AI.run("qwen-qwen25-vl-3b-instruct-awq", { "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, - { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } + { "type": "image_url", "image_url": { "url": "" } } ] } ] }) ``` +Replace `` with an `https` URL that serves an image, or with a `data:` URL that carries the image in base64. When the URL serves no image, `Azion.AI.run` throws `Error: Request failed with status 500`. + The model returns the same response object as a chat completion, and what it read in the image sits at `choices[0].message.content`. --- @@ -198,9 +207,7 @@ The model returns the same response object as a chat completion, and what it rea The request fields, the message objects, and the HTTP endpoint that takes the same body. The catalog of models AI Inference runs, with the id and the capabilities of each one. - The product that loads and runs this model. - The product whose runtime carries the binding these examples call. The extension of AI Inference that adapts a model with LoRA, and the models that accept it. - Where model id, context length, and the rest of the AI Inference vocabulary are defined. + Where model id, `Azion.AI.run`, and the rest of the AI Inference vocabulary are defined. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen-2-5-vl-7b.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen-2-5-vl-7b.mdx index 8d7b05b856..aa7c43717b 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen-2-5-vl-7b.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen-2-5-vl-7b.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Qwen2.5 VL AWQ 7B** is a vision-language model with 7 billion parameters, built for visual analysis, agentic reasoning, long video comprehension, visual localization, and structured output generation. The model accepts text and images in the same request, returns text, and takes tool definitions. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `qwen-qwen25-vl-7b-instruct-awq`. +**Qwen2.5 VL AWQ 7B** is a vision-language model with 7 billion parameters, built for visual analysis, agentic reasoning, visual localization, and structured output generation. The model accepts text and images in the same request, returns text, and calls a tool that the request names. [AI Inference](/en/documentation/platform/ai-inference/) runs it under the id `qwen-qwen25-vl-7b-instruct-awq`. ## Model details @@ -31,20 +31,20 @@ These values identify the model. A request names the model id to reach it, and t ## Capabilities -Qwen2.5 VL AWQ 7B states these capabilities for itself, and none of them is a request field. To read the fields a chat request carries, with their types, defaults, and bounds, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +These values are properties of the model, and a request body does not set them. To read the fields a chat request carries, with their types, defaults, and bounds, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). | Capability | Value | | --- | --- | | Input data | Text and image | | Context length | 32k tokens | -| Tool calling | Yes | +| Tool calling | Named tool only | | Supports LoRA | Yes | --- ## Usage -Every example on this page calls `Azion.AI.run` from inside a [function](/en/documentation/platform/functions/). The binding takes the model id as its first argument and an OpenAI-compatible request body as its second, so the body never repeats the id. To send the same body to the OpenAI-compatible HTTP endpoint, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +Every example on this page calls `Azion.AI.run` from inside a [Function](/en/documentation/platform/functions/). The binding takes the model id as its first argument and an OpenAI-compatible request body as its second, so the body does not need the id: the first argument decides the model, and a `model` field in the body is ignored. Over HTTP, an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves an endpoint that takes the same body, with the id in its `model` field. For that endpoint, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). ### Chat completion @@ -64,13 +64,14 @@ With `stream` set to `false`, the call resolves to one complete response, and `m ### Tool calling -A tool-calling request keeps the same messages and adds a `tools` array. Every entry declares `type` as `function`, then names the function, describes what it does, and states its `parameters` as a JSON Schema object: +A tool-calling request adds a `tools` array to the messages. Every entry declares `type` as `function`, then names the function, describes what it does, and states its `parameters` as a JSON Schema object. + +This model returns `tool_calls` when the request names the tool in `tool_choice`. A request that carries `tools` and leaves the choice to the model fails, and `Azion.AI.run` throws `Error: Request failed with status 400`. This request names `get_weather`: ```ts const modelResponse = await Azion.AI.run("qwen-qwen25-vl-7b-instruct-awq", { - "stream": false, + "max_tokens": 48, "messages": [ - { "role": "system", "content": "You are a helpful assistant with access to tools." }, { "role": "user", "content": "What is the weather in London?" } ], "tools": [ @@ -82,20 +83,18 @@ const modelResponse = await Azion.AI.run("qwen-qwen25-vl-7b-instruct-awq", { "parameters": { "type": "object", "properties": { - "location": { - "type": "string", - "description": "The city and state" - } + "location": { "type": "string" } }, "required": ["location"] } } } - ] + ], + "tool_choice": { "type": "function", "function": { "name": "get_weather" } } }) ``` -A function reads the model's answer from the first entry in `choices` and acts on it, which for this request means calling `get_weather`. +The response carries one entry in `tool_calls` that names `get_weather` with the arguments the model chose. `content` is an empty string, and `finish_reason` is `stop`, not `tool_calls`. ### Multimodal input @@ -110,13 +109,15 @@ const modelResponse = await Azion.AI.run("qwen-qwen25-vl-7b-instruct-awq", { "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, - { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } + { "type": "image_url", "image_url": { "url": "" } } ] } ] }) ``` +Replace `` with an `https` URL that serves an image, or with a `data:` URL that carries the image in base64. When the URL serves no image, `Azion.AI.run` throws `Error: Request failed with status 500`. + The model reads the image from the URL the request gives it, and answers in text at `modelResponse?.choices?.[0]?.message?.content`. --- @@ -127,9 +128,7 @@ The model reads the image from the URL the request gives it, and answers in text How a request reaches a model, through the binding or over HTTP, and what its body carries. The rest of the catalog, with the capabilities each model states for itself. - What AI Inference is, and what it does with a model request. - Where the code on this page runs, and how you deploy it. The extension of AI Inference that adapts a model with LoRA, and the models that accept it. - The AI Inference terms this page uses, defined in one place. + Where model id, `Azion.AI.run`, and the rest of the AI Inference vocabulary are defined. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen3-embedding-4b.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen3-embedding-4b.mdx index d597d3e364..9c73af955b 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen3-embedding-4b.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/ai-models/qwen3-embedding-4b.mdx @@ -31,19 +31,19 @@ The model id is the string that selects this model, and it is the first argument ## Capabilities -The model's native vector width is 2560, and the `dimensions` request field selects one of the widths listed below. For `dimensions`, `encoding_format`, and the rest of the request body, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +Without `dimensions`, the model returns a vector 2560 wide, its native width. The `dimensions` request field selects one of the smaller widths listed below. One value outside the list is accepted: 4096, which still returns a vector 2560 wide. Any other value, 2560 included, rejects with `AIError: validation error: Enum`. For `dimensions`, `encoding_format`, and the rest of the request body, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). | Capability | Value | | --- | --- | | Input data | Text | | Context length | 32k tokens | -| Output dimensions | 256, 512, 1024, 2048, 4096 | +| Output dimensions | 256, 512, 1024, 2048; 2560 without `dimensions` | --- ## Usage -A [function](/en/documentation/platform/functions/) invokes the model with `Azion.AI.run`, passing the id as the first argument and an OpenAI-compatible request body as the second. The examples below use that binding. To send the same body to the OpenAI-compatible HTTP endpoint instead, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +A [Function](/en/documentation/platform/functions/) invokes the model with `Azion.AI.run`, passing the id as the first argument and an OpenAI-compatible request body as the second. The examples below use that binding. Over HTTP, an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves an endpoint that takes the same body, with the id in its `model` field. For that endpoint, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). ### Embedding @@ -64,17 +64,17 @@ The model answers with one entry in `data`, and the vector sits at `data[0].embe "id": "embd-0123456789abcdef0123456789abcdef", "object": "list", "created": 1746821207, - "model": "Qwen/Qwen3-Embedding-4B", + "model": "qwen-qwen3-embedding-4b", "data": [ { "index": 0, "object": "embedding", - "embedding": [0.01, ..., 0.005] + "embedding": [-0.0009033476817421615, 0.020453155040740967, ..., -0.0008010818855836987] } ], "usage": { - "prompt_tokens": 11, - "total_tokens": 11, + "prompt_tokens": 9, + "total_tokens": 9, "completion_tokens": 0, "prompt_tokens_details": null } @@ -89,9 +89,7 @@ The model answers with one entry in `data`, and the vector sits at `data[0].embe Every field a request body accepts, and the HTTP endpoint that takes the same body. Where the vectors this model returns are stored and queried. - The product that runs this model. - The product whose runtime holds the binding the examples on this page call. The conditions under which Azion terminates or deprovisions a model. - Where model id, context length, and the rest of the AI Inference vocabulary are defined. + Where model id, `Azion.AI.run`, and the rest of the AI Inference vocabulary are defined. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/best-practices.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/best-practices.mdx index 53481ab9ca..a0af7d252d 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/best-practices.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/best-practices.mdx @@ -1,8 +1,8 @@ --- -title: Best practices +title: Best practices for AI Inference description: >- - Secure the endpoint that serves a model, copy the id each model states, and - decide what reaches the model before the call is made. + Gate the endpoint that serves a model, choose the models it can reach, copy + each id, and read the response and the errors a call returns. meta_tags: 'AI Inference, best practices, model id, authentication, Workload Domain, context length, optional chaining, Compute Time' namespace: docs_edge_ai_best_practices permalink: /documentation/platform/ai-inference/best-practices/ @@ -11,61 +11,155 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -A model call is code you own invoking a model you do not operate. Your code chooses which model answers, what reaches it, and what the caller finally receives. The model reads the request exactly as it arrives, so the decisions that shape an answer are taken before the call. +Code that calls a model decides who can make the call, which model answers, what the model reads, and what the caller gets back. Each of those decisions is made in your code, before or after the call. Left to their defaults, an endpoint answers anyone, a mistyped field changes nothing without an error, and a response read too directly breaks on the first model that answers differently. -In [AI Inference](/en/documentation/platform/ai-inference/), the code that makes the call is a [function](/en/documentation/platform/functions/), and the call is `Azion.AI.run`. Each practice below is one of the decisions that call leaves to you. The values themselves belong elsewhere. The request fields are on [Model invocation](/en/documentation/platform/ai-inference/model-invocation/), and the conditions Azion applies to a model are on [AI Inference limits](/en/documentation/platform/ai-inference/limits/). The path a request crosses is on [How AI Inference works](/en/documentation/platform/ai-inference/how-it-works/). +In [AI Inference](/en/documentation/platform/ai-inference/), that code is a [Function](/en/documentation/platform/functions/), and it calls a model with `Azion.AI.run`. The request fields are on [Model invocation](/en/documentation/platform/ai-inference/model-invocation/), the conditions Azion applies to a model are on [AI Inference limits](/en/documentation/platform/ai-inference/limits/), and the path of a request is on [How AI Inference works](/en/documentation/platform/ai-inference/how-it-works/). -The sections follow the order in which the decisions arise: the authentication the endpoint does not carry, the model id, and the capabilities a model states. The last two cover the input the function sends and the response it reads. +In order, the practices cover the check on each request, the models a request can reach, the model id, the capabilities of each model, the spelling of each field, the size of the input and the output, the read of the response, and the errors. The specimens are JavaScript for a Function, and request bodies in JSON. --- -## The authentication the endpoint does not carry +## Check each request in the Function before it calls a model + +The [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) template configures no authentication in front of its endpoint, and its rule runs the Function on every path. Any client that reaches the domain can therefore call a model, and every call is billed in Compute Time and Requests. The cost of a check is a secret to keep and a header every client sends. + +This Function rejects a request whose `Authorization` header does not carry the secret, before `Azion.AI.run` runs. The full shape also carries the next practice's model check and the last practice's error handling: + +```js +const ALLOWED_MODELS = ["Qwen/Qwen3-30B-A3B-Instruct-2507-FP8"]; + +async function handleRequest(request) { + const secret = Azion.env.get("INFERENCE_SECRET"); + if (!secret || request.headers.get("Authorization") !== `Bearer ${secret}`) { + return new Response(JSON.stringify({ error: "Unauthorized" }), { + status: 401, + headers: { "Content-Type": "application/json" }, + }); + } + + const input = await request.json(); + const model = input["model"]; + if (!ALLOWED_MODELS.includes(model)) { + return new Response(JSON.stringify({ error: `${model} is not allowed` }), { + status: 403, + headers: { "Content-Type": "application/json" }, + }); + } + + try { + const modelResponse = await Azion.AI.run(model, input); + return new Response(JSON.stringify(modelResponse), { + headers: { "Content-Type": "application/json" }, + }); + } catch (e) { + console.error(`${e.name}: ${e.message}`); + if (e.message.includes("validation error")) { + return new Response(JSON.stringify({ error: `Invalid input for ${model}` }), { + status: 400, + headers: { "Content-Type": "application/json" }, + }); + } + if (e.message.includes("model not found")) { + return new Response(JSON.stringify({ error: `${model} not found or not allowed` }), { + status: 400, + headers: { "Content-Type": "application/json" }, + }); + } + return new Response(JSON.stringify({ error: "AI internal error" }), { + status: 500, + headers: { "Content-Type": "application/json" }, + }); + } +} + +addEventListener("fetch", (event) => { + event.respondWith(handleRequest(event.request)); +}); +``` + +`Azion.env.get` reads the secret from an environment variable stored on your Azion account, per [Environment variables](/en/documentation/devtools/runtime/api-reference/environment-variables/). When the variable does not exist, the call returns `undefined`, and the Function refuses every request. The check covers every domain of the Workload: a custom domain answers in addition to the workload domain, and only the **Workload Domain Allow Access** switch of the Workload closes the workload domain. + +To check it, send a request without the header: the Function answers `401`. -An application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) answers on a Workload Domain, in the form `xxxxxxxxxx.map.azionedge.net`, and serves an OpenAI-compatible endpoint on it. Authentication on that endpoint is entirely yours. Azion neither issues a credential for a model call nor requires one. A request that reaches the domain reaches the function unless your own code stops it. +--- + +## Choose in the Function which models a request can reach + +The Function the template installs passes the `model` field of the request body to `Azion.AI.run` as it arrives. A client can therefore select any model the account can call, including one whose context, capabilities, or consumption you never planned for. The cost is a list to update each time you adopt a model. + +In the Function of the first practice, the list is `const ALLOWED_MODELS = ["Qwen/Qwen3-30B-A3B-Instruct-2507-FP8"];`, and a request that names another model answers `403`. To map names of your own to model ids, with a key per team, refer to [Route model calls through a gateway function](/en/documentation/guides/ai/inference/route-model-calls-through-a-gateway-function/). + +To check it, send a request whose `model` is not on the list: the Function answers `403`, and no model runs. + +--- + +## Copy each model id from its model page, or list the ids with Azion.AI.models() + +A model answers to its id and to nothing else: the first argument of `Azion.AI.run`, or the `model` field over HTTP, with no base URL or host beside it. Ids do not follow from the model name. Two forms can select the same model, `Qwen/Qwen2.5-VL-3B-Instruct-AWQ` and `qwen-qwen25-vl-3b-instruct-awq`, and no simple rule turns one into the other: `Qwen2.5` becomes `qwen25`. GPT-OSS 20B answers to `openai/gpt-oss-20b`, while `gpt-oss-20b` is refused. -The consequence is what a deployed application does when nothing is added to it. It answers every request that reaches the domain, and each request the endpoint serves runs a model. A model call consumes Compute Time, the duration of active execution multiplied by the memory allocated. An open endpoint is therefore consumption that anyone can start. For the metric and the rate, refer to [Pricing](/en/documentation/fundamentals/pricing/#ai-inference). +Copy the id from the model's page in [AI models](/en/documentation/platform/ai-inference/models/), or list the ids your account can call from a Function: -The check belongs in the function, before the model call. The function receives the request and preprocesses it, so it is the place a request can be rejected without a model running. Attaching a custom domain in place of the Workload Domain changes where the application answers, not what it checks. +```js +const modelIds = await Azion.AI.models(); +``` + +Never reuse the `model` field of a response as an id: it carries an internal id, and GPT-OSS 20B returns `gpt-oss-20b`, the form that is refused. + +To check it, run the call once: a wrong id rejects with `AIError: model not found or not allowed`. An account without access to AI Inference receives the same error, so confirm the access in [AI Inference limits](/en/documentation/platform/ai-inference/limits/) first. --- -## Model ids, copied rather than derived +## Send each model only the requests its page says it serves -A model is addressed by its id and by nothing else. The id is the first argument to `Azion.AI.run` and the `model` field of an HTTP request body, and no base URL or host accompanies it. +What a model accepts belongs to that model. Each page in [AI models](/en/documentation/platform/ai-inference/models/) states its context length, from 8k to 131k tokens across the catalog, its input types, text only or text and images, and its tool calling: Yes, Named tool only, or No. The model server refuses a prompt longer than the context, and a `tools` request that leaves the choice to a model whose tool calling is not Yes, with `Request failed with status 400`. The message does not say which value caused it. Where a page states nothing, the capability is unknown, not absent: confirm it before your code depends on it. -The ids do not share one form. `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` is the model's repository path unchanged. `casperhansen-mistral-small-24b-instruct-2501-awq` is the same path with the slash replaced by a hyphen. `qwen-qwen25-vl-3b-instruct-awq` is lowercased and has lost the dot in the version as well. `gpt-oss-20b` has dropped the organization entirely. +For example, Qwen2.5 VL AWQ 3B and 7B refuse a `tools` request that leaves the choice to the model, and return `tool_calls` when the body names the tool: `"tool_choice": {"type": "function", "function": {"name": "get_weather"}}`. The cost is a check per model in your code, since the platform reports the mismatch only as a status. -No rule turns a model name into its id. An id assembled from the name is right for some models in the catalog and wrong for others. The mistake is a string, which is why it reads as correct. Copy the id from the model's own page in [AI models](/en/documentation/platform/ai-inference/models/), where each page states the id that reaches that model. +To check it, read the capability on the model page whenever a call fails with status `400`. --- -## The capabilities a model states for itself +## Spell each request field as Model invocation lists it -What a model accepts is a property of that model rather than of AI Inference. Each page in [AI models](/en/documentation/platform/ai-inference/models/) states its own context length, the input types it takes, and whether it supports tool calling. The catalog is not uniform on any of the three. Context lengths run from 8k tokens to 131k tokens. Some models take text only, and others take text and images. Tool calling is stated as supported on some pages and unsupported on others. +A field the model does not know is ignored, with no error. A misspelled field therefore changes nothing in the response, and nothing tells you it was not applied. The cost is a check against [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) whenever you add a field. -A request that does not match is a request the model cannot serve. An image sent to a text-only model is one such request. So is a prompt longer than the context the model accepts. Both are decided in your code before the call, which is where they are checkable. +A body that sets the sampling temperature spells it `"temperature": 0.7`. Written as `"temprature": 0.7`, the field is ignored, and the request runs as if it carried no temperature. -Where a model page states nothing for a capability, nothing about that capability is stated. Read a blank as unknown rather than as a yes or a no, and confirm it before code depends on it. +To check it, send the field once with a value past its bound, such as `"temperature": 2.1`: a correctly spelled field rejects with `validation error: Maximum`, and a misspelled one returns a normal response. --- -## The input decided before the call +## Send the model only the input it needs, and bound the output + +Everything a model reads comes from your Function, in the same execution that awaits the answer. The model reads the whole prompt, and the time it takes to generate is time the Function waits. That wait does not count against the 2-second CPU limit of the Function, but it does count toward its 5-minute execution time, which is wall-clock time, per [Functions limits](/en/documentation/platform/functions/limits/). AI Inference bills Compute Time and Requests, and Compute Time, the duration of active execution multiplied by the memory allocated, grows with a longer generation. + +Send the section of a document that answers the question, not the whole document, and set `max_tokens` on every body, such as `"max_tokens": 1024`. The cost is a margin to keep: GPT-OSS 20B reasons before it answers, and with a small `max_tokens`, the reasoning can use the whole budget and return `content` set to `null`. + +To check it, read `usage.prompt_tokens` and `usage.completion_tokens` in the response before and after you change a prompt. + +--- + +## Read the response with optional chaining, and check why it stopped + +The generated text of a chat model sits four levels into the response, at `choices[0].message.content`, and that text is not always there. `content` is `null` when the model returns `tool_calls`, and on GPT-OSS 20B when the reasoning uses the whole `max_tokens`. With `stream` set to `true`, `Azion.AI.run` resolves to an async iterator of chunks instead, with no `choices[0].message` at all. -Everything a model reads was assembled by your function, in the same execution that makes the call. Preprocessing sits on one side of `Azion.AI.run` and response shaping on the other, and both are code you wrote. +Read each level with optional chaining, so a missing level returns `undefined` rather than throwing inside the Function: -The call is awaited, so the time the model spends generating is time the function spends waiting. The length of what you send is part of that. A prompt that carries a whole document where a section would do is read in full, inside an execution measured while it runs. +```js +const summary = modelResponse?.choices?.[0]?.message?.content?.trim(); +``` -Narrowing the input is done before the call rather than corrected after it. The response states what the request consumed: `usage.prompt_tokens` carries the tokens read from the request, and `usage.total_tokens` the request and the response together. Those two fields are how a change to a prompt is measured. For the response fields, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +The cost is a branch for the empty case. To check it, read `choices[0].finish_reason` whenever the text is empty: `tool_calls` means the model chose a tool, and `length` means it ran out of `max_tokens`. --- -## Optional chaining on the model response +## Tell the three kinds of failure apart by their message -Reading the text a chat model generated means walking four levels into an object: `choices`, its first entry, that entry's `message`, and its `content`. The worked functions Azion publishes walk them as `modelResponse?.choices?.[0]?.message?.content`, with optional chaining at every level. +A failed `Azion.AI.run` call rejects with an error that carries `name` and `message` only, with no `code` and no `status`. The message tells the cases apart. `AIError: model not found or not allowed` covers an id that does not exist and an account without access. `AIError: validation error` covers a body that does not match the model's schema, before the model runs. `Error: Request failed with status ` covers a refusal from the model server, with no reason. -The response is not identical for every model and every call. It carries fields that only some models return, such as the reasoning content and the log probabilities. Reading through the levels with optional chaining is what keeps a missing level from ending the read. +The Function of the first practice branches on the message: `e.message.includes("validation error")` and `e.message.includes("model not found")` answer `400`, and any other error answers `500`. It also writes each error with `console.error`. The cost is that a model server refusal reaches the caller with no cause, so the Function cannot tell the caller what to change. For every error and its cause, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/#errors). -The difference is where a failure lands. With optional chaining the function receives `undefined` and decides what the caller gets; without it, the read itself fails inside the function. One of Azion's worked functions chains `?.trim()` onto the same read, so the value is normalized where it is taken. +To check it, open [Real-Time Events](/en/documentation/platform/real-time-events/): the Functions Console data source carries the lines the Function writes with `console.error`, `AIError` messages included. --- @@ -73,13 +167,9 @@ The difference is where a failure lands. With optional chaining the function rec - The id to copy, and the capabilities each model states for itself. - The request fields a call accepts and the response object it returns. - The conditions under which Azion terminates or deprovisions a model. - What runs a model, and where Azion's part ends and yours begins. - Deploy an application and send a first request to a model. - The ceilings on the function a model call runs inside. - How AI Inference consumption is measured and charged. - Where to ask which value applies when a page states none. + Every request field, the response object, and each error a call returns. + Each model page, with its id and the context, input, and tools it serves. + Deploy the template that serves the endpoint these practices secure. + How Compute Time and Requests are measured and charged. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/edge-ai-reference.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/edge-ai-reference.mdx index 2ad0b02c8c..c96fdba5d3 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/edge-ai-reference.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/edge-ai-reference.mdx @@ -1,8 +1,8 @@ --- title: AI Inference description: >- - Call a language, vision, embedding, or reranking model from inside a function - with Azion.AI.run, on infrastructure you do not provision. + Run a language, vision, embedding, or reranking model from a Function with + Azion.AI.run, with no inference infrastructure to provision. meta_tags: 'AI Inference, AI models, Azion.AI.run, inference, LLM, VLM, embedding model, reranker, OpenAI-compatible API, Azion Runtime' namespace: docs_edge_ai_reference permalink: /documentation/platform/ai-inference/ @@ -11,18 +11,51 @@ import DocButton from '~/components/webkit/DocButton.vue'; import DocCardGroup from '@aziontech/webkit/doc-card-group' import DocCard from '@aziontech/webkit/doc-card' -Inference is the act of running a trained AI model. You send an input, and the model returns an output computed from the weights it learned in training: generated text, a ranking, or a vector of numbers that stands for the input. A model answers nothing until those weights are loaded into memory, on hardware sized for them. An inference service carries that part, keeping the models loaded and putting each one behind a request. +**AI Inference** is a Platform Resource that runs open-source AI models on Azion's distributed infrastructure, in response to the calls your [Functions](/en/documentation/platform/functions/) send. Running a trained model on an input is called inference: the model computes an output from the weights it learned in training. That output can be generated text, a ranking, or a vector of numbers that represents the input. A model answers only after its weights sit in memory, on hardware sized for them. An inference service keeps the models in memory, so you provision no hardware for them. -**AI Inference** runs the models on Azion's distributed infrastructure, on [Azion Runtime](/en/documentation/devtools/runtime/). A model is not an object you create. You name one by its id inside a [function](/en/documentation/platform/functions/), and that call is what invokes it. Use AI Inference to generate text from a prompt or to read the text out of an image. You can also use it to turn a document into a vector for retrieval, or to rank a set of documents against a query. +A Function passes a model id and a request body to `Azion.AI.run`, then awaits the model response. Use AI Inference to generate text from a prompt, extract the text from an image, convert a document into a vector for retrieval, or rank a set of documents against a query. - + --- -## Model call +## Request path -A function reaches a model through `Azion.AI.run`, the runtime binding that takes the model id and an OpenAI-compatible request body: +A Function calls a model while it handles a request, so the request stays open until the model response returns. The diagram follows one request from the client to the model and back. + +Solid arrows carry the request, and dotted arrows carry the response. Each label starts with the number of its step below. + +```mermaid +%%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% +flowchart TD + Client(["Client"]) + WL["Workload"] + App["Application"] + Fn["Function"] + AI["AI Inference"] + Client -->|"1. request"| WL + WL -->|"1. request"| App + App -->|"2. Run Function"| Fn + Fn -->|"3. Azion.AI.run"| AI + AI -.->|"4. model response"| Fn + Fn -.->|"5. response"| App + App -.->|"5. response"| Client +``` + +1. The request reaches a data center near the client through a domain of your [Workload](/en/documentation/platform/workloads/). The deployment of that Workload sets the [Application](/en/documentation/platform/applications/) that receives it. +2. A rule of the Application runs the Function with the _Run Function_ behavior. +3. The Function passes the model id and the request body to `Azion.AI.run`. +4. AI Inference runs the model and returns its response to the Function. +5. The Function builds its response from the model response, and the Application delivers it to the client. + +Workloads receives the request, Applications runs the rule, and Functions runs your code on [Azion Runtime](/en/documentation/devtools/runtime/). To see which side of that path Azion operates and which side you own, refer to [How AI Inference works](/en/documentation/platform/ai-inference/how-it-works/). + +--- + +## Function code + +This Function code sends a chat request to a model and reads the generated text: ```ts const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { @@ -36,63 +69,41 @@ const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", const answer = modelResponse?.choices?.[0]?.message?.content ``` -- The first argument is the model id, the string the model answers to. The ids do not share one form, so copy the one stated on the model's own page in [AI models](/en/documentation/platform/ai-inference/models/). -- The second argument is the request body. `messages` carries the conversation, and fields such as `stream`, `max_tokens`, and `temperature` shape the output. Every field a body accepts is in [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). -- The call is asynchronous. The function awaits it, and the generated text sits at `choices[0].message.content` in the resolved value. -- The id selects the model, and the code names no host, no base URL, and no credential. +- `Azion.AI.run` takes the model id first: the string a model answers to. Ids follow no single pattern, so copy each one from the model's page in [AI models](/en/documentation/platform/ai-inference/models/). +- The request body comes second. `messages` holds the conversation, and fields such as `stream`, `max_tokens`, and `temperature` control the output. [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) lists every field a body accepts. +- `Azion.AI.run` returns a promise. The Function awaits it and finds the generated text at `choices[0].message.content` of the resolved value. +- The code passes no host, no base URL, and no credential: the model id is the only address. -If you have written against the OpenAI chat completions format, the request body and the response object are the ones you already know, and the binding is what changes. - ---- - -## Invocation path - -A model call does not leave the request that started it. The function already handling the request is what calls the model, so the call is one step inside one execution rather than a round trip to a separate service. - -```mermaid -%%{init: {"layout": "elk", "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% -flowchart TD - User(["User"]) -->|"Request to the application domain"| DC["Nearest data center"] - DC --> App["Application applies its policies"] - App --> Fn["Function calls Azion.AI.run"] - Fn --> Cells["Azion Cells API, part of Orchestrator"] - Cells --> Model["AI Inference runs the model"] - Model -->|"Response returns along the same path"| User -``` - -1. A user sends a request to the domain of your application. -2. The nearest data center receives the request and forwards it to the application, which applies its policies and calls the function. -3. The function preprocesses the input and calls the model with `Azion.AI.run`, through the Azion Cells API. -4. The response travels back to the user along the same path. - -Four products carry that chain. [Applications](/en/documentation/platform/applications/) receives the request and applies policies to it, [Functions](/en/documentation/platform/functions/) runs the code that makes the call, [Orchestrator](/en/documentation/platform/orchestrator/) places the call on Azion Cells, and AI Inference runs the model. For the same chain with the line drawn between what Azion operates and what you own, refer to [How AI Inference works](/en/documentation/platform/ai-inference/how-it-works/). +A request body or a response object written for the OpenAI chat completions format reads the same here, and only the call that sends it changes. --- ## Scope and limits -- **Models**: AI Inference runs a catalog of open-source models. It holds large language models, vision language models that read text and images, an embedding model, and a reranker. Each model page states the id the model answers to and the capabilities it supports. For the catalog, refer to [AI models](/en/documentation/platform/ai-inference/models/). -- **Context length**: a per-model value, from 8k tokens to 131k tokens across the catalog. Size a prompt against the model you call rather than against the catalog. -- **Input**: every model reads text. The models whose input also covers images read an image passed as a URL, in a content part of the message. -- **Interfaces**: two of them reach the same models. A function calls `Azion.AI.run` directly, or an application you deploy serves an OpenAI-compatible endpoint at `/v1/chat/completions` on its own domain and calls the binding behind it. Both carry the same request body, documented in [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). -- **Management**: AI Inference has no management surface of its own, and no API of its own. You do not create, configure, or deploy a model. You call one by id from inside a function, so the function is the object you create and manage, through the interfaces [Functions](/en/documentation/platform/functions/) states. -- **Model adaptation**: adapting a model to a task with Low-Rank Adaptation is [LoRA Fine-Tune](/en/documentation/platform/ai-inference/lora-fine-tune/), an extension of AI Inference. The model pages state which models accept it. -- **Vectors**: an embedding model returns vectors, and [SQL Database](/en/documentation/platform/sql-database/) stores and queries them. The semantic and hybrid queries a retrieval-augmented generation flow reads from are in [Vector search](/en/documentation/platform/sql-database/vector-search/). -- **Termination**: Azion may terminate a model that consumes more than the maximum defined memory, or that runs for longer than the maximum allowed time. A model created and then not executed for more than three days may be deprovisioned. For what each condition covers, refer to [AI Inference limits](/en/documentation/platform/ai-inference/limits/). -- **Observability**: a model call runs inside a function, on an application, so what it did in production is read where that traffic is read. [Real-Time Metrics](/en/documentation/platform/real-time-metrics/) reports the traffic, and [Real-Time Events](/en/documentation/platform/real-time-events/) carries the requests and the logs. -- **Billing**: for how the consumption of a model call is measured and charged, refer to [Pricing](/en/documentation/fundamentals/pricing/#ai-inference). - -Azion hosts no inference endpoint and issues no credential for a model call. The OpenAI-compatible endpoint belongs to an application you deploy, and the authentication in front of it is one you define. +- **Access**: on the Hobby and Pro plans, AI Inference is available upon request, subject to approval. For the access each plan gives, refer to [AI Inference limits](/en/documentation/platform/ai-inference/limits/). +- **Models**: the catalog holds open-source large language models, vision language models that read text and images, an embedding model, and a reranker. Each model page states the id to pass and the capabilities the model supports, and `Azion.AI.models()` returns the ids your account can call. For the full list, refer to [AI models](/en/documentation/platform/ai-inference/models/). +- **Context length**: the context a model accepts varies by model, from 8k to 131k tokens across the catalog. Check the page of the model you call before you size a prompt. +- **Input**: all models accept text. A model that also accepts images reads each image from a URL, inside a content part of the message. +- **Streaming**: with `stream` set to `true`, the model streams its response instead of returning it whole. The endpoint of the AI Inference Starter Kit relays that stream as server-sent events, one `data:` line per chunk, ending with `data: [DONE]`. +- **Interfaces**: a Function calls `Azion.AI.run`, which takes no credential. Over HTTP, an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) template serves an OpenAI-compatible endpoint on its domain. The `model` field of the request body selects the model, and the template configures no authentication in front of the endpoint. Both interfaces carry the request body that [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) documents. +- **Local testing**: under `azion dev`, `Azion.AI` is `undefined`, so test model calls on a deployed Function. For the error the local call throws, refer to [AI Inference API](/en/documentation/devtools/runtime/api-reference/ai/). +- **Management**: Azion Console has no AI Inference screen, and neither the v4 Azion API nor the Azion CLI has an operation for AI Inference or its models. The entity you create and manage is the Function that calls a model, through the interfaces [Functions](/en/documentation/platform/functions/) documents. +- **Model adaptation**: [LoRA Fine-Tune](/en/documentation/platform/ai-inference/lora-fine-tune/), an extension of AI Inference, adapts a model to a task with Low-Rank Adaptation. Each model page states whether the model accepts it. +- **Vectors**: [SQL Database](/en/documentation/platform/sql-database/) stores and queries the vectors an embedding model returns. [Vector search](/en/documentation/platform/sql-database/vector-search/) covers the semantic search a retrieval-augmented generation flow runs on them. +- **Termination**: Azion may terminate a model, without prior notice, when it consumes more than the maximum defined memory or runs longer than the maximum allowed time. A model created and not executed for more than three days may be deprovisioned. [AI Inference limits](/en/documentation/platform/ai-inference/limits/) covers each condition. +- **Model terms**: a model may carry third-party license terms, and you are responsible for complying with them and for the output the model generates. Azion does not verify that output for accuracy. +- **Observability**: because a model call runs inside a Function on an Application, its traffic shows where that Application's traffic shows. [Real-Time Metrics](/en/documentation/platform/real-time-metrics/) reports it, and [Real-Time Events](/en/documentation/platform/real-time-events/) carries the requests and the Function's console logs, `AIError` messages included. +- **Billing**: [Pricing](/en/documentation/fundamentals/pricing/#ai-inference) states how a model call is measured and charged. --- ## Next steps - - - - - - + + + + + + diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/glossary.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/glossary.mdx index 5c9b8eba27..908e11a3d9 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/glossary.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/glossary.mdx @@ -1,24 +1,23 @@ --- title: Glossary description: >- - Find the meaning of every term the AI Inference documentation uses, from - Azion.AI.run and Azion Cells to Compute Time and Workload Domain. + Look up the terms the AI Inference documentation uses, from Azion.AI.run and + the model id to Compute Time and the workload domain. meta_tags: 'ai inference, glossary, terms, definitions, azion.ai.run, model id, compute time, workload domain' namespace: docs_edge_ai_glossary permalink: /documentation/platform/ai-inference/glossary/ --- -The terms below are the vocabulary of the [AI Inference](/en/documentation/platform/ai-inference/) documentation, and each definition links the page that carries the term. +Definitions for the terms the **AI Inference** documentation uses. | Term | Definition | | --- | --- | -| AI Inference | The product that runs artificial intelligence models on Azion's globally distributed infrastructure in response to a request. [AI Inference](/en/documentation/platform/ai-inference/) calls each model through `Azion.AI.run` from inside a [function](/en/documentation/platform/functions/), so you provision no infrastructure to execute one. | -| AI Inference Starter Kit | The template that deploys an application with an OpenAI-compatible API in front of AI Inference. The [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) creates the application and the function that calls the model, and the application answers on a Workload Domain. | -| Azion Cells | The feature of [Orchestrator](/en/documentation/platform/orchestrator/) through which AI Inference runs a model. A call to `Azion.AI.run` reaches the model through the Azion Cells API. | -| Azion Runtime | The execution environment for the JavaScript of a [function](/en/documentation/platform/functions/), built on Web standards. The function that calls a model runs on [Azion Runtime](/en/documentation/devtools/runtime/). | -| `Azion.AI.run` | The runtime binding a [function](/en/documentation/platform/functions/) calls to run a model. It takes the model id and a request body, and returns the object the model produces, such as `choices[0].message.content` for a chat model. [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) documents every field of the body. | -| Compute Time | The usage meter for the execution of a model, stated in GB-hour. For AI Inference and LoRA Fine-Tune, it is the active execution time in hours multiplied by the memory allocated in gigabytes. The [pricing page](/en/documentation/fundamentals/pricing/#ai-inference) carries the rate. | -| LoRA Fine-Tune | The Platform Resource that extends [AI Inference](/en/documentation/platform/ai-inference/) with fine-tuning of supported models through Low-Rank Adaptation. [LoRA Fine-Tune](/en/documentation/platform/ai-inference/lora-fine-tune/) runs on Azion's infrastructure, and the [model pages](/en/documentation/platform/ai-inference/models/) state which models support it. | -| model id | The string that identifies a model to `Azion.AI.run`, passed as its first argument. Two conventions are in use: the HuggingFace repository path, such as `Qwen/Qwen3-Embedding-4B`, and a lowercase form with no slash, such as `gpt-oss-20b`. Each [model page](/en/documentation/platform/ai-inference/models/) states the id to use for that model. | -| OpenAI-compatible API | The request and response shape AI Inference accepts for a chat model, matching the OpenAI chat completions format. The endpoint that serves it belongs to your own deployed application, on a Workload Domain, and AI Inference publishes no endpoint of its own. [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) carries the request body and the response. | -| Workload Domain | The read-only hostname Azion assigns a [workload](/en/documentation/platform/workloads/) at creation, in the format `xxxxxxxxxx.map.azionedge.net`. An application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves its OpenAI-compatible endpoint on this domain. A custom domain answers alongside it. | +| AI Inference | A Platform Resource that runs open-source AI models on Azion's distributed infrastructure, in response to the calls your Functions send. A [Function](/en/documentation/platform/functions/) calls a model with `Azion.AI.run`, so you provision no infrastructure to run one. [AI Inference](/en/documentation/platform/ai-inference/) describes the request path and the scope. | +| AI Inference Starter Kit | A template in Azion Console that deploys an Application serving an OpenAI-compatible API, with the Function that calls the model. The [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) also creates the Workload and its deployment, and the API answers on the workload domain. | +| Azion Runtime | The JavaScript runtime of [Functions](/en/documentation/platform/functions/), which runs the handler of a Function on Azion's distributed infrastructure. `Azion.AI.run` is one of its Azion APIs, so the Function that calls a model runs on [Azion Runtime](/en/documentation/devtools/runtime/). | +| `Azion.AI.run` | The runtime binding a Function calls to run a model. It takes the model id and a request body, and no credential, and it resolves to the response object, such as a `chat.completion` for a chat model, or to an iterator of chunks when `stream` is `true`. [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) documents every field. | +| Compute Time | The usage meter of AI Inference and LoRA Fine-Tune: the duration of active execution in hours multiplied by the memory allocated in gigabytes, stated in GB-hour. The [pricing page](/en/documentation/fundamentals/pricing/#ai-inference) carries the rate. | +| LoRA Fine-Tune | A Platform Resource that extends [AI Inference](/en/documentation/platform/ai-inference/) with the fine-tuning of supported models through Low-Rank Adaptation, on Azion's infrastructure. The [model pages](/en/documentation/platform/ai-inference/models/) state which models support it, and [LoRA Fine-Tune](/en/documentation/platform/ai-inference/lora-fine-tune/) describes it. | +| model id | The string that selects a model: the first argument of `Azion.AI.run`, or the `model` field of an HTTP request body. Two forms select the same model, a repository path such as `Qwen/Qwen3-Embedding-4B` and a lowercase form such as `qwen-qwen3-embedding-4b`. Each [model page](/en/documentation/platform/ai-inference/models/) states an id to use, and `Azion.AI.models()` returns the ids your account can call. | +| OpenAI-compatible API | The HTTP endpoint that an Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves on its domain. It takes a request body in the OpenAI chat completions format, with the model id in `model`, and passes it to `Azion.AI.run`. [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) documents the body and the response. | +| workload domain | The read-only hostname Azion assigns a [Workload](/en/documentation/platform/workloads/) at creation, in the form `.map.azionedge.net` on production infrastructure. An Application deployed from the AI Inference Starter Kit serves its OpenAI-compatible API on this domain. The [Workloads glossary](/en/documentation/platform/workloads/glossary/) defines it in full. | diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/how-it-works.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/how-it-works.mdx index 3df21b32d7..f1be3ac80b 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/how-it-works.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/how-it-works.mdx @@ -3,7 +3,7 @@ title: How AI Inference works description: >- Trace a model call from the request that arrives to the response that returns, and find where Azion's part ends and yours begins. -meta_tags: 'AI Inference, how it works, Azion.AI.run, invocation chain, Azion Cells, Orchestrator, OpenAI-compatible endpoint, model call' +meta_tags: 'AI Inference, how it works, Azion.AI.run, invocation chain, Workloads, Applications, Functions, OpenAI-compatible endpoint, model call' namespace: docs_edge_ai_how_it_works permalink: /documentation/platform/ai-inference/how-it-works/ --- @@ -14,7 +14,7 @@ import DocItem from '@aziontech/webkit/doc-item' When an application needs a model to answer something, it sends the input and holds the request open while the model generates a response. It then returns that response to the caller. Every model call has that shape. What differs from one platform to another is where the model runs and how much of it you operate. -[AI Inference](/en/documentation/platform/ai-inference/) runs the models, and a [function](/en/documentation/platform/functions/) is what calls one. The function reaches a model through `Azion.AI.run`, the runtime binding that takes a model id and a request body in the OpenAI shape. The call happens inside the function's execution, so a single piece of your code holds both the request that arrived and the answer the model produced. +[AI Inference](/en/documentation/platform/ai-inference/) is a Platform Resource that runs AI models, and a [Function](/en/documentation/platform/functions/) calls one with `Azion.AI.run`. That runtime binding takes a model id and a request body. The call happens inside the Function's execution, so a single piece of your code holds both the request that arrived and the answer the model produced. Three adjacent subjects have their own pages. [LoRA Fine-Tune](/en/documentation/platform/ai-inference/lora-fine-tune/) is the extension that adapts a model with LoRA, and it names the models that accept it. The vectors an embedding model returns are stored and queried with [Vector search](/en/documentation/platform/sql-database/vector-search/) in SQL Database. For the request body field by field, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). @@ -24,37 +24,42 @@ The mechanisms are the model call itself, the invocation chain, the binding and ## The model call -A model call starts in the code you deploy. `Azion.AI.run` is the runtime binding that makes it, and it takes two arguments: the id of the model, and the request body in the OpenAI shape. The call is asynchronous, so the function awaits it and reads the model response from the resolved value. For a chat model, the generated text sits at `choices[0].message.content` inside that response. +A model call starts in the code you deploy. `Azion.AI.run` is the runtime binding that makes it, and it takes two arguments: the id of the model, and the request body. The call is asynchronous, so the Function awaits it and reads the model response from the resolved value. For a chat model, the generated text sits at `choices[0].message.content` inside that response. -The id is the only address the code needs. Azion publishes no inference endpoint of its own, so a function configures no base URL and names no host to reach a model. Model ids do not follow a single form: some are a repository path such as `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`, and others a lowercase string such as `gpt-oss-20b`. Copy the id from the model's own page in [AI models](/en/documentation/platform/ai-inference/models/) rather than deriving it from the model name. +The id is the only address the code passes: `Azion.AI.run` takes no base URL, no host, and no credential. Model ids do not follow a single form: some are a repository path such as `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`, and others a lowercase string such as `qwen-qwen25-vl-3b-instruct-awq`. Copy the id from the model's own page in [AI models](/en/documentation/platform/ai-inference/models/) rather than deriving it from the model name, or list the ids your account can call with `Azion.AI.models()`. A call rejects with `AIError: model not found or not allowed` when the id does not exist or when the account has no access to the model, and the error does not say which. -Around the call, the function is ordinary code. It preprocesses the input before it invokes the model, and it shapes what the model returns before the caller sees it. The same execution can retrieve context from a store and reach an external service. The retrieval, the call, and the response shaping happen within one request. +Around the call, the Function is ordinary code. It can preprocess the input before it invokes the model and shape what the model returns before the caller sees it. The same execution can also retrieve context from a store and reach an external service, all within one request. --- ## The invocation chain -This diagram traces one request, from the user to the model and back. Each arrow is a hand-off from one part of the platform to the next, and each part is named in the list that follows. +This diagram traces one request, from the client to the model and back. Solid arrows carry the request, and dotted arrows carry the response. Each label starts with the number of its step below. ```mermaid -%%{init: {"layout": "elk", "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% +%%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% flowchart TD - User(["User"]) -->|"Request to the application domain"| DC["Nearest data center"] - DC -->|"Forwards the request"| App["Application applies its policies"] - App -->|"Calls the function"| Fn["Function preprocesses the input"] - Fn -->|"Azion.AI.run"| Cells["Azion Cells API, part of Orchestrator"] - Cells --> Model["AI Inference runs the model"] - Model -->|"Response travels back along the same path"| User + Client(["Client"]) + WL["Workload"] + App["Application"] + Fn["Function"] + AI["AI Inference"] + Client -->|"1. request"| WL + WL -->|"1. request"| App + App -->|"2. Run Function"| Fn + Fn -->|"3. Azion.AI.run"| AI + AI -.->|"4. model response"| Fn + Fn -.->|"5. response"| App + App -.->|"5. response"| Client ``` -Read the diagram as four movements: +1. The request reaches a data center near the client through a domain of a [Workload](/en/documentation/platform/workloads/). The Workload's deployment sets the Application that receives the request. +2. A rule of the Application runs the Function with the _Run Function_ behavior. +3. The Function calls the model with `Azion.AI.run`, passing the model id and the request body. +4. AI Inference runs the model and returns the model response to the Function. +5. The Function builds its response from the model response, and the Application delivers it to the client. -1. The user sends a request to the domain of the application. -2. The nearest data center receives the request and forwards it to the application, which applies its policies and calls the function. -3. The function orchestrates the inference. It preprocesses the input and calls the model with `Azion.AI.run`, through the Azion Cells API. -4. The response travels back to the user along the same path. - -Five parts carry that chain. [Applications](/en/documentation/platform/applications/) is the application layer that receives the request and applies policies to it. Functions executes the inference logic: it orchestrates retrieval, integrates external services, and issues the model call. AI Inference runs the models, and the function that calls them runs on [Azion Runtime](/en/documentation/devtools/runtime/). [Orchestrator](/en/documentation/platform/orchestrator/) manages the requests for Azion Cells execution, and Azion Cells is the part of Orchestrator that the binding reaches. Azion's distributed infrastructure is what all of it runs on, which is why the data center that answers is the one nearest to the user. +Four Platform Resources carry that chain, on Azion's distributed infrastructure. Workloads receives the request, and the deployment of the Workload sets the Application. [Applications](/en/documentation/platform/applications/) runs the rule that calls the Function. Functions runs the code that calls the model, on [Azion Runtime](/en/documentation/devtools/runtime/). AI Inference runs the model. --- @@ -62,11 +67,11 @@ Five parts carry that chain. [Applications](/en/documentation/platform/applicati A request reaches a model through one of two interfaces, and both end at the same binding. -The first is the binding itself. Inside a function, the code calls `Azion.AI.run`, and nothing stands between that code and the model call. The function decides which model answers, what the request body carries, and what happens before and after. +The first is the binding itself. Inside a Function, the code calls `Azion.AI.run` directly. The Function decides which model answers, what the request body carries, and what happens before and after. -The second is an OpenAI-compatible HTTP endpoint, and the mechanism behind it is that Azion does not host it. The host is the application you deploy, so the endpoint is one more thing that application serves, on the domain it answers on. [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) carries the path, the domain form, and the request the endpoint accepts. +The second is an OpenAI-compatible HTTP endpoint that an Application you deploy serves on its domain. The [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) template deploys such an Application. [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) carries the path, the domain form, and the request the endpoint accepts. -Behind the endpoint there is still a function, and it calls `Azion.AI.run` the way any other function does. The second interface is therefore the first one with an application in front of it, published in a request shape that clients already speak. That endpoint carries no Azion authentication and Azion issues no credential for it, so any check it performs is one your application defines. +Behind the endpoint there is still a Function, and it calls `Azion.AI.run` the way any other Function does. In the Function that the template installs, the `model` field of the request body selects the model, and the Function passes the whole body to the binding. The second interface is therefore the first one with an Application in front of it, published in a request shape that clients already speak. The template configures no authentication in front of the endpoint, so any check it performs is one you add to your Application. --- @@ -74,21 +79,23 @@ Behind the endpoint there is still a function, and it calls `Azion.AI.run` the w The invocation chain crosses a line between what Azion operates and what you deploy. Where that line falls is what tells you which side a problem sits on. -Azion runs the models and everything under them: the models themselves, the hardware that executes them, and the orchestration that places a call on Azion Cells. You load no model, size no cluster, and keep no inference server running. You also do not select which data center serves a given request, because the request is answered by the nearest one. +Azion runs the models and the infrastructure that executes them. You load no model, size no cluster, and keep no inference server running. You also do not select which data center serves a request: Azion routes it to a data center near the client. + +You own everything that decides what the model is asked. The Function is your code: the input handling, the prompt, the model id, the request body, and the response the caller finally receives. The Application in front of the Function is yours as well, along with the domain your Workload answers on and the authentication the Application checks. When a response is wrong, start with the input your Function sent. -You own everything that decides what the model is asked. The function is your code: the input handling, the prompt, the model id, the request body, and the response the caller finally receives. The application in front of the function is yours as well, along with the domain it answers on and the authentication it checks. When a response is wrong, the input your function sent is where to look first, because the model answered exactly that. +The models also carry terms of their own. A model may be subject to third-party license terms, and you are responsible for complying with them and for the output the model generates. Azion does not verify that output for accuracy. --- ## What the design costs -Running a model from inside a function keeps the request and the model call in one execution. Three things pay for that. +Running a model from inside a Function keeps the request and the model call in one execution. Three things pay for that. -The model call happens inside one execution. The function awaits it, so the time the model takes to generate is time the function spends waiting, and the request stays open for both. A function that calls a model is therefore bounded by two sets of values at once: its own, in [Functions limits](/en/documentation/platform/functions/limits/), and the model's, in [AI Inference limits](/en/documentation/platform/ai-inference/limits/). +The model call happens inside one execution. The Function awaits it, so the time the model takes to generate is time the Function spends waiting, and the request stays open for both. That wait counts toward the Function's execution time, which is wall-clock time, and not toward its CPU time. The Function's own limits are in [Functions limits](/en/documentation/platform/functions/limits/), and the conditions Azion applies to a model are in [AI Inference limits](/en/documentation/platform/ai-inference/limits/). -Azion bounds the model side as well. Azion may terminate a model that consumes more than the maximum defined memory, or that runs longer than the maximum allowed time. A model that is created and then not executed for more than three days may be deprovisioned. For what each of those conditions covers, refer to [AI Inference limits](/en/documentation/platform/ai-inference/limits/). +Azion bounds the model side as well. Azion may terminate, without prior notice, a model that consumes more than the maximum defined memory, or that runs longer than the maximum allowed time. A model that is created and then not executed for more than three days may be deprovisioned. For what each of those conditions covers, refer to [AI Inference limits](/en/documentation/platform/ai-inference/limits/). -The OpenAI-compatible endpoint is a shape your application serves, not a service Azion operates for you. You build the application that exposes it, you keep it running, and you secure it. Azion hands you no managed endpoint to point a client at. The endpoint is yours to change, and yours to keep answering. +The OpenAI-compatible endpoint is a shape your Application serves. You deploy the Application that exposes it, you keep it running, and you secure it, so the endpoint is yours to change and yours to keep answering. --- @@ -97,11 +104,8 @@ The OpenAI-compatible endpoint is a shape your application serves, not a service Every field the request body accepts, on both interfaces. - Deploy an application and send a first request to a model. - The id to pass, and what each model states about itself. + Deploy an Application and send a first request to a model. The conditions under which Azion terminates or deprovisions a model. - The runtime that holds the binding and the ceilings that bound a call. - The deployed shape around a model call, where your application is the inference endpoint. - How AI Inference consumption is measured and charged. + The deployed shape around a model call, where your Application is the inference endpoint. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/limits.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/limits.mdx index abeedea8a2..3bf21a7853 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/limits.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/limits.mdx @@ -1,8 +1,8 @@ --- title: AI Inference limits description: >- - Review the conditions under which Azion terminates or deprovisions an AI - Inference model, and where each remaining limit is stated. + Review who can call AI Inference on each plan, the conditions under which + Azion terminates or deprovisions a model, and where each other limit is stated. meta_tags: 'AI Inference, limits, model limits, memory, execution time, termination, deprovisioning, context length' namespace: docs_edge_ai_limits permalink: /documentation/platform/ai-inference/limits/ @@ -12,7 +12,21 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -A model in [AI Inference](/en/documentation/platform/ai-inference/) meets two kinds of boundary. The first is a condition: Azion terminates a model that consumes too much memory or runs too long, and deprovisions one that is never executed. The second is a stated value that bounds one call, such as a request field or a model's context length. This page carries the conditions, and names the page that states each value. +A model call in [AI Inference](/en/documentation/platform/ai-inference/) meets three kinds of boundary. The first is access, which depends on the plan of the account. The second is a condition: Azion may terminate the execution of a model that consumes too much memory or runs too long, and may deprovision one that is created and not executed for more than three days. The third is a stated value that bounds one call, such as a request field or a model's context length. This page carries the access and the conditions, and names the page that states each value. + +## Access by plan + +Access to AI Inference depends on the plan. The plans are the ones the [Azion pricing page](https://www.azion.com/en/pricing/) lists. + +| Plan | AI Inference access | +| --- | --- | +| Hobby | Upon request, subject to approval | +| Pro | Upon request, subject to approval | +| Enterprise | Custom | + +An account without access receives `AIError: model not found or not allowed` for every model id. That is the same error a model id that does not exist returns, so the error alone does not tell the two cases apart. + +--- ## Model termination and deprovisioning @@ -28,13 +42,15 @@ Azion applies the conditions below to every model. The first two bound a model w ## Limits stated on other pages -The values that bound a model call belong to the model, to the request schema, or to the function that makes the call. Each one is stated on the page that owns it. To size a prompt, read the context length on the page of the model you call. +The values that bound a model call belong to the model, to the request schema, or to the Function that makes the call. Each one is stated on the page that owns it. To size a prompt, read the context length on the page of the model you call. | Limit | What it bounds | Where it is stated | | --- | --- | --- | | Context length | The context a model accepts, in tokens. Each model page states its own value. | [AI models](/en/documentation/platform/ai-inference/models/) | -| Request field bounds | The values `temperature`, `top_p`, `n`, `presence_penalty`, and `frequency_penalty` accept. | [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) | -| Function limits | The code size, memory, execution time, and outbound requests of the function that calls the model. | [Functions limits](/en/documentation/platform/functions/limits/) | +| Request field bounds | The values `temperature`, `top_p`, `n`, `max_tokens`, `presence_penalty`, and `frequency_penalty` accept. | [Model invocation](/en/documentation/platform/ai-inference/model-invocation/) | +| Function limits | The code size, memory, execution time, and outbound requests of the Function that calls the model. | [Functions limits](/en/documentation/platform/functions/limits/) | + +The time a Function waits inside `Azion.AI.run` does not count against the 2-second CPU limit of the Function. For example, a generation of 2048 tokens that takes about 20 seconds completes without the Function being terminated. The 5-minute execution time of a Function is wall-clock time and includes async operations, so the wait counts there. --- @@ -43,9 +59,7 @@ The values that bound a model call belong to the model, to the request schema, o The request fields a model call accepts, with the bounds on each one. - The catalog to open for the context length and the id of a single model. - The values that bound the function a model call runs inside. - What executes a model, and what the conditions on this page apply to. + The values that bound the Function a model call runs inside. The metric a model call is measured in, and the rate charged for it. Where to ask which value applies when this page states none. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/lora-fine-tune.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/lora-fine-tune.mdx index 0299176569..ad13c37631 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/lora-fine-tune.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/lora-fine-tune.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Low-Rank Adaptation (LoRA) adapts a model to a task by training a small set of additional weights instead of retraining the whole model. **LoRA Fine-Tune** applies that method to supported models on Azion's infrastructure, as an extension of [AI Inference](/en/documentation/platform/ai-inference/). LoRA applies to some models and not to others, and each model page states which case it is. +Low-Rank Adaptation (LoRA) adapts a model to a task by training a small set of additional weights instead of retraining the whole model. **LoRA Fine-Tune** is a Platform Resource that extends [AI Inference](/en/documentation/platform/ai-inference/) with that method, for supported models, on Azion's infrastructure. LoRA applies to some models and not to others, and each model page states which case it is. ## Supported models @@ -36,7 +36,9 @@ For the category, the id, the context length, and the input types of a model in ## Relationship to AI Inference -LoRA Fine-Tune is a Platform Resource of its own that extends AI Inference. The adaptation runs on Azion's infrastructure, with no infrastructure for you to provision or manage. You are responsible for the training data, the model inputs and outputs, and the third-party license of the model you adapt. +LoRA Fine-Tune extends AI Inference. The adaptation runs on Azion's infrastructure, with no infrastructure for you to provision or manage. You are responsible for the training data, the model inputs and outputs, the third-party license of the model you adapt, compliance with the applicable terms, and the security and legality of your use. + +No public interface creates or trains an adapter, the set of additional weights LoRA trains for a model. Azion Console has no LoRA Fine-Tune screen, and neither the v4 Azion API nor the Azion CLI has an operation for it. --- @@ -51,9 +53,7 @@ LoRA Fine-Tune is billed on two metrics, Compute Time and Requests, and it is me The category, id, context length, and input types of every model AI Inference runs. - The product LoRA Fine-Tune extends, and the one that runs the models. What executes a model, and where Azion's part of a model call ends. - The request body and the binding that a call to a model travels through. The rate charged for the Compute Time and the Requests of LoRA Fine-Tune. Where to ask what this page does not state about adapting a model. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/model-invocation.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/model-invocation.mdx index 264de63954..7283779251 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/model-invocation.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/model-invocation.mdx @@ -1,7 +1,7 @@ --- title: Model invocation description: >- - Send a request to an AI Inference model from a function or over HTTP, and read + Send a request to an AI Inference model from a Function or over HTTP, and read the fields every request body accepts. meta_tags: 'AI Inference, model invocation, Azion.AI.run, chat completions, request schema, messages, embeddings, reranking' namespace: docs_edge_ai_model_invocation @@ -12,15 +12,23 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -You invoke a model with two things: the model id, and an OpenAI-compatible request body. [AI Inference](/en/documentation/platform/ai-inference/) accepts that request through two interfaces, and both reach the same models. You call the `Azion.AI.run` binding inside a [function](/en/documentation/platform/functions/), or you post to the OpenAI-compatible HTTP endpoint that the application you deploy serves. The request fields are the same on both. +You invoke a model with two things: the model id, and a request body in the format the model takes. For a chat model, that body follows the OpenAI chat completions format. [AI Inference](/en/documentation/platform/ai-inference/) accepts that request through two interfaces, and both reach the same models. You call the `Azion.AI.run` binding inside a [Function](/en/documentation/platform/functions/), or you post to the OpenAI-compatible HTTP endpoint that an Application deployed from a template serves. The request fields are the same on both, and over HTTP the body also carries the model id. ## The Azion.AI.run binding -`Azion.AI.run` is the runtime binding a function calls to invoke a model. It takes the model id and the request body this page describes, and the call is asynchronous. The binding belongs to the runtime rather than to AI Inference, so its parameters, the call, and its return value are documented with the other runtime bindings, in [AI Inference API](/en/documentation/devtools/runtime/api-reference/ai/). +`Azion.AI.run` is the runtime binding a Function calls to invoke a model. It takes the model id first and the request body this page describes second, and the call is asynchronous. The first argument decides the model, so the body does not need the id, and a `model` field in the body is ignored. The binding takes no credential, no base URL, and no host. The binding belongs to the runtime rather than to AI Inference, so its parameters, the call, and its return value are documented with the other runtime bindings, in [AI Inference API](/en/documentation/devtools/runtime/api-reference/ai/). + +`Azion.AI.models()` returns a promise that resolves to an array of the model ids your account can call: + +```ts +const modelIds = await Azion.AI.models() +``` ## The HTTP endpoint -The HTTP endpoint accepts a POST request to `/v1/chat/completions` carrying a JSON body. Azion does not host that endpoint. The host is the application you deploy, which answers at the Workload Domain of the workload that serves it, in the form `xxxxxxxxxx.map.azionedge.net`, or at a custom domain of that workload. An application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves the endpoint on that domain. +An Application deployed from the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/) serves the endpoint on the domains of its Workload: the workload domain, in the form `xxxxxxxxxx.map.azionedge.net`, or a custom domain of that Workload. The Function the template installs reads the model id from the `model` field of the body, and passes the whole body to `Azion.AI.run`. + +The endpoint takes a `POST` request with a JSON body that carries `model`, on any path of the domain. `/v1/chat/completions` is the path OpenAI clients use, and the same endpoint also serves embedding and reranking bodies. The `Content-Type` header must be exactly `application/json`: a header that adds a `charset` parameter is refused. The template configures no authentication in front of the endpoint. When you add authentication to your Application, include the header it requires, for example `-H "Authorization: Bearer [TOKEN VALUE]"`. A request to a chat model over HTTP: @@ -28,45 +36,104 @@ A request to a chat model over HTTP: curl -X POST https:///v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ - "model": "Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", - "max_tokens": 500, + "model": "qwen-qwen25-vl-3b-instruct-awq", + "max_tokens": 16, "messages": [ - { "role": "user", "content": "Name three European capitals." } + { "role": "user", "content": "Name one European capital." } ] }' ``` -Azion issues no credential for a model call, and the endpoint carries no Azion authentication. Authentication is what you add to your own application. When your application requires a header, include it in the request, for example `-H "Authorization: Bearer [TOKEN VALUE]"`. +The endpoint returns the object the model returns: + +```json +{ + "id": "chatcmpl-0cb926279c564d868e3e3e8a2fc20313", + "object": "chat.completion", + "created": 1794444659, + "model": "qwen-qwen25-vl-3b-instruct-awq", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "Paris, France is a European capital.", + "refusal": null, + "annotations": null, + "audio": null, + "function_call": null, + "tool_calls": [], + "reasoning_content": null + }, + "logprobs": null, + "finish_reason": "stop", + "stop_reason": null + } + ], + "service_tier": null, + "system_fingerprint": null, + "usage": { + "prompt_tokens": 24, + "total_tokens": 33, + "completion_tokens": 9, + "prompt_tokens_details": null + }, + "prompt_logprobs": null, + "kv_transfer_params": null +} +``` --- ## Request fields -These fields form the body of a chat model request, whether you send it through the binding or over HTTP. Over HTTP, the body also carries a `model` field holding the model id. Through the binding, the first parameter carries the id and the body does not repeat it. Each chat model names the [OpenAI Chat API](https://developers.openai.com/api/reference/overview) as the endpoint it is compatible with, so a field behaves as that schema describes. The types, defaults, and bounds below are the ones AI Inference states. A dash in the Default column means the schema sets no default for that field. +These fields form the body of a chat model request, whether you send it through the binding or over HTTP. Over HTTP, the body also carries a `model` field holding the model id. Through the binding, the first parameter carries the id. Each chat model names the [OpenAI Chat API](https://developers.openai.com/api/reference/overview) as the endpoint it is compatible with. The types, defaults, and bounds below are the ones the chat models' request schema states. A dash in the Default column means the schema sets no default for that field. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | -| `messages` | array | Yes | — | The conversation sent to the model. Each entry is a system, user, or assistant message object. | +| `messages` | array | Yes | — | The conversation sent to the model. Each entry is a system, user, assistant, or tool message object. | | `temperature` | number | No | — | Sampling temperature. Minimum `0`, maximum `2`. | -| `top_p` | number | No | `1` | Top-p sampling value. Minimum `0`, maximum `1`. | +| `top_p` | number | No | — | Top-p sampling value. Maximum `1`. | | `n` | integer | No | `1` | Number of responses to generate. Minimum `1`. | | `stream` | boolean | No | `false` | Streams the response instead of returning it whole. Accepts `true` or `false`. | -| `max_tokens` | integer | No | — | Maximum number of tokens the model generates. Minimum `1`. | -| `presence_penalty` | number | No | `0` | Presence penalty applied to the output. Minimum `-2`, maximum `2`. | -| `frequency_penalty` | number | No | `0` | Frequency penalty applied to the output. Minimum `-2`, maximum `2`. | -| `tools` | array | No | — | The tool definitions the model may call, on a model whose Tool calling capability is Yes. The model pages that support it show the shape. | +| `max_tokens` | integer | No | — | Maximum number of tokens the model generates for each response. Minimum `1`. | +| `presence_penalty` | number | No | — | Presence penalty applied to the output. Maximum `2`. | +| `frequency_penalty` | number | No | — | Frequency penalty applied to the output. Maximum `2`. | +| `tools` | array | No | — | The tool definitions the model may call. The model pages that support it show the shape. | + +A value past a minimum or a maximum rejects with `validation error: Minimum` or `validation error: Maximum` before the model runs. The validator also accepts `top_p` down to `0` and both penalties down to `-2`, but the model server refuses a request that sets `temperature` and `top_p` to `0` and both penalties to `-2` together. With `n` set to `2`, `choices` carries two entries, and `max_tokens` applies to each. + +A field the model does not know is ignored, with no error. A misspelled field name therefore changes nothing in the response: check each name against the tables on this page. Context length, tool calling, and the input types a model accepts are per-model values, and they are not part of this schema. For the model you call, refer to [AI models](/en/documentation/platform/ai-inference/models/). -## Message objects +### Tool choice, seed, stop, and log probabilities -Every entry in the `messages` array is a message object, and its `role` field states which of the three objects it is. Each object requires `role` and `content`. The `role` field is an enum holding one value, so the object and the role are the same choice. The `content` field takes text as a string, or, on a model that accepts images, an array of content parts. +The chat models also accept the fields below, which the request schema does not list. The descriptions apply to Qwen3 30B A3B Instruct 2507 FP8. -| Role | Schema object | Required fields | +| Field | Type | Description | | --- | --- | --- | -| `system` | `SystemMessage` | `role`, `content` | -| `user` | `UserMessage` | `role`, `content` | -| `assistant` | `AssistantMessage` | `role`, `content` | +| `tool_choice` | string or object | How the model picks a tool: `auto`, `none`, `required`, or an object that names one function. | +| `seed` | integer | A sampling seed: the same request with the same `seed` can return the same output. | +| `stream_options` | object | Options for a streamed response, such as `{"include_usage": true}`. Requires `stream` set to `true`. | +| `logprobs` | boolean | With `true`, fills `choices[].logprobs` with the log probability of each generated token. | +| `top_logprobs` | integer | The number of alternative tokens listed for each generated token, with `logprobs` set to `true`. | +| `stop` | array of strings | Sequences that end the generation before they are written. | + +`auto` is the behavior with no `tool_choice`, `required` forces a tool call, and `none` prevents `tool_calls`. With `none`, Qwen3 30B can still write the call as text in `content`. On Qwen2.5 VL AWQ 3B and 7B, an object that names the tool returns `tool_calls`, with `finish_reason` set to `stop`. A `seed` that is not an integer, a `tool_choice` outside these values, and `stream_options` without `stream` are refused with `Request failed with status 400`. + +With `logprobs`, each entry of `choices[].logprobs.content` carries `token`, `logprob`, `bytes`, and `top_logprobs`. With `stop`, the response ends before the sequence, and `finish_reason` is `stop`. + +## Message objects + +Every entry in the `messages` array is a message object, and its `role` field states which of the four objects it is. The `content` field takes text as a string, or, on a model that accepts images, an array of content parts. + +| Role | Required fields | +| --- | --- | +| `system` | `role`, `content` | +| `user` | `role`, `content` | +| `assistant` | `role`, `content`; `content` is `null` when the message carries `tool_calls` | +| `tool` | `role`, `tool_call_id`, `content` | A `messages` array that carries a previous turn: @@ -81,6 +148,33 @@ A `messages` array that carries a previous turn: } ``` +When a model calls a tool, its response carries `tool_calls`, with `content` set to `null` and `finish_reason` set to `tool_calls`. To return the result, send the conversation again with the assistant message as the model returned it, followed by a `tool` message. The `tool_call_id` of that message is the `id` of the tool call, and its `content` carries the result. The model then answers in text. A `messages` array that returns a tool result, sent with the same `tools` array as the first request: + +```json +{ + "messages": [ + { "role": "system", "content": "You are a helpful assistant with access to tools." }, + { "role": "user", "content": "What is the weather in London?" }, + { + "role": "assistant", + "content": null, + "tool_calls": [ + { + "id": "chatcmpl-tool-789b0d0737f84d09b61eee169a3bea75", + "type": "function", + "function": { "name": "get_weather", "arguments": "{\"location\": \"London\"}" } + } + ] + }, + { + "role": "tool", + "tool_call_id": "chatcmpl-tool-789b0d0737f84d09b61eee169a3bea75", + "content": "{\"temperature_c\": 14, \"condition\": \"light rain\"}" + } + ] +} +``` + A model that accepts images takes `content` as an array of content parts instead of a string. Each part states its `type`, and carries the field that type uses. The model pages of the models that accept images show this form; a text-only model takes the string. | Content part | Type | Carries | @@ -88,7 +182,7 @@ A model that accepts images takes `content` as an array of content parts instead | `type` | string | Which kind of part this is: `text` or `image_url`. | | `text` | string | The text of the part, when `type` is `text`. | | `image_url` | object | The image of the part, when `type` is `image_url`. | -| `image_url.url` | string | The URL the model reads the image from. | +| `image_url.url` | string | An `https` URL that serves the image, or a `data:` URL with the image in base64. | A `content` array carrying text and an image: @@ -97,39 +191,65 @@ A `content` array carrying text and an image: "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, - { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } + { "type": "image_url", "image_url": { "url": "" } } ] } ``` -To find out whether a model accepts images, read the input types on its page in [AI models](/en/documentation/platform/ai-inference/models/). +The URL must serve an image the model can fetch. A URL that serves no image fails with `Request failed with status 500`, which does not name the image as the cause. To find out whether a model accepts images, read the input types on its page in [AI models](/en/documentation/platform/ai-inference/models/). + +--- + +## Streaming responses + +With `stream` set to `true`, the two interfaces deliver the response in chunks, each a `chat.completion.chunk` object. The text of each chunk is in `choices[0].delta.content`, and the last chunk of text carries `finish_reason`. + +- **Through the binding**, `Azion.AI.run` resolves to an async iterator of parsed chunk objects, which the Function reads with `for await`. No `[DONE]` item reaches the iterator. +- **Over HTTP**, the endpoint answers with `Content-Type: text/event-stream`, one `data:` line per chunk, and a final `data: [DONE]` line. + +`usage` arrives only when the body sets `stream_options` to `{"include_usage": true}`. It comes in one more chunk at the end, whose `choices` array is empty: + +```json +{ + "id": "chatcmpl-2d0e9241b82048c49b9f946c746818b1", + "object": "chat.completion.chunk", + "created": 1794443931, + "model": "qwen-qwen3-30b-a3b-instruct-2507-fp8", + "choices": [], + "usage": { + "prompt_tokens": 20, + "total_tokens": 30, + "completion_tokens": 10 + } +} +``` --- ## Embedding requests -An embedding model takes a request body the chat schema does not define. `input` carries the text to embed and is the only required field. The other two shape the vector that comes back, and each accepts a fixed set of values; a value outside the set is not part of the schema. +An embedding model takes a request body the chat schema does not define. `input` carries the text to embed and is the only required field. The other two shape the vector that comes back, and each accepts a fixed set of values. A value outside the set rejects with `validation error: Enum`. | Field | Type | Required | Description | | --- | --- | --- | --- | -| `input` | string, or an array | Yes | The text to embed. An array holds strings, integers, or arrays of integers. | +| `input` | string, or an array of strings | Yes | The text to embed. An array returns one embedding per string. | | `encoding_format` | string | No | The encoding of the embedding in the response: `float` or `base64`. | | `dimensions` | integer | No | The size of the vector the model returns: `256`, `512`, `1024`, `2048`, or `4096`. | +Without `dimensions`, Qwen3 Embedding 4B returns a vector of 2560 numbers. With `dimensions` set to `4096`, the request is accepted and the vector still has 2560 numbers. With `base64`, the embedding is a string that decodes to little-endian 32-bit floats, 4 bytes per dimension. The vectors are normalized to a length of 1. + To store the vectors an embedding model returns and query them, refer to [Vector search](/en/documentation/platform/sql-database/vector-search/). ## Reranking requests -A reranking request does not carry a `messages` array. It carries one of two input pairs instead, and each pair holds a single value and a collection to score against it. A request uses one pair or the other, and the schema names `query` and `documents` as the required pair. +A reranking request does not carry a `messages` array. It carries a query and the documents to rank against it, and both are required. | Field | Type | Carries | | --- | --- | --- | | `query` | string | The query the documents are ranked against. | | `documents` | array of strings | The documents to rank by relevance to `query`. | -| `text_1` | string | The first text the model processes. | -| `text_2` | array of strings | The texts the model scores against `text_1`. | -| `top_n` | integer | Declared by the schema, which states no default and no bounds. | -| `max_tokens_per_doc` | integer | Declared by the schema, which states no default and no bounds. | +| `top_n` | integer | The number of results to return, highest scores first. | +| `max_tokens_per_doc` | integer | Declared by the schema, which states no default and no bounds. Accepted, with no documented effect. | --- @@ -137,6 +257,8 @@ A reranking request does not carry a `messages` array. It carries one of two inp A model returns one object, whatever interface carried the request. The shape depends on what the model does, and the three below cover every model in the catalog. The model pages show a complete payload for the models that have one. +The `model` field carries the account's internal id for the model, in lowercase with hyphens, which can differ from the id the request sent. A request to `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` returns `qwen-qwen3-30b-a3b-instruct-2507-fp8`, and GPT-OSS 20B returns `gpt-oss-20b`, an id that `Azion.AI.run` refuses as input. Do not reuse the `model` field of a response as an id. + A chat model returns a `chat.completion` object: | Field | Type | Carries | @@ -144,23 +266,28 @@ A chat model returns a `chat.completion` object: | `id` | string | The identifier of this completion. | | `object` | string | `chat.completion`. | | `created` | integer | When the completion was created. | -| `model` | string | The id of the model that answered. | +| `model` | string | The internal id of the model that answered. | | `choices` | array | The generated responses, one entry per response requested through `n`. | | `choices[].index` | integer | The position of the entry in `choices`. | | `choices[].message` | object | The generated message. | | `choices[].message.role` | string | `assistant`. | -| `choices[].message.content` | string | The generated text. This is where a chat response is read from. | -| `choices[].message.reasoning_content` | string | The reasoning the model returned, where it returns any. | -| `choices[].message.tool_calls` | array | The tools the model chose to call, on a model whose Tool calling capability is Yes. | -| `choices[].finish_reason` | string | Why generation stopped, such as `stop` or `tool_calls`. | -| `choices[].stop_reason` | string | The stop condition that ended generation. | -| `choices[].logprobs` | object | The log probabilities, where the model returns them. | +| `choices[].message.content` | string, or null | The generated text. This is where a chat response is read from. | +| `choices[].message.reasoning_content` | string, or null | The reasoning the model returned, where it returns any. | +| `choices[].message.reasoning` | string, or null | The same reasoning, on Qwen3 30B and GPT-OSS 20B. | +| `choices[].message.tool_calls` | array | The tools the model chose to call. | +| `choices[].finish_reason` | string | Why generation stopped, such as `stop`, `length`, or `tool_calls`. | +| `choices[].stop_reason` | string, integer, or null | The stop condition that ended generation. | +| `choices[].logprobs` | object, or null | The log probabilities, when the request sets `logprobs`. | | `usage` | object | The tokens the request and the response consumed. | | `usage.prompt_tokens` | integer | The tokens read from the request. | | `usage.completion_tokens` | integer | The tokens generated in the response. | | `usage.total_tokens` | integer | The two added together. | -| `usage.prompt_tokens_details` | object | The breakdown of the prompt tokens. | -| `prompt_logprobs` | object | The log probabilities of the prompt, where the model returns them. | +| `usage.prompt_tokens_details` | object, or null | The breakdown of the prompt tokens. | +| `prompt_logprobs` | object, or null | The log probabilities of the prompt, where the model returns them. | + +`content` is `null` when the message carries `tool_calls`. It can also be `null` on GPT-OSS 20B, which fills `reasoning_content` first: with a small `max_tokens`, the reasoning can use the whole budget, and `finish_reason` is `length`. + +A chat response also carries fields this table does not describe: `refusal`, `annotations`, `audio`, and `function_call` in the message; `token_ids` in each choice on Qwen3 30B; and `service_tier`, `system_fingerprint`, `prompt_token_ids`, and `kv_transfer_params` at the top level. An embedding model returns a `list` object whose `data` array holds one embedding per input: @@ -169,38 +296,63 @@ An embedding model returns a `list` object whose `data` array holds one embeddin | `id` | string | The identifier of this response. | | `object` | string | `list`. | | `created` | integer | When the response was created. | -| `model` | string | The id of the model that answered. | +| `model` | string | The internal id of the model that answered. | | `data` | array | The embeddings, one entry per input. | | `data[].index` | integer | The position of the entry in `data`. | | `data[].object` | string | `embedding`. | -| `data[].embedding` | array of numbers | The vector, of the size `dimensions` selected. | -| `usage` | object | The tokens the request consumed. | +| `data[].embedding` | array of numbers, or string | The vector, or its base64 string when `encoding_format` is `base64`. | +| `usage` | object | The tokens the request consumed: `prompt_tokens`, `total_tokens`, `completion_tokens`, and `prompt_tokens_details`. | A reranking model returns the ranked results: | Field | Type | Carries | | --- | --- | --- | | `id` | string | The identifier of this response. | -| `model` | string | The id of the model that answered. | +| `model` | string | The internal id of the model that answered. | | `results` | array | The ranked entries, highest score first. | -| `results[].index` | integer | The position the entry held in the input collection. | +| `results[].index` | integer | The position the entry held in `documents`. | | `results[].document` | object | The entry that was ranked. | | `results[].document.text` | string | The text of that entry. | +| `results[].document.multi_modal` | null | A field the reranker returns with no value. | | `results[].relevance_score` | number | How relevant the model judged the entry. | | `usage.total_tokens` | integer | The tokens the request consumed. | --- +## Errors + +`Azion.AI.run` rejects with an error object that carries `name` and `message` only, with no `code` and no `status` field. Read `message` to tell the cases apart: + +| Error | Cause | What to do | +| --- | --- | --- | +| `AIError: model not found or not allowed` | The model id does not exist, or the account has no access to AI Inference. The message does not say which. | Copy the id from the model page, or list the ids with `Azion.AI.models()`. For access, refer to [AI Inference limits](/en/documentation/platform/ai-inference/limits/). | +| `AIError: validation error: {path: ""}` | The body does not match the model's schema. The model does not run. | Fix the field that `path` names. | +| `Error: Request failed with status ` | The model server refused a request that passed validation. The message carries no reason. | Check the values the model server refuses, listed below. | + +The validation `` is `Required` for a missing field, `WrongType` for a value of the wrong type, with a `detail` such as `The value must be integer`, `Minimum` or `Maximum` for a value past a bound, `Enum` for a value outside a fixed set, or `OneOf` for a message that matches no message object. + +The model server refuses these with status `400`: a prompt longer than the context the model serves, which the message does not name as the cause; `temperature` and `top_p` at `0` with both penalties at `-2`; a `tools` request without `tool_choice` on Qwen2.5 VL AWQ 3B, Qwen2.5 VL AWQ 7B, or Nanonets-OCR-s; a `seed` that is not an integer; an unknown `tool_choice`; and `stream_options` without `stream`. An `image_url` that serves no image fails with status `500`. + +The endpoint of the AI Inference Starter Kit returns its own errors as a JSON body with an `error` field: + +| Status | Body | Cause | +| --- | --- | --- | +| `400` | `{"error":"Request must be a POST request with JSON body"}` | The method is not `POST`, or `Content-Type` is not exactly `application/json`. | +| `400` | `{"error":"Invalid JSON in request body"}` | The body does not parse as JSON. | +| `400` | `{"error":"Missing 'model' field in request body"}` | The body has no `model` field. | +| `400` | `{"error":" not found or not allowed"}` | The binding rejected the id with `model not found or not allowed`. | +| `400` | `{"error":"Invalid input for "}` | The binding rejected the body with a `validation error`. | +| `500` | `{"error":"AI internal error"}` | Any other error, such as a refusal from the model server. | + +--- + ## Related resources - The binding a function calls, with its parameters and return value. - What runs a model and where the request on this page is served from. - Deploy an application and send a first request to a model. + The binding a Function calls, with its parameters and return value. The id to pass, and the capabilities each model states for itself. - The conditions under which Azion terminates or deprovisions a model. - The runtime that holds the binding and the limits that bound a call. - How AI Inference consumption is measured and charged. + What runs a model and where the request on this page is served from. + Who can call a model on each plan, and when Azion terminates or deprovisions one. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/models.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/models.mdx index 3f4a6173e8..45071c0ca7 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/models.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/models.mdx @@ -12,29 +12,46 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -[AI Inference](/en/documentation/platform/ai-inference/) runs the models on this page. You select a model by its id, a string the model answers to, rather than by the name it is listed under. Each row of the catalog carries that id next to the capabilities the model page states for itself. For the request body the id travels in, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). +[AI Inference](/en/documentation/platform/ai-inference/) runs the models on this page. You select a model by its id, a string the model answers to, rather than by the name it is listed under. Each row of the catalog carries that id next to the capabilities of the model. For the request body the id travels in, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). ## Model catalog -Each row is one model, and the model name links the model page, which carries a request example. The Category column reads LLM for a large language model, VLM for a vision language model, Embedding, or Reranker. A dash means the model page states no value for that capability. +Each row is one model, and the model name links the model page, which carries a request example. The Category column takes one of four values: + +- **LLM**: a large language model, which reads text and returns text. +- **VLM**: a vision language model, which reads text and images and returns text. +- **Embedding**: a model that returns a vector that represents the input text. +- **Reranker**: a model that scores a set of documents against a query. + +A dash means the model page states no value for that capability. | Model | Category | Input | Context length | Size | Tool calling | LoRA | Model id | | --- | --- | --- | --- | --- | --- | --- | --- | | [Mistral 3 Small (24B AWQ)](/en/documentation/platform/ai-inference/mistral-3-small/) | LLM | Text | 32k tokens | 24B parameters | Yes | No | `casperhansen-mistral-small-24b-instruct-2501-awq` | | [BAAI/bge-reranker-v2-m3](/en/documentation/platform/ai-inference/baai-bge-reranker-v2-m3/) | Reranker | Text | 8k tokens | 568M parameters | — | No | `baai-bge-reranker-v2-m3` | | [InternVL3](/en/documentation/platform/ai-inference/internvl3/) | VLM | Text and image | 16k tokens | 1B parameters | No | No | `opengvlab-internvl3-1b-instruct` | -| [Qwen2.5 VL AWQ 3B](/en/documentation/platform/ai-inference/qwen-2-5-vl-3b/) | VLM | Text and image | 32k tokens | 3B parameters | Yes | Yes | `qwen-qwen25-vl-3b-instruct-awq` | -| [Qwen2.5 VL AWQ 7B](/en/documentation/platform/ai-inference/qwen-2-5-vl-7b/) | VLM | Text and image | 32k tokens | 7B parameters | Yes | Yes | `qwen-qwen25-vl-7b-instruct-awq` | -| [Qwen3 30B A3B Instruct 2507 FP8](/en/documentation/platform/ai-inference/qwen3-30ba3b/) | LLM | Text | 64k tokens | 30B parameters | Yes | Yes | `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` | +| [Qwen2.5 VL AWQ 3B](/en/documentation/platform/ai-inference/qwen-2-5-vl-3b/) | VLM | Text and image | 32k tokens | 3B parameters | Named tool only | Yes | `qwen-qwen25-vl-3b-instruct-awq` | +| [Qwen2.5 VL AWQ 7B](/en/documentation/platform/ai-inference/qwen-2-5-vl-7b/) | VLM | Text and image | 32k tokens | 7B parameters | Named tool only | Yes | `qwen-qwen25-vl-7b-instruct-awq` | +| [Qwen3 30B A3B Instruct 2507 FP8](/en/documentation/platform/ai-inference/qwen3-30ba3b/) | LLM | Text | 64k tokens | 30.5B parameters | Yes | Yes | `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` | | [Qwen3 Embedding 4B](/en/documentation/platform/ai-inference/qwen3-embedding-4b/) | Embedding | Text | 32k tokens | 4B parameters | — | — | `Qwen/Qwen3-Embedding-4B` | -| [Nanonets-OCR-s](/en/documentation/platform/ai-inference/nanonets-ocr-s/) | — | Text and image | 32k tokens | — | — | — | `nanonets/Nanonets-OCR-s` | -| [GPT-OSS 20B](/en/documentation/platform/ai-inference/gpt-oss-20b/) | LLM | Text | 131k tokens | 20B parameters | Yes | No | `gpt-oss-20b` | +| [Nanonets-OCR-s](/en/documentation/platform/ai-inference/nanonets-ocr-s/) | — | Text and image | 32k tokens | — | No | — | `nanonets/Nanonets-OCR-s` | +| [GPT-OSS 20B](/en/documentation/platform/ai-inference/gpt-oss-20b/) | LLM | Text | 131k tokens | 21B parameters | Yes | No | `openai/gpt-oss-20b` | + +Tool calling reads Yes when a request that carries a `tools` array returns `tool_calls`, with the model choosing the tool. Qwen2.5 VL AWQ 3B, Qwen2.5 VL AWQ 7B, and Nanonets-OCR-s reject that request with `Request failed with status 400`. The two Qwen2.5 VL models return `tool_calls` when `tool_choice` names the tool, with `finish_reason` set to `stop` and `content` set to an empty string. --- ## Model ids -A model id is the string that selects the model: the first argument to `Azion.AI.run` inside a [function](/en/documentation/platform/functions/), and the `model` field of an HTTP request body. The ids do not share one form. Some are lowercase and hyphenated with no slash, and others carry a publisher prefix and mixed capitalization. Copy an id from the table character for character rather than deriving it from the model name. +A model id is the string that selects the model: the first argument to `Azion.AI.run` inside a [Function](/en/documentation/platform/functions/), and the `model` field of a request body sent to the HTTP endpoint of the [AI Inference Starter Kit](/en/documentation/guides/application-development/frameworks/ai-inference-starter-kit/). A model can answer to two forms of its id: a repository form, such as `Qwen/Qwen2.5-VL-3B-Instruct-AWQ`, and a lowercase form with hyphens, such as `qwen-qwen25-vl-3b-instruct-awq`. Both forms select the same model. The lowercase form does not follow from the repository form by a simple rule, so copy an id from the table character for character rather than deriving it from the model name. + +To list the ids your account can call, in both forms, call `Azion.AI.models()` from a Function. It returns a promise that resolves to an array of id strings: + +```ts +const modelIds = await Azion.AI.models() +``` + +The `model` field of a response carries the account's internal id for the model, which can differ from the id the request sent. A request to `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` returns `qwen-qwen3-30b-a3b-instruct-2507-fp8`, and GPT-OSS 20B returns `gpt-oss-20b`, an id that `Azion.AI.run` refuses as input. Do not reuse the `model` field of a response as an id. --- @@ -43,10 +60,8 @@ A model id is the string that selects the model: the first argument to `Azion.AI The request body an id travels in, and the two interfaces that carry it. - The product that runs the models in this catalog. The extension of AI Inference behind the LoRA column. Where the vectors an embedding model returns are stored and queried. - The product whose runtime binding takes the ids in this table. Where model id, LoRA Fine-Tune, and the rest of the AI Inference vocabulary are defined. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/quickstart.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/quickstart.mdx index ff954aa98d..1f8c4e101c 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/quickstart.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/quickstart.mdx @@ -2,7 +2,7 @@ title: AI Inference quickstart description: >- Deploy the AI Inference Starter Kit template and post a first chat request to - a model on your own application domain. + a model on the domain the template creates. meta_tags: 'AI Inference, quickstart, AI Inference Starter Kit, first inference, chat completions, Workload Domain, Azion.AI.run' namespace: docs_edge_ai_quickstart permalink: /documentation/platform/ai-inference/quickstart/ @@ -14,24 +14,24 @@ import DocStep from '@aziontech/webkit/doc-step' This guide instructs you through getting your first response from an AI Inference model. -- Deploy the AI Inference Starter Kit template as an application. -- Open the Workload Domain that the deployment assigns to the workload serving the application. +- Deploy the AI Inference Starter Kit template as an Application. +- Open the workload domain of the Workload the template creates. - Post a chat request to a model and read the answer it returns. -- Change the model that the function calls. +- Call another model by changing one field of the request. -The deployment creates three objects, and one request passes through all of them: +The template creates these entities, and one request passes through them in this order: -1. The **Workload Domain** is the address a client posts to. Azion assigns it to the workload that serves the application, in the form `xxxxxxxxxx.map.azionedge.net`. -2. The **application** receives the request on that domain, applies its policies, and calls the function. -3. The **function** holds the code that calls the model with `Azion.AI.run`, and it returns the model response. +1. A **Workload**, with its deployment. The Workload receives the request on its workload domain, in the form `xxxxxxxxxx.map.azionedge.net`, and its deployment sets the Application. +2. An **Application**, with Cache, Functions, and Application Accelerator turned on. Its one rule runs the Function on every path, through the Function Instance, and bypasses the cache. +3. A **Function** and its **Function Instance**, which binds the Function to the Application. The Function reads the model id from the `model` field of the request body, passes the whole body to `Azion.AI.run`, and returns the model response. -You write no code to reach a first response. The template creates all three objects, and the function it installs already serves an OpenAI-compatible endpoint. +The Application and the Function take the name you enter, followed by a "(Build at …)" suffix. You write no code to reach a first response: the Function the template installs already serves an OpenAI-compatible endpoint. --- ## Prerequisites -This guide requires an Azion account. The template creates every other object the guide uses: the application, the function, and the domain. +This guide requires an Azion account with access to AI Inference. On the Hobby and Pro plans, access is available upon request, subject to approval. For the access each plan gives, refer to [AI Inference limits](/en/documentation/platform/ai-inference/limits/). The template creates every other entity the guide uses. --- @@ -41,48 +41,52 @@ This guide requires an Azion account. The template creates every other object th The template uses [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), [Functions](/en/documentation/platform/functions/), and [AI Inference](/en/documentation/platform/ai-inference/). These products can generate usage-related costs. For the rates, refer to [Pricing](/en/documentation/fundamentals/pricing/#ai-inference). ::: -To create the application that answers model requests: +To create the Application that answers model requests: - + Access [Azion Console](https://console.azion.com/) and select **+ Create**. - - + - Enter a name for the application. For example: `ai-inference-quickstart`. + Under **Start from Template**, select **AI Inference Starter Kit**. + + + + + In **Application Name**, enter a name made of letters, numbers, and underscores. For example: `ai_inference_quickstart`. A hyphen is refused with "The use of accents and/or special characters is not allowed." -A window shows the deployment logs while the deployment runs. When it finishes, the page shows information about the application and the options to continue. +A window shows the deployment logs while the deployment runs. When it finishes, the page shows the domain under **Visit site**, the **Add custom domain** option, the **Deployment logs**, and **Resources created**, which lists the Workload and the Application. -The application exists, with a function that calls a model and a domain that serves it. +The Workload, the Application, and the Function exist, and the Function answers every request that reaches the domain. --- -## Open the application domain +## Open the workload domain -Azion assigns a Workload Domain to the workload that serves the application during the deployment. The domain has the form `xxxxxxxxxx.map.azionedge.net`, and it is the address a client sends a model request to. The deployment page shows the link to the application. +The domain under **Visit site** is the workload domain of the Workload, in the form `xxxxxxxxxx.map.azionedge.net`. It is the address a client sends a model request to. -To see the application in the browser, select the link. +To check that the domain answers, select **Visit site**. :::note -The application takes a few minutes to propagate to Azion's data centers. Until it propagates, the domain does not resolve and the page does not open. Wait a few minutes, then select the link again. +The deployment takes several minutes to propagate to Azion's data centers. Until it propagates, the domain answers with Azion's placeholder `404`. Wait a few minutes, then select **Visit site** again. ::: -The domain resolves, and the application answers on it. Copy the domain: the model request goes to it. +The page shows `{"error":"Request must be a POST request with JSON body"}`. That answer comes from the Function, which accepts only a `POST` request with a JSON body. Copy the domain: the model request goes to it. --- ## Send a request to the model -The application serves an OpenAI-compatible endpoint at `/v1/chat/completions` on its domain. The request body names the model in its `model` field and carries the conversation in `messages`. +The Function answers on any path of the domain, and `/v1/chat/completions` is the path OpenAI clients use. The request body names the model in its `model` field and carries the conversation in `messages`. The `Content-Type` header must be exactly `application/json`. -The function the template installs calls `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`. To send a chat request to it, replace `` with the domain of your application and run: +To send a chat request to Qwen3 30B A3B Instruct 2507 FP8, replace `` with the domain you copied and run: ```bash curl -X POST https:///v1/chat/completions \ @@ -100,85 +104,79 @@ curl -X POST https:///v1/chat/completions \ }' ``` -The model answers with one entry in `choices`, and the generated text sits at `choices[0].message.content`: +The model answers with one entry in `choices`, and the generated text sits at `choices[0].message.content`. The response below shortens that text: ```json { - "id": "chatcmpl-example", + "id": "chatcmpl-784835050db84a289185baceb0ccbc8e", "object": "chat.completion", - "created": 1767268800, - "model": "Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", + "created": 1794444653, + "model": "qwen-qwen3-30b-a3b-instruct-2507-fp8", "choices": [ { "index": 0, "message": { "role": "assistant", - "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", - "tool_calls": [] + "content": "There are 44 sovereign countries in Europe, each with its own capital city. Here is a list of all the European capitals:...", + "refusal": null, + "annotations": null, + "audio": null, + "function_call": null, + "tool_calls": [], + "reasoning": null, + "reasoning_content": null }, "logprobs": null, "finish_reason": "stop", - "stop_reason": null + "stop_reason": null, + "token_ids": null } ], + "service_tier": null, + "system_fingerprint": null, "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 24, + "total_tokens": 620, + "completion_tokens": 596, "prompt_tokens_details": null }, - "prompt_logprobs": null + "prompt_logprobs": null, + "prompt_token_ids": null, + "kv_transfer_params": null } ``` -You have your first model response, served by your own application. - -Azion issues no credential for this request, and the endpoint carries no Azion authentication. When you add authentication to your application, include the header it requires, for example `-H "Authorization: Bearer [TOKEN VALUE]"`. For every field a request body accepts, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). - ---- - -## (Optional) Change the model the function calls - -The function that the template deployed holds the call to the model, and the first argument of `Azion.AI.run` is the model id. The function page carries three tabs: +The `model` field carries the account's internal id for the model, `qwen-qwen3-30b-a3b-instruct-2507-fp8`, which differs from the id the request sent. -- **Main Settings** renames the function and changes its basic settings. -- **Code** holds the function code. -- **Arguments** defines the arguments the function uses. +You have your first model response, served by your own Application. -To call a different model: +If the account has no access to AI Inference, or the model id is wrong, the endpoint answers `400` with `{"error":" not found or not allowed"}`. For every error the endpoint returns, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/#errors). - - +The template configures no authentication in front of the endpoint, so any client that reaches the domain can call a model. When you add authentication to your Application, include the header it requires, for example `-H "Authorization: Bearer [TOKEN VALUE]"`. For every field a request body accepts, refer to [Model invocation](/en/documentation/platform/ai-inference/model-invocation/). - Access [Azion Console](https://console.azion.com/) > **Functions**. +--- - - +## (Optional) Call another model - Select the function that carries the same name as the application. +The Function reads the model id from the request, so calling another model changes only the `model` field of the body. The Function code needs no change. Model ids differ in form between models, so copy the id from the model's own page in [AI models](/en/documentation/platform/ai-inference/models/). - - +To send a chat request to Qwen2.5 VL AWQ 3B, run: - In the **Code** tab, change the first argument of `Azion.AI.run`. The call has this form: - - ```ts - const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { - "stream": true, +```bash +curl -X POST https:///v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "qwen-qwen25-vl-3b-instruct-awq", + "max_tokens": 16, "messages": [ - { "role": "system", "content": "You are a helpful assistant." }, - { "role": "user", "content": "Name the European capitals." } + { "role": "user", "content": "Name one European capital." } ] - }) - return modelResponse - ``` + }' +``` - - - +The response carries `"model": "qwen-qwen25-vl-3b-instruct-awq"`, and `choices[0].message.content` holds the answer of that model, such as `Paris, France is a European capital.` -The function calls the model whose id is saved in the **Code** tab. Model ids differ in form between models, so copy the id from the model's own page in [AI models](/en/documentation/platform/ai-inference/models/). +The same Function answered both requests. Its code is in the **Code** tab of the Function, which the **Functions** item of the Console menu opens. --- @@ -188,7 +186,7 @@ The function calls the model whose id is saved in the **Code** tab. Model ids di - - - + + + diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/troubleshooting.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/troubleshooting.mdx new file mode 100644 index 0000000000..669ac14606 --- /dev/null +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/ai-inference/troubleshooting.mdx @@ -0,0 +1,232 @@ +--- +title: Troubleshoot AI Inference +description: Find the cause of a refused model call, an answer that differs from the request, and an error from the AI Inference Starter Kit endpoint. +meta_tags: 'ai inference, troubleshooting, errors, azion.ai.run, model not found or not allowed, validation error, request failed, starter kit, endpoint' +namespace: documentation_products_ai_inference_troubleshooting +permalink: /documentation/platform/ai-inference/troubleshooting/ +--- + +import FrameBox from '@aziontech/webkit/frame-box' +import ItemList from '@aziontech/webkit/item-list' +import DocItem from '@aziontech/webkit/doc-item' + +This page covers the symptoms of a model call to [AI Inference](/en/documentation/platform/ai-inference/), made by a Function with `Azion.AI.run` or sent to the endpoint of the AI Inference Starter Kit. A quoted error from the binding is the `message` of the error that `Azion.AI.run` throws. A quoted error from the endpoint is the `error` field of its JSON response. + +--- + +## A model call fails with model not found or not allowed + +`Azion.AI.run` throws this error, and the model does not run: + +```text +AIError: model not found or not allowed +``` + +The model id does not exist, or the account has no access to AI Inference. The message does not say which. A `model` value copied from an earlier response can also fail, because a response carries the account's internal id, which the binding can refuse as input. + +- **Copy the id from the model page**: each page in [AI models](/en/documentation/platform/ai-inference/models/#model-ids) states an id that answers. +- **List the ids the account can call**: `Azion.AI.models()` returns them, as [List models](/en/documentation/devtools/runtime/api-reference/ai/#list-models) shows. +- **Check the access of the plan**: on the Hobby and Pro plans, AI Inference is available upon request, per [Access by plan](/en/documentation/platform/ai-inference/limits/#access-by-plan). + +With an id from that list, the call returns the model response. + +--- + +## A model call fails with a validation error + +`Azion.AI.run` throws an error that names a type and a field, and the model does not run: + +```text +AIError: validation error: Required { + path: "/query", +} +``` + +The request body does not match the schema of the model. `Required` marks a missing field, `WrongType` a value of the wrong type, `Minimum` or `Maximum` a value past a bound, `Enum` a value outside a fixed set, and `OneOf` a message that matches no message object. + +- **Fix the field that path names**: [Request fields](/en/documentation/platform/ai-inference/model-invocation/#request-fields) lists each field with its type and bounds. +- **Use query and documents on the reranker**: the BAAI reranker refuses the `text_1` and `text_2` pair with `Required`, per [Reranking requests](/en/documentation/platform/ai-inference/model-invocation/#reranking-requests). +- **Pick a listed width for dimensions**: Qwen3 Embedding 4B refuses a value outside its list with `Enum`, per [Embedding requests](/en/documentation/platform/ai-inference/model-invocation/#embedding-requests). + +Once the body matches the schema, the call returns the model response. + +--- + +## A model call fails with Request failed with status 400 + +`Azion.AI.run` throws an error that carries a status and no reason: + +```text +Error: Request failed with status 400 +``` + +The model server refused a request that passed validation. The causes observed are a `tools` request without `tool_choice` on Qwen2.5 VL AWQ 3B, Qwen2.5 VL AWQ 7B, or Nanonets-OCR-s, a prompt longer than the context the model serves, `stream_options` without `stream`, an unknown `tool_choice`, a `seed` that is not an integer, and `temperature` and `top_p` at `0` with both penalties at `-2`. + +- **Name the tool on the Qwen2.5 VL models**: a tool named in `tool_choice` returns `tool_calls`, as [Tool calling](/en/documentation/platform/ai-inference/qwen-2-5-vl-3b/#tool-calling) shows. Nanonets-OCR-s takes no tools. +- **Shorten the prompt**: [AI models](/en/documentation/platform/ai-inference/models/) states the context length of each model. +- **Check the values against the list**: [Errors](/en/documentation/platform/ai-inference/model-invocation/#errors) lists every request the model server refuses. + +After the change, the call returns the model response. + +--- + +## An image request fails with Request failed with status 500 + +A request with an `image_url` part throws this error: + +```text +Error: Request failed with status 500 +``` + +The URL in `image_url.url` does not serve an image, so the model has nothing to read. + +- **Use a URL that serves an image**: an `https` URL that returns the image, or a `data:` URL that carries the image in base64, per [Message objects](/en/documentation/platform/ai-inference/model-invocation/#message-objects). + +With a URL that serves an image, the model answers in text. + +--- + +## GPT-OSS 20B returns no content + +A response from GPT-OSS 20B carries `content` set to `null` and `finish_reason` set to `length`. + +The model reasons before it answers, and the reasoning counts against `max_tokens`. With a small `max_tokens`, the reasoning uses the whole budget, and no answer text remains. The reasoning itself is in `reasoning_content`. + +- **Raise max_tokens**: leave room for the reasoning and the answer, as [Chat completion](/en/documentation/platform/ai-inference/gpt-oss-20b/#chat-completion) shows. + +With room for both, `content` carries the answer and `finish_reason` is `stop`. + +--- + +## An embedding has 2560 values instead of 4096 + +A request to Qwen3 Embedding 4B with `dimensions` set to `4096` returns a vector of 2560 values, which does not match a vector column declared for 4096 values. + +The model accepts `4096`, but its largest vector has 2560 values. A request without `dimensions` also returns 2560 values. + +- **Ask for a width the model returns**: `256`, `512`, `1024`, or `2048` return that width, per [Embedding](/en/documentation/platform/ai-inference/qwen3-embedding-4b/#embedding). +- **Size the column for 2560 values**: when the request asks for `4096` or for no width, declare the vector column with 2560 values. + +The vector and the column then have the same width. + +--- + +## A request field has no effect + +A field in the request body changes nothing in the response, and no error is returned. + +The binding accepts a field that the model does not know and ignores it, so a misspelled field name passes silently. A `model` field in the body is ignored as well: the first argument of `Azion.AI.run` decides the model. + +- **Spell the field as the reference lists it**: [Request fields](/en/documentation/platform/ai-inference/model-invocation/#request-fields) gives each name. +- **Pass the model id as the first argument**: change the first argument of `Azion.AI.run` to call another model. + +With the field spelled as listed, the response reflects it. + +--- + +## Azion.AI is undefined when the Function runs locally + +Under `azion dev`, a call to `Azion.AI.run` throws this error: + +```text +TypeError: Cannot read properties of undefined (reading 'run') +``` + +`Azion.AI` exists only in a deployed Function. Under `azion dev`, it is `undefined`, per the [AI Inference API](/en/documentation/devtools/runtime/api-reference/ai/). + +- **Test model calls on a deployed Function**: deploy the Function, then send the request to its domain. + +On a deployed Function, the call returns the model response. + +--- + +## The endpoint answers Request must be a POST request with JSON body + +The endpoint of the AI Inference Starter Kit answers `400` with this body: + +```json +{"error":"Request must be a POST request with JSON body"} +``` + +The Function the template installs accepts only a `POST` request whose `Content-Type` header is exactly `application/json`. A browser that opens the domain sends a `GET`, and a client that adds `; charset=utf-8` to the header is refused too. + +- **Send a POST request**: the [quickstart](/en/documentation/platform/ai-inference/quickstart/#send-a-request-to-the-model) shows one with `curl`. +- **Send the header with no parameter**: set `Content-Type` to `application/json`. + +The endpoint then returns the model response. + +--- + +## The endpoint answers Missing model field or Invalid JSON + +The endpoint of the AI Inference Starter Kit answers `400` with one of these bodies: + +```json +{"error":"Missing 'model' field in request body"} +{"error":"Invalid JSON in request body"} +``` + +The Function the template installs reads the model id from the `model` field of the body. A body without `model`, or a body that does not parse as JSON, stops before the model call. + +- **Add the model field**: set `model` to an id from [AI models](/en/documentation/platform/ai-inference/models/). +- **Send valid JSON**: check the quoting of the body your client sends. + +The endpoint then returns the model response. + +--- + +## The endpoint answers AI internal error + +The endpoint of the AI Inference Starter Kit answers `500` with this body: + +```json +{"error":"AI internal error"} +``` + +The binding threw an error other than `model not found or not allowed` or a validation error, such as a refusal from the model server. The body does not carry that error, but the Function the template installs writes it to the console. + +- **Read the console line of the request**: the [Functions Console](/en/documentation/platform/real-time-events/data-sources/#functions-console) data source of Real-Time Events carries the lines a Function writes, including the error name and message. +- **Match the message to its cause**: the entries above cover each message observed. + +The console line names the refusal, and the fix for that message applies. + +--- + +## The endpoint answers 404 right after the deployment + +Right after you deploy the AI Inference Starter Kit, the domain under **Visit site** answers `404` with Azion's placeholder page. + +The deployment has not propagated to Azion's data centers yet. Propagation takes several minutes. + +- **Repeat the request after several minutes**: as [Open the workload domain](/en/documentation/platform/ai-inference/quickstart/#open-the-workload-domain) describes. + +Once the deployment propagates, the domain answers with the Function's response. + +--- + +## Application Name is refused when you deploy the template + +When you deploy the AI Inference Starter Kit, the **Application Name** field shows this message: + +```text +The use of accents and/or special characters is not allowed. +``` + +The field accepts letters, numbers, and underscores only, so a hyphen is refused. + +- **Use underscores**: enter a name such as `ai_inference_starter_kit`, the default. + +The **Deploy** button then deploys the template. + +--- + +## Related resources + + + + Every request field, the response fields, and the errors of the binding and of the endpoint. + The id, context length, and capabilities of each model. + Access by plan, and when Azion terminates or deprovisions a model. + Deploy the template and send a first request to a model. + + diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/deploy/edge-orchestrator/edge-services.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/deploy/edge-orchestrator/edge-services.mdx index c067d93512..7ab36b7cd2 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/deploy/edge-orchestrator/edge-services.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/deploy/edge-orchestrator/edge-services.mdx @@ -24,9 +24,9 @@ You can configure the install, uninstall, and reload triggers and define the dep ## How it works -By using Azion as your edge platform, you can create and customize services to run on private and hybrid edge networks. Azion **Edge Services** operates using triggers to install, uninstall, and reload. It defines dependencies between resources and natively implements a set of functions for Azion products, such as **Applications**, **Firewall**, and **Functions**, using **Azion Cells** technology from Azion as its basis. +By using Azion as your edge platform, you can create and customize services to run on private and hybrid edge networks. Azion **Edge Services** operates using triggers to install, uninstall, and reload. It defines dependencies between resources and natively implements a set of functions for Azion products, such as **Applications**, **Firewall**, and **Functions**. -This way, you can build applications for a wide variety of uses, such as hosting other applications, implementing AI, VR applications, and many others. To do so, you must activate Azion Cells and define the **Edge Nodes** that should host certain applications, all controlled by the Azion dashboard or APIs, in a centralized interface, and with different access controls. +This way, you can build applications for a wide variety of uses, such as hosting other applications, implementing AI, VR applications, and many others. To do so, you define the **Edge Nodes** that should host certain applications, all controlled by the Azion dashboard or APIs, in a centralized interface, and with different access controls. --- diff --git a/apps/docs/src/content/docs/en/pages/use-cases/build-and-run-ai-workloads/govern-access-to-multiple-ai-models.mdx b/apps/docs/src/content/docs/en/pages/use-cases/build-and-run-ai-workloads/govern-access-to-multiple-ai-models.mdx index 6bb135e2c1..bb4350b70c 100644 --- a/apps/docs/src/content/docs/en/pages/use-cases/build-and-run-ai-workloads/govern-access-to-multiple-ai-models.mdx +++ b/apps/docs/src/content/docs/en/pages/use-cases/build-and-run-ai-workloads/govern-access-to-multiple-ai-models.mdx @@ -103,7 +103,7 @@ This section explains how the gateway function applies the policy, how team reco The gateway is one function. Every decision it applies is in the code, so a policy change is a code change that every team gets at once. -- **Teams send an alias, not a model id.** `general` routes to `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` on AI Inference, and `long-context` to `gpt-oss-20b`, whose 131k-token context is the longest among the models AI Inference runs. Both fall back to the provider. An alias lets the platform team change the model behind it without a change in any team's code. The gateway calls an AI Inference route as [Call a model on AI Inference from a function](/en/documentation/guides/ai/inference/call-a-model-on-ai-inference-from-a-function/) describes, with these values: the route's model id, and the team's request body with `stream` set to `false`. +- **Teams send an alias, not a model id.** `general` routes to `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` on AI Inference, and `long-context` to `openai/gpt-oss-20b`, whose 131k-token context is the longest among the models AI Inference runs. Both fall back to the provider. An alias lets the platform team change the model behind it without a change in any team's code. The gateway calls an AI Inference route as [Call a model on AI Inference from a function](/en/documentation/guides/ai/inference/call-a-model-on-ai-inference-from-a-function/) describes, with these values: the route's model id, and the team's request body with `stream` set to `false`. - **The key is stored as a hash.** The record key is `team:` followed by the SHA-256 of the team key, so KV Store never holds a usable key. SHA-256 is one of the digests `crypto.subtle.digest` supports. - **A failed call moves to the next route.** A call that throws, returns no `choices`, answers with an error status, or runs past 30 seconds counts as failed. Thirty seconds bounds how long a team waits on one route before the next one runs, inside the 5-minute wall-clock limit of a function. - **Caching is the caller's decision.** The gateway caches only requests that carry `x-gateway-cache: allow`, because only the team knows whether one answer can stand for every identical prompt. The gateway caches as [Cache a function's response with the Cache API](/en/documentation/guides/application-development/functions-and-runtime/cache-a-function-response-with-the-cache-api/) describes, with the cache `ai-gateway`, the key `https://ai-gateway.cache/`, and `max-age=3600`, one hour. diff --git a/apps/docs/src/content/docs/pt-br/pages/arquiteturas/artificial-intelligence/ai-inference-architecture.mdx b/apps/docs/src/content/docs/pt-br/pages/arquiteturas/artificial-intelligence/ai-inference-architecture.mdx index 3f6a767ff0..4b73a210a0 100644 --- a/apps/docs/src/content/docs/pt-br/pages/arquiteturas/artificial-intelligence/ai-inference-architecture.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/arquiteturas/artificial-intelligence/ai-inference-architecture.mdx @@ -2,7 +2,7 @@ title: Catalog-model inference API description: >- Sirva um endpoint de inferência compatível com OpenAI no domínio da sua - própria aplicação, com uma função que chama o modelo com Azion.AI.run. + própria Application, com uma Function que chama o modelo com Azion.AI.run. meta_tags: 'arquitetura de referência, API de inferência com modelo do catálogo, AI Inference, Azion.AI.run, funções, aplicações, endpoint compatível com OpenAI, endpoint de inferência' namespace: docs_arch_ai_inference permalink: /documentacao/casos-de-uso/construir-e-executar-workloads-de-ai/ai-inference-architecture/ @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Um cliente que chama um modelo precisa de um endereço para o qual enviar a requisição e de um formato de resposta para ler. Esta arquitetura coloca esse endereço em uma aplicação que você implanta: a aplicação é o endpoint de inferência, e o modelo executa atrás dela. Use-a quando seu time já serve uma API HTTP e quer que a inferência seja mais um caminho nela. O domínio é seu, e nenhum servidor de inferência fica em execução. O design implementa o caso de uso [Adicionar funcionalidades de IA a aplicações existentes](/pt-br/documentacao/casos-de-uso/construir-e-executar-workloads-de-ai/adicionar-funcionalidades-de-ia-a-aplicacoes-existentes/). +Um cliente que chama um modelo precisa de um endereço para o qual enviar a requisição e de um formato de resposta para ler. Esta arquitetura coloca esse endereço em uma Application que você implanta: a Application é o endpoint de inferência, e o modelo executa atrás dela. Use-a quando seu time já serve uma API HTTP e quer que a inferência seja mais um caminho nela. O domínio é seu, e nenhum servidor de inferência fica em execução. O design implementa o caso de uso [Adicionar funcionalidades de IA a aplicações existentes](/pt-br/documentacao/casos-de-uso/construir-e-executar-workloads-de-ai/adicionar-funcionalidades-de-ia-a-aplicacoes-existentes/). [Como AI Inference funciona](/pt-br/documentacao/plataforma/ai-inference/como-funciona/) cobre as passagens dentro de uma única chamada. Esta página descreve a forma que você implanta em torno delas. @@ -26,10 +26,12 @@ As setas contínuas levam a requisição, e as setas pontilhadas levam a respost %%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% flowchart TD Client(["Cliente compatível com OpenAI"]) - App["aplicação"] - Fn["função com o prompt e o id do modelo"] + WL["Workload"] + App["Application"] + Fn["Function"] AI["AI Inference"] - Client -->|"1, 2. POST /v1/chat/completions"| App + Client -->|"1. POST /v1/chat/completions"| WL + WL -->|"2. requisição"| App App -->|"3. Run Function"| Fn Fn -->|"4. Azion.AI.run"| AI AI -.->|"5. resposta gerada"| Fn @@ -39,29 +41,29 @@ flowchart TD ### Fluxo de dados -1. Um cliente envia uma requisição compatível com OpenAI para `/v1/chat/completions` no domínio da aplicação. -2. O data center mais próximo recebe a requisição e a entrega à aplicação. -3. A aplicação aplica suas políticas, verifica a autenticação que você configurou e chama a função. -4. A função pré-processa a entrada e chama o modelo com `Azion.AI.run`, que alcança AI Inference através da API do Azion Cells. -5. AI Inference executa o modelo e retorna a resposta gerada à função. -6. A função formata essa resposta e a retorna ao cliente pelo mesmo caminho. +1. Um cliente envia uma requisição compatível com OpenAI para `/v1/chat/completions` em um domínio do Workload. +2. Um data center perto do cliente recebe a requisição, e o deployment do Workload define a Application que a trata. +3. A Application executa as regras dela, incluindo qualquer verificação de autenticação que você acrescentar, e uma regra executa a Function com o behavior _Run Function_. +4. A Function monta o corpo da requisição e chama o modelo com `Azion.AI.run`. +5. AI Inference executa o modelo e retorna a resposta gerada à Function. +6. A Function formata essa resposta e a retorna ao cliente pelo mesmo caminho. -O cliente não sabe nada sobre a Azion. Ele envia JSON para uma URL e lê JSON de volta, como faria com qualquer serviço compatível com OpenAI. Atrás do domínio, uma única execução faz o resto, e a função mantém a requisição aberta até o modelo responder. Nenhuma seta sai em direção a um host de inferência, porque a função não configura nenhuma URL base e não nomeia nenhum host. Ela passa um id de modelo, e Azion faz a chamada. +O cliente não sabe nada sobre a Azion. Ele envia JSON para uma URL e lê JSON de volta, como faria com qualquer serviço compatível com OpenAI. Atrás do domínio, uma única execução faz o resto, e a Function mantém a requisição aberta até o modelo responder. Nenhuma seta sai em direção a um host de inferência, porque a Function não passa nenhuma URL base e não nomeia nenhum host. Ela passa um id de modelo, e Azion faz a chamada. --- ## Componentes -- [Applications](/pt-br/documentacao/plataforma/applications/): recebe a requisição no seu domínio e aplica suas políticas antes que qualquer código seu execute. É o que torna o endpoint seu, porque o domínio, o caminho e a autenticação à frente da função são todos configurados aqui. Azion não emite nenhuma credencial para uma chamada de modelo, então um endpoint sem verificação própria responde a qualquer um que o encontre. +- [Workloads](/pt-br/documentacao/plataforma/workloads/): recebe a requisição nos domínios dele, o workload domain ou um domínio personalizado, e o deployment dele define a Application. O endereço para o qual o cliente envia a requisição pertence ao Workload. +- [Applications](/pt-br/documentacao/plataforma/applications/): executa as regras dela sobre a requisição antes que qualquer código seu execute. O caminho que a Function responde e qualquer autenticação à frente dela são definidos nessas regras. `Azion.AI.run` não recebe nenhuma credencial, então um endpoint sem verificação própria responde a qualquer um que o encontre. - [Functions](/pt-br/documentacao/plataforma/functions/): contém a lógica de inferência e emite a chamada de modelo. Seu código não executa em nenhum outro lugar desta arquitetura, então o prompt, o id do modelo, o contexto recuperado de um armazenamento e qualquer serviço externo de que a chamada precise ficam todos em uma única execução. -- [AI Inference](/pt-br/documentacao/plataforma/ai-inference/): executa o modelo, que é o que remove o servidor de inferência desta arquitetura. Você não carrega nenhum modelo e não dimensiona nenhum cluster, e o id em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/) é o único endereço de que a função precisa. -- [Orchestrator](/pt-br/documentacao/plataforma/orchestrator/): gerencia as requisições para a execução no Azion Cells. `Azion.AI.run` alcança um modelo através da API do Azion Cells, que é a parte do Orchestrator de que esta arquitetura depende. -- **A infraestrutura distribuída da Azion**: executa todas as partes acima. É por isso que esta arquitetura não tem região a escolher. O data center mais próximo do cliente responde a requisição, e você não seleciona nenhum deles. -- [Real-Time Metrics](/pt-br/documentacao/plataforma/real-time-metrics/): reporta o tráfego e a performance da aplicação que serve o endpoint. Uma arquitetura sem servidor de inferência próprio ainda precisa de uma visão do que o endpoint transportou. +- [AI Inference](/pt-br/documentacao/plataforma/ai-inference/): executa o modelo, que é o que remove o servidor de inferência desta arquitetura. Você não carrega nenhum modelo e não dimensiona nenhum cluster, e o id em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/) é o único endereço de que a Function precisa. +- **A infraestrutura distribuída da Azion**: executa todas as partes acima. É por isso que esta arquitetura não tem região a escolher. Um data center perto do cliente responde a requisição, e você não seleciona nenhum deles. +- [Real-Time Metrics](/pt-br/documentacao/plataforma/real-time-metrics/): reporta o tráfego e a performance da Application que serve o endpoint. Uma arquitetura sem servidor de inferência próprio ainda precisa de uma visão do que o endpoint transportou. - [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/): rastreia requisições individuais, dados brutos e logs. Quando uma resposta está errada, a requisição que a produziu é o que você lê aqui. :::note[nota] -Azion Cells é uma funcionalidade avançada que faz parte do Orchestrator. Para ativá-lo, entre em contato com a equipe de vendas da Azion para verificar os requisitos e habilitar o produto na sua conta. +Nos planos Hobby e Pro, AI Inference está disponível sob solicitação, sujeito a aprovação. Para o acesso que cada plano dá, consulte [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). ::: --- @@ -70,7 +72,7 @@ Azion Cells é uma funcionalidade avançada que faz parte do Orchestrator. Para - [Adicionar funcionalidades de IA a aplicações existentes](/pt-br/documentacao/casos-de-uso/construir-e-executar-workloads-de-ai/adicionar-funcionalidades-de-ia-a-aplicacoes-existentes/) - constrói este design de ponta a ponta, com a function de resumo e a rota de API. - [Primeiros passos com AI Inference](/pt-br/documentacao/plataforma/ai-inference/primeiros-passos/) - implanta esta arquitetura e envia uma primeira requisição a um modelo no domínio que ela atribui. -- [Como implementar o template AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) - cria a aplicação, a função e o domínio que esta página descreve, em uma única implantação. +- [Como implementar o template AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) - cria o Workload com o deployment dele, a Application e a Function que esta página descreve, em uma única implantação. - [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) - traz o corpo da requisição que as duas interfaces aceitam e a forma em `curl` para o endpoint HTTP. --- @@ -82,7 +84,7 @@ Azion Cells é uma funcionalidade avançada que faz parte do Orchestrator. Para A cadeia de invocação passagem por passagem, e onde termina a parte da Azion. O id a passar e o que cada modelo aceita. Os tetos que uma chamada de modelo encontra, e quando Azion desprovisiona um modelo. - O armazenamento de onde uma função lê contexto antes de chamar um modelo. + O armazenamento de onde uma Function lê contexto antes de chamar um modelo. As consultas de embeddings que constroem o contexto que um prompt carrega. diff --git a/apps/docs/src/content/docs/pt-br/pages/build/functions/glossario.mdx b/apps/docs/src/content/docs/pt-br/pages/build/functions/glossario.mdx index 5164c748ee..6363c4af7b 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/functions/glossario.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/functions/glossario.mdx @@ -15,7 +15,6 @@ Definições para os termos que a documentação de [Functions](/pt-br/documenta | Args | O objeto JSON que uma [instância de função](/pt-br/documentacao/plataforma/applications/functions-instances/) passa para o contexto de execução da função. Uma instância que define Args substitui por inteiro os Args padrão da função. [Como funciona](/pt-br/documentacao/plataforma/functions/como-funciona/) mostra quais Args a função recebe. | | Azion Bundler | O adaptador de frameworks open source que transforma um projeto de framework em funções que rodam no Azion Runtime. [Como funciona](/pt-br/documentacao/plataforma/functions/como-funciona/) descreve as quatro etapas do build, da detecção do framework ao deploy das funções geradas. | | Azion Runtime | O ambiente que executa o handler de uma função. [Azion Runtime](/pt-br/documentacao/devtools/runtime/) executa JavaScript construído sobre padrões Web. Uma função também chama as [APIs da Azion](/pt-br/documentacao/devtools/runtime/api-reference/azion-runtime-globals/), que acessam variáveis de ambiente, stores e AI Inference. | -| Cell | O ambiente de isolamento dentro do qual uma função roda, baseado em isolates V8. Cada Cell é um contexto de execução leve, sem acesso direto ao sistema operacional subjacente, e é por isso que uma função não consegue ler propriedades do SO, resolver DNS por chamadas nativas de sistema nem abrir sockets de baixo nível. [Compatibilidade com Node.js](/pt-br/documentacao/devtools/runtime/node/) lista o que isso exclui. | | contexto de execução | O parâmetro `ctx` que um handler recebe, depois de `request` e `env`. `ctx.waitUntil(promise)` estende a duração da execução para além do ponto em que o handler retorna. No handler firewall de uma função com build feito pela Azion CLI 4.24.0 ou posterior, `ctx` também carrega `ctx.deny()`, `ctx.drop()`, `ctx.continue()`, `ctx.respondWith()`, `ctx.addRequestHeader()` e `ctx.addResponseHeader()`, que se comportam como os métodos do evento de firewall com o mesmo nome. Uma função com build feito pela Azion CLI 4.23.0 carrega apenas `ctx.waitUntil()`. [Handlers](/pt-br/documentacao/devtools/runtime/api-reference/handlers/) lista todos os parâmetros dos dois handlers. | | editor de código | O editor em Azion Console onde você escreve e edita o código de uma função. O [editor de código](/pt-br/documentacao/plataforma/functions/code-editor/) usa o editor Monaco do VS Code e mostra a saída da função por meio de Preview deployment. | | fase de execução | A etapa do processamento da requisição à qual uma regra de [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) pertence. Request Phase trata o que o usuário enviou e Response Phase trata o que a aplicação retorna. [Como funciona](/pt-br/documentacao/plataforma/functions/como-funciona/) descreve as duas fases e os critérios que acionam uma regra. | diff --git a/apps/docs/src/content/docs/pt-br/pages/casos-de-uso/construir-e-executar-workloads-de-ai/governar-o-acesso-a-multiplos-modelos-de-ia.mdx b/apps/docs/src/content/docs/pt-br/pages/casos-de-uso/construir-e-executar-workloads-de-ai/governar-o-acesso-a-multiplos-modelos-de-ia.mdx index 7ec5eb1593..7cea1bce8a 100644 --- a/apps/docs/src/content/docs/pt-br/pages/casos-de-uso/construir-e-executar-workloads-de-ai/governar-o-acesso-a-multiplos-modelos-de-ia.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/casos-de-uso/construir-e-executar-workloads-de-ai/governar-o-acesso-a-multiplos-modelos-de-ia.mdx @@ -103,7 +103,7 @@ Esta seção explica como a function de gateway aplica a política, como os regi O gateway é uma única function. Cada decisão que ele aplica está no código, então uma mudança de política é uma mudança de código que todas as equipes recebem de uma vez. -- **As equipes enviam um alias, não um id de modelo.** `general` roteia para `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` no AI Inference, e `long-context` para `gpt-oss-20b`, cuja janela de contexto de 131k tokens é a mais longa entre os modelos que o AI Inference executa. Os dois fazem fallback para o provedor. Um alias permite que a equipe de plataforma mude o modelo por trás dele sem mudança no código de nenhuma equipe. O gateway chama uma rota do AI Inference como [Chame um modelo no AI Inference a partir de uma function](/pt-br/documentacao/guias/ai/inferencia/chamar-um-modelo-no-ai-inference-a-partir-de-uma-function/) descreve, com estes valores: o id de modelo da rota e o body da requisição da equipe com `stream` definido como `false`. +- **As equipes enviam um alias, não um id de modelo.** `general` roteia para `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` no AI Inference, e `long-context` para `openai/gpt-oss-20b`, cuja janela de contexto de 131k tokens é a mais longa entre os modelos que o AI Inference executa. Os dois fazem fallback para o provedor. Um alias permite que a equipe de plataforma mude o modelo por trás dele sem mudança no código de nenhuma equipe. O gateway chama uma rota do AI Inference como [Chame um modelo no AI Inference a partir de uma function](/pt-br/documentacao/guias/ai/inferencia/chamar-um-modelo-no-ai-inference-a-partir-de-uma-function/) descreve, com estes valores: o id de modelo da rota e o body da requisição da equipe com `stream` definido como `false`. - **A chave é armazenada como hash.** A key do registro é `team:` seguida do SHA-256 da chave da equipe, então o KV Store nunca guarda uma chave utilizável. SHA-256 é um dos digests que `crypto.subtle.digest` suporta. - **Uma chamada que falha passa para a próxima rota.** Uma chamada que lança uma exceção, não retorna `choices`, responde com um status de erro ou passa de 30 segundos conta como falha. Trinta segundos limitam o tempo que uma equipe espera em uma rota antes que a próxima seja executada, dentro do limite de 5 minutos de tempo de execução de uma function. - **O cache é decisão de quem chama.** O gateway armazena em cache apenas requisições que trazem `x-gateway-cache: allow`, porque só a equipe sabe se uma resposta pode valer para todo prompt idêntico. O gateway armazena em cache como [Armazene em cache a resposta de uma function com a Cache API](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/functions-e-runtime/armazenar-em-cache-a-resposta-de-uma-function-com-a-cache-api/) descreve, com o cache `ai-gateway`, a key `https://ai-gateway.cache/` e `max-age=3600`, uma hora. diff --git a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/api-reference/ai/ai.mdx b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/api-reference/ai/ai.mdx index c280fc8d45..865d7f9bb0 100644 --- a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/api-reference/ai/ai.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/api-reference/ai/ai.mdx @@ -1,7 +1,7 @@ --- title: AI Inference API description: >- - Chame o binding Azion.AI.run dentro de uma função para invocar um modelo do AI + Chame o binding Azion.AI.run dentro de uma Function para invocar um modelo do AI Inference e consulte os parâmetros e o valor de retorno dele. meta_tags: 'AI Inference, Azion.AI.run, runtime binding, model invocation, functions, runtime api' namespace: documentation_runtime_ai @@ -12,22 +12,22 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -`Azion.AI.run` é o binding que uma [função](/pt-br/documentacao/plataforma/functions/) chama para invocar um modelo no [AI Inference](/pt-br/documentacao/plataforma/ai-inference/). Ele é um global do [Azion Runtime](/pt-br/documentacao/devtools/runtime/), então uma função o alcança sem linha de import e sem credencial. O binding carrega o id do modelo e o corpo da requisição. Os campos que esse corpo aceita, e o objeto que o modelo retorna, são os mesmos do endpoint HTTP e estão documentados em [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +`Azion.AI.run` é o binding que uma [Function](/pt-br/documentacao/plataforma/functions/) chama para invocar um modelo no [AI Inference](/pt-br/documentacao/plataforma/ai-inference/). Ele é um global do [Azion Runtime](/pt-br/documentacao/devtools/runtime/), então uma Function o alcança sem linha de import e sem credencial. O binding carrega o id do modelo e o corpo da requisição. Os campos que esse corpo aceita, e o objeto que o modelo retorna, são os mesmos do endpoint HTTP e estão documentados em [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). :::note[nota] -Com `azion dev`, `Azion.AI` é `undefined`, e uma chamada a `Azion.AI.run` lança `TypeError: Cannot read properties of undefined (reading 'run')`. Teste as chamadas de modelo em uma função com deploy feito. +Com `azion dev`, `Azion.AI` é `undefined`, e uma chamada a `Azion.AI.run` lança `TypeError: Cannot read properties of undefined (reading 'run')`. Teste as chamadas de modelo em uma Function publicada. ::: --- ## Parâmetros -`Azion.AI.run` recebe dois parâmetros, e a chamada é assíncrona: a função aguarda a chamada e lê a resposta do modelo no valor resolvido. +`Azion.AI.run` recebe dois parâmetros, e a chamada é assíncrona: a Function aguarda a chamada e lê a resposta do modelo no valor resolvido. | Parâmetro | Tipo | Descrição | | --- | --- | --- | | Id do modelo | string | O id do modelo a ser invocado, na forma que a página do modelo indica. | -| Corpo da requisição | object | Os campos da requisição para a operação. O id do modelo não é repetido dentro dele. | +| Corpo da requisição | object | Os campos da requisição para a operação. Um campo `model` dentro dele é ignorado, assim como um campo que o modelo não conhece. | A forma do id varia entre os modelos, então copie o id da própria página do modelo em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/) em vez de derivá-lo do nome do modelo. @@ -35,7 +35,7 @@ A forma do id varia entre os modelos, então copie o id da própria página do m ## Chame um modelo -Uma chamada a um modelo de chat dentro de uma função: +Uma chamada a um modelo de chat dentro de uma Function: ```ts const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { @@ -52,7 +52,19 @@ return modelResponse ## Valor de retorno -O valor resolvido é o objeto que o modelo retorna. Um modelo de chat retorna um objeto `chat.completion`, um modelo de embedding retorna uma `list` de embeddings e um modelo de reranking retorna os resultados ranqueados. O texto gerado por um modelo de chat fica em `modelResponse?.choices?.[0]?.message?.content`, que é o conteúdo da primeira entrada de `choices`. Todos os campos das três formas estão listados em [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#campos-da-resposta). +O valor resolvido é o objeto que o modelo retorna. Um modelo de chat retorna um objeto `chat.completion`, um modelo de embedding retorna uma `list` de embeddings e um modelo de reranking retorna os resultados ranqueados. Com `stream` definido como `true` no corpo, a chamada resolve num iterador assíncrono de objetos `chat.completion.chunk`, que a Function lê com `for await`. O campo `model` de uma resposta é o id interno do modelo na conta, que pode ser diferente do id que a chamada passou. O texto gerado por um modelo de chat fica em `modelResponse?.choices?.[0]?.message?.content`, que é o conteúdo da primeira entrada de `choices`. Todos os campos das três formas estão listados em [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#campos-da-resposta). + +--- + +## Listar modelos + +`Azion.AI.models()` retorna os ids dos modelos que a sua conta pode chamar, como um array de strings. Ele não recebe argumento, e a chamada é assíncrona: + +```ts +const modelIds = await Azion.AI.models() +``` + +A lista pode trazer duas formas do id de um mesmo modelo, um caminho de repositório e uma forma em minúsculas, e qualquer uma delas seleciona esse modelo em `Azion.AI.run`. --- diff --git a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/compatibilidade/node-polyfills/node.mdx b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/compatibilidade/node-polyfills/node.mdx index 32357351b9..a86c0408c5 100644 --- a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/compatibilidade/node-polyfills/node.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/compatibilidade/node-polyfills/node.mdx @@ -44,9 +44,9 @@ A tabela lista cada módulo com o seu status. Quando existe uma página do módu - 🔴 **Somente para build**: o módulo é incluído para que o build seja concluído sem erros, mas as chamadas à API dele não funcionam em tempo de execução. :::note[nota] -Uma function na Azion executa dentro de uma **Cell**, o ambiente de isolamento que a Azion constrói sobre **V8 isolates**. Uma Cell é um contexto de execução leve e seguro, e o código dentro dela não tem acesso direto ao sistema operacional subjacente. +Uma function na Azion executa dentro de um ambiente de isolamento que a Azion constrói sobre **V8 isolates**. Ele é um contexto de execução leve e seguro, e o código dentro dele não tem acesso direto ao sistema operacional subjacente. -Por segurança multilocatário e integridade da infraestrutura, uma Cell não oferece a uma function: +Por segurança multilocatário e integridade da infraestrutura, o ambiente de isolamento não oferece a uma function: - As propriedades da máquina que a executa. `node:os` e `process` retornam valores fixos no lugar delas, como `linux` para `os.platform()`, uma string vazia para `os.hostname()` e `0` para `os.totalmem()`. - Resolução de DNS por meio de chamadas de sistema nativas (`node:dns`, `node:dns/promises`). diff --git a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/debugging/debugging.mdx b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/debugging/debugging.mdx index b68ad0e06c..c211915e8a 100644 --- a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/debugging/debugging.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/debugging/debugging.mdx @@ -43,7 +43,7 @@ Para ler a saída no terminal com Azion CLI: azion logs cells --tail ``` -O terminal imprime as mensagens de console dos últimos 5 minutos e continua imprimindo as novas. Adicione `--function-id` para restringir a saída a uma função. O subcomando se chama `cells` porque uma função roda dentro de uma Cell, o ambiente de isolamento que a Azion constrói sobre isolates V8. +O terminal imprime as mensagens de console dos últimos 5 minutos e continua imprimindo as novas. Adicione `--function-id` para restringir a saída a uma função. Para enviar a mesma saída a um endpoint que você controla: diff --git a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/glossary.mdx b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/glossary.mdx index 1cdb1e5e33..060a2ccfb8 100644 --- a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/glossary.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/glossary.mdx @@ -8,7 +8,7 @@ namespace: documentation_runtime_glossary permalink: /documentacao/devtools/runtime/glossario/ --- -Este glossário define os termos que o [Azion Runtime](/pt-br/documentacao/devtools/runtime/) usa de forma própria. Para os termos que ele compartilha com Functions, como handler, Cell e tempo de relógio, consulte o [glossário de Functions](/pt-br/documentacao/plataforma/functions/glossario/). +Este glossário define os termos que o [Azion Runtime](/pt-br/documentacao/devtools/runtime/) usa de forma própria. Para os termos que ele compartilha com Functions, como handler e tempo de relógio, consulte o [glossário de Functions](/pt-br/documentacao/plataforma/functions/glossario/). | Termo | Definição | | --- | --- | diff --git a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/how-it-works.mdx b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/how-it-works.mdx index 65a66a6146..45ad5cc2eb 100644 --- a/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/how-it-works.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/how-it-works.mdx @@ -19,9 +19,9 @@ As seções cobrem o modelo de execução, o ciclo de vida da requisição, os f ## Modelo de execução -Cada invocação de uma function roda em um isolate, um contexto de execução do V8. As functions rodam dentro de Cells, um ambiente de isolamento baseado em isolates V8. Cada Cell é um contexto de execução leve, sem acesso direto ao sistema operacional subjacente. O limite de memória de uma function se aplica por isolate, e uma function que excede o seu tempo de CPU é encerrada. Para os valores, consulte [Limites de Functions](/pt-br/documentacao/plataforma/functions/limites/). +Cada invocação de uma function roda em um isolate, um contexto de execução do V8, dentro de um ambiente de isolamento baseado em isolates V8. Esse ambiente não dá ao código acesso direto ao sistema operacional subjacente. O limite de memória de uma function se aplica por isolate, e uma function que excede o seu tempo de CPU é encerrada. Para os valores, consulte [Limites de Functions](/pt-br/documentacao/plataforma/functions/limites/). -Para a segurança multi-tenant e a integridade da infraestrutura, uma Cell mantém três coisas fora do alcance do código: +Para a segurança multi-tenant e a integridade da infraestrutura, o ambiente de isolamento mantém três coisas fora do alcance do código: - As propriedades do sistema operacional do host. `node:os` retorna strings vazias ou zeros para o hostname, a release e os campos de memória, enquanto as suas chamadas `platform()` e `type()` retornam os valores genéricos `linux` e `Linux`. - A resolução de DNS por chamadas de sistema nativas. Uma chamada como `dns.lookup()` de `node:dns` lança `Error: [unenv] dns.lookup is not implemented yet!`. diff --git a/apps/docs/src/content/docs/pt-br/pages/guias/agentes-e-rag/gerar-embeddings-de-documentos-em-uma-tabela-vetorial.mdx b/apps/docs/src/content/docs/pt-br/pages/guias/agentes-e-rag/gerar-embeddings-de-documentos-em-uma-tabela-vetorial.mdx index 7d109a8792..ffca5a6c71 100644 --- a/apps/docs/src/content/docs/pt-br/pages/guias/agentes-e-rag/gerar-embeddings-de-documentos-em-uma-tabela-vetorial.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/guias/agentes-e-rag/gerar-embeddings-de-documentos-em-uma-tabela-vetorial.mdx @@ -47,7 +47,7 @@ Os exemplos leem o bucket `my-bucket`, geram embeddings com `Qwen/Qwen3-Embeddin ## Crie a tabela vetorial -A coluna vetorial declara a largura dos vetores que guarda, e a requisição de embedding pede a mesma largura. `Qwen/Qwen3-Embedding-4B` retorna uma de cinco larguras, `256`, `512`, `1024`, `2048` ou `4096`, pelo campo `dimensions`, então uma coluna `F32_BLOB(1024)` corresponde a uma requisição de `1024`. Um índice vetorial precisa de uma tabela com `ROWID` ou com uma chave primária de coluna única, e o segundo argumento dele define a métrica de distância. +A coluna vetorial declara a largura dos vetores que guarda, e a requisição de embedding pede a mesma largura. `Qwen/Qwen3-Embedding-4B` retorna a largura que o campo `dimensions` pede, `256`, `512`, `1024` ou `2048`, então uma coluna `F32_BLOB(1024)` corresponde a uma requisição de `1024`. Com `dimensions` definido como `4096`, ou ausente, o vetor tem largura `2560`. Um índice vetorial precisa de uma tabela com `ROWID` ou com uma chave primária de coluna única, e o segundo argumento dele define a métrica de distância. Para criar a tabela e o seu índice, envie as duas instruções ao endpoint de consulta: diff --git a/apps/docs/src/content/docs/pt-br/pages/guias/conhecendo-o-azion-console/conhecendo-o-azion-console.mdx b/apps/docs/src/content/docs/pt-br/pages/guias/conhecendo-o-azion-console/conhecendo-o-azion-console.mdx index f0917742ee..e6e40f8566 100644 --- a/apps/docs/src/content/docs/pt-br/pages/guias/conhecendo-o-azion-console/conhecendo-o-azion-console.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/guias/conhecendo-o-azion-console/conhecendo-o-azion-console.mdx @@ -1,11 +1,11 @@ --- title: Sobre Azion Console description: >- - Encontre onde o Azion Console guarda cada produto, o modal Create, a ajuda e + Encontre onde o Azion Console guarda cada produto, a Creation Center, a ajuda e as páginas da conta, da página inicial ao menu da conta. meta_tags: >- Azion, Azion Console, application, jornada, onboarding, templates, domínios, - tráfego, menu do Console, products menu, account menu + tráfego, menu do Console, products menu, Creation Center, account menu namespace: documentation_getting_to_know_azion_console permalink: /documentacao/guias/plataforma/conta-e-billing/conhecendo-o-azion-console/ --- @@ -15,7 +15,7 @@ import DocItem from '@aziontech/webkit/doc-item' Cada produto, recurso e configuração de conta que você usa na Azion é configurado em uma única interface web. O cabeçalho dela traz os menus e botões que abrem cada área, e a página inicial traz atalhos para as primeiras tarefas. Essa interface é o [Azion Console](https://console.azion.com/). -Nele, você configura sua [conta Azion](/pt-br/documentacao/fundamentos/criar-uma-conta/), [cria e implanta aplicações](/pt-br/documentacao/plataforma/applications/), [gerencia as configurações principais de uma aplicação](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/definir-configuracoes-principais/) e configura cada produto da Azion. Os [Guias](/pt-br/documentacao/guias/) cobrem as tarefas de cada um. As seções abaixo cobrem a página inicial, o menu do Console, o modal Create, os botões de ajuda, feedback e Copilot e o menu da conta, nessa ordem. Para se cadastrar ou entrar, consulte [Acesse Azion Console](/pt-br/documentacao/guias/plataforma/conta-e-billing/como-acessar-o-azion-console/). +Nele, você configura sua [conta Azion](/pt-br/documentacao/fundamentos/criar-uma-conta/), [cria e implanta aplicações](/pt-br/documentacao/plataforma/applications/), [gerencia as configurações principais de uma aplicação](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/definir-configuracoes-principais/) e configura cada produto da Azion. Os [Guias](/pt-br/documentacao/guias/) cobrem as tarefas de cada um. As seções abaixo cobrem a página inicial, o menu do Console, a Creation Center, os botões de ajuda, feedback e Copilot e o menu da conta, nessa ordem. Para se cadastrar ou entrar, consulte [Acesse Azion Console](/pt-br/documentacao/guias/plataforma/conta-e-billing/como-acessar-o-azion-console/). --- @@ -58,11 +58,14 @@ Selecionar uma entrada abre aquele produto com as configurações dele. As seç --- -## Modal Create +## Creation Center -O botão **+ Create** fica no cabeçalho do Console e no bloco **Get Started** da página inicial. Ele abre um modal com quatro abas: **Recommended**, **Templates**, **Resources** e **Import from GitHub**. Em algumas contas, só a aba **Resources** aparece. +O botão **+ Create** fica no cabeçalho do Console e no bloco **Get Started** da página inicial. Ele abre a **Creation Center**, uma página com duas seções: -A aba **Resources** cria um recurso por vez, como um workload, uma aplicação, um firewall, uma função ou um certificado digital. As outras abas iniciam uma aplicação inteira a partir de um template ou de um repositório do GitHub. Para saber o que cada aba oferece, consulte [Use o botão + Create](/pt-br/documentacao/guias/plataforma/conta-e-billing/botao-create/). +- **Import from GitHub** inicia uma aplicação a partir de um repositório de uma conta do GitHub que você conecta. +- **Start from Template** lista os templates **Recommended** e os **Azion Templates** disponíveis para a sua conta, com uma busca e filtros por tecnologia e por caso de uso. + +Para saber o que cada opção oferece, consulte [Use o botão + Create](/pt-br/documentacao/guias/plataforma/conta-e-billing/botao-create/). --- diff --git a/apps/docs/src/content/docs/pt-br/pages/guias/inferencia/rotear-chamadas-de-modelo-por-uma-function-de-gateway.mdx b/apps/docs/src/content/docs/pt-br/pages/guias/inferencia/rotear-chamadas-de-modelo-por-uma-function-de-gateway.mdx index 4f46784b96..637195493f 100644 --- a/apps/docs/src/content/docs/pt-br/pages/guias/inferencia/rotear-chamadas-de-modelo-por-uma-function-de-gateway.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/guias/inferencia/rotear-chamadas-de-modelo-por-uma-function-de-gateway.mdx @@ -92,7 +92,7 @@ const ROUTES = { { kind: "provider" } ], "long-context": [ - { kind: "azion", model: "gpt-oss-20b" }, + { kind: "azion", model: "openai/gpt-oss-20b" }, { kind: "provider" } ], "fallback-test": [ diff --git a/apps/docs/src/content/docs/pt-br/pages/guias/marketplace/templates/edge-ai-starter-kit.mdx b/apps/docs/src/content/docs/pt-br/pages/guias/marketplace/templates/edge-ai-starter-kit.mdx index 91fc761a9d..28cfde6bc6 100644 --- a/apps/docs/src/content/docs/pt-br/pages/guias/marketplace/templates/edge-ai-starter-kit.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/guias/marketplace/templates/edge-ai-starter-kit.mdx @@ -13,7 +13,7 @@ import DocCard from '@aziontech/webkit/doc-card' import DocSteps from '@aziontech/webkit/doc-steps' import DocStep from '@aziontech/webkit/doc-step' -Você pode implantar o template **AI Inference Starter Kit** e gerenciar o que ele cria pelo Azion Console. O template cria uma aplicação com uma função e um domínio, e a função serve um endpoint compatível com OpenAI. +Você pode implantar o template **AI Inference Starter Kit** e gerenciar o que ele cria pelo Azion Console. O template cria um Workload com o deployment dele, uma Application e uma Function com a Function Instance dela, e a Function serve um endpoint compatível com OpenAI no workload domain do Workload. O guia [Primeiros passos com AI Inference](/pt-br/documentacao/plataforma/ai-inference/primeiros-passos/) cobre a mesma implantação e acrescenta uma primeira requisição ao modelo. @@ -25,7 +25,7 @@ O template usa [Application Accelerator](/pt-br/documentacao/plataforma/applicat ## Implante o template -Para criar a aplicação, a função e o domínio a partir de um único template: +Para criar essas entidades a partir de um único template: @@ -35,12 +35,12 @@ Para criar a aplicação, a função e o domínio a partir de um único template - Selecione o template **AI Inference Starter Kit**. + Em **Start from Template**, selecione **AI Inference Starter Kit**. - Insira um nome para a aplicação. + Em **Application Name**, insira um nome feito de letras, números e sublinhados, como o padrão `ai_inference_starter_kit`. Um hífen é recusado com "The use of accents and/or special characters is not allowed." @@ -50,13 +50,13 @@ Para criar a aplicação, a função e o domínio a partir de um único template -Uma janela mostra os logs da implantação enquanto ela é executada. Quando ela termina, a página mostra informações sobre a aplicação e as opções para continuar. +Uma janela mostra os logs da implantação enquanto ela é executada. Quando ela termina, a página mostra o domínio em **Visit site**, a opção **Add custom domain**, os **Deployment logs** e **Resources created**, que lista o Workload e a Application. :::note[nota] -A página da implantação mostra um link para a aplicação. A aplicação leva alguns minutos para se propagar aos data centers da Azion, e o domínio não resolve até que ela se propague. Aguarde alguns minutos e selecione o link novamente. +A implantação leva vários minutos para se propagar aos data centers da Azion. Até se propagar, o domínio responde com o `404` de placeholder da Azion. Aguarde alguns minutos e selecione **Visit site** novamente. ::: -A aplicação responde no Workload Domain do workload que a serve, na forma `xxxxxxxxxx.map.azionedge.net/`, e serve um endpoint compatível com OpenAI nesse domínio. Para conhecer o caminho que uma requisição percorre do domínio até o modelo, consulte a arquitetura de [Adicionar funcionalidades de IA a aplicações existentes](/pt-br/documentacao/casos-de-uso/construir-e-executar-workloads-de-ai/adicionar-funcionalidades-de-ia-a-aplicacoes-existentes/). +A Application responde no workload domain do Workload, na forma `xxxxxxxxxx.map.azionedge.net`, e a Function serve um endpoint compatível com OpenAI em qualquer path desse domínio. Para conhecer o caminho que uma requisição percorre do domínio até o modelo, consulte a arquitetura de [Adicionar funcionalidades de IA a aplicações existentes](/pt-br/documentacao/casos-de-uso/construir-e-executar-workloads-de-ai/adicionar-funcionalidades-de-ia-a-aplicacoes-existentes/). --- @@ -78,7 +78,7 @@ Para alterar a função: - Selecione a função que tem o mesmo nome da aplicação. A lista está em ordem alfabética, e a **barra de busca** a filtra apenas por **Function Name**. + Selecione a Function que tem o nome que você inseriu durante a implantação, seguido do sufixo "(Build at …)". A lista está em ordem alfabética, e a **barra de busca** a filtra apenas por **Function Name**. @@ -95,60 +95,17 @@ Para alterar a função: A função tem as alterações que você salvou. Para conhecer todas as configurações que uma função tem, consulte [Functions](/pt-br/documentacao/plataforma/functions/). -A aba **Code** abre em uma função pronta para ser executada. Ela recebe uma requisição POST, chama o modelo e retorna a resposta. A chamada abaixo define `stream` como `false`, então o modelo retorna a resposta inteira: - -```ts -const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are a helpful assistant." - }, - { - "role": "user", - "content": "Name the European capitals." - } - ] -}) -return modelResponse -``` - -O modelo responde com uma entrada em `choices`, e o texto gerado fica em `choices[0].message.content`: - -```json -{ - "id": "chatcmpl-example", - "object": "chat.completion", - "created": 1767268800, - "model": "Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", - "choices": [ - { - "index": 0, - "message": { - "role": "assistant", - "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", - "tool_calls": [] - }, - "logprobs": null, - "finish_reason": "stop", - "stop_reason": null - } - ], - "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, - "prompt_tokens_details": null - }, - "prompt_logprobs": null -} -``` - -Este exemplo chama o [modelo Qwen3](/pt-br/documentacao/plataforma/ai-inference/qwen3-30ba3b/). Para chamar outro modelo, altere o primeiro argumento de `Azion.AI.run` para o id dele, listado em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). O corpo também aceita `stream`, que transmite a resposta em vez de retorná-la inteira. Para conhecer todos os campos que o corpo aceita, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). - -Antes de alterar a chamada, leia [Boas práticas do AI Inference](/pt-br/documentacao/plataforma/ai-inference/boas-praticas/) para conhecer os padrões de requisição que Azion recomenda, e [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/) para conhecer as condições em que Azion encerra um modelo. +A aba **Code** contém o código que o template instala. A cada requisição, a Function: + +- Aceita só uma requisição `POST` cujo header `Content-Type` seja exatamente `application/json`. Qualquer outra requisição recebe `400` com `{"error":"Request must be a POST request with JSON body"}`. +- Lê o id do modelo do campo `model` do corpo da requisição. Um corpo sem esse campo recebe `400` com `{"error":"Missing 'model' field in request body"}`. +- Passa o corpo inteiro para `Azion.AI.run` e retorna a resposta do modelo. Com `stream` definido como `true`, ela transmite a resposta como server-sent events, uma linha `data:` por parte, terminando com `data: [DONE]`. + +O código não contém nenhum id de modelo. Para chamar outro modelo, altere o campo `model` da requisição para o id dele, listado em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). Para conhecer todos os campos que o corpo aceita, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). + +A resposta do modelo mantém o formato de chat completion, e o texto gerado fica em `choices[0].message.content`. O campo `model` dela traz o id interno da conta para o modelo, que pode ser diferente do id que a requisição enviou: `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` retorna `qwen-qwen3-30b-a3b-instruct-2507-fp8`. Para enviar uma primeira requisição e ler uma resposta completa, consulte [Primeiros passos com AI Inference](/pt-br/documentacao/plataforma/ai-inference/primeiros-passos/). + +Antes de alterar o código, leia [Boas práticas do AI Inference](/pt-br/documentacao/plataforma/ai-inference/boas-praticas/) para conhecer os padrões de requisição que Azion recomenda, e [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/) para conhecer as condições em que Azion encerra um modelo. --- @@ -177,5 +134,5 @@ A página da aplicação abre nas configurações que você pode ajustar. Para s - + diff --git a/apps/docs/src/content/docs/pt-br/pages/hubs/guias/ai-inference.mdx b/apps/docs/src/content/docs/pt-br/pages/hubs/guias/ai-inference.mdx index 63f2a36b1f..c230250519 100644 --- a/apps/docs/src/content/docs/pt-br/pages/hubs/guias/ai-inference.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/hubs/guias/ai-inference.mdx @@ -7,4 +7,4 @@ permalink: /documentacao/plataforma/ai-inference/guias/ guides_hub: ai-inference --- -Todos os guias e tutoriais de AI Inference, cada um cobrindo uma tarefa. Abra um deles e você vai para a seção Guias, onde todos os guias ficam. +Cada guia abre na seção Guias, onde todos os guias ficam. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/Qwen3-30b-a3b-Instruct-2507-fp8.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/Qwen3-30b-a3b-Instruct-2507-fp8.mdx index fe80d597bb..bf120e0475 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/Qwen3-30b-a3b-Instruct-2507-fp8.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/Qwen3-30b-a3b-Instruct-2507-fp8.mdx @@ -1,7 +1,7 @@ --- title: Qwen3 30B A3B Instruct 2507 FP8 description: >- - Invoque Qwen3 30B A3B Instruct 2507 FP8, um modelo de linguagem de 30B + Invoque Qwen3 30B A3B Instruct 2507 FP8, um modelo de linguagem de 30,5B parâmetros com contexto de 64k tokens, chamada de ferramentas e suporte a LoRA. meta_tags: 'AI Inference, AI models, Qwen3 30B A3B Instruct 2507 FP8, large language model, tool calling, LoRA, Azion.AI.run' namespace: docs_edge_ai_models_qwen_3_30ba3b @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Qwen3 30B A3B Instruct 2507 FP8** é um modelo de linguagem grande ajustado por instruções com 30 bilhões de parâmetros, em precisão FP8. Ele lê texto e retorna texto, para chat e resposta a perguntas, sumarização, tarefas multilíngues, problemas de matemática e ciências, codificação e fluxos de trabalho que chamam ferramentas. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`. +**Qwen3 30B A3B Instruct 2507 FP8** é um large language model ajustado por instruções com 30,5 bilhões de parâmetros, em precisão FP8. Ele lê texto e retorna texto, para tarefas que pedem seguir instruções, raciocínio lógico, compreensão de texto, matemática, ciências, programação ou uso de ferramentas. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`. ## Detalhes do modelo @@ -24,7 +24,7 @@ O id é a string que uma requisição envia para selecionar este modelo, e `Azio | Versão | 30B - FP8 | | Categoria do modelo | Large Language Model (LLM) | | Id do modelo | `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` | -| Tamanho | 30B parâmetros | +| Tamanho | 30,5B parâmetros | | Modelo no HuggingFace | [Qwen/Qwen3-30B-A3B-Instruct-2507-FP8](https://huggingface.co/Qwen/Qwen3-30B-A3B-Instruct-2507-FP8) | | Endpoint compatível com OpenAI | [OpenAI Chat API](https://developers.openai.com/api/reference/overview) | | Licença | [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) | @@ -46,7 +46,7 @@ A janela de contexto nativa do modelo no projeto de origem é maior, e 64k token ## Uso -Os exemplos abaixo invocam o modelo a partir de uma [função](/pt-br/documentacao/plataforma/functions/) com `Azion.AI.run`. O binding recebe o id do modelo como primeiro argumento e o corpo da requisição como segundo, então o corpo nunca repete o id. Para enviar o mesmo corpo ao endpoint HTTP compatível com OpenAI, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +Os exemplos abaixo invocam o modelo a partir de uma [Function](/pt-br/documentacao/plataforma/functions/) com `Azion.AI.run`. O binding recebe o id do modelo como primeiro argumento e o corpo da requisição como segundo, então o corpo não precisa do id: o primeiro argumento decide o modelo, e um campo `model` no corpo é ignorado. Por HTTP, uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve um endpoint que recebe o mesmo corpo, com o id no campo `model`. Para esse endpoint, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). ### Chat completion @@ -97,7 +97,57 @@ const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", }) ``` -Quando o modelo seleciona uma ferramenta, a mensagem do assistente carrega um array `tool_calls` em vez de texto, e cada entrada nomeia a função e os argumentos que o modelo gerou para ela. +Quando o modelo seleciona uma ferramenta, a mensagem do assistente carrega `content` como `null` e um array `tool_calls`, e `finish_reason` é `tool_calls`. Cada entrada de `tool_calls` nomeia a função, os argumentos que o modelo gerou para ela e um `id`. + +Para devolver o resultado da chamada, envie a conversa de volta com mais duas mensagens: a mensagem do assistente como o modelo a retornou e uma mensagem `tool` que carrega o `id` da chamada em `tool_call_id` e o resultado em `content`: + +```ts +const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { + "stream": false, + "max_tokens": 64, + "messages": [ + { "role": "system", "content": "You are a helpful assistant with access to tools." }, + { "role": "user", "content": "What is the weather in London?" }, + { + "role": "assistant", + "content": null, + "tool_calls": [ + { + "id": "chatcmpl-tool-789b0d0737f84d09b61eee169a3bea75", + "type": "function", + "function": { "name": "get_weather", "arguments": "{\"location\": \"London\"}" } + } + ] + }, + { + "role": "tool", + "tool_call_id": "chatcmpl-tool-789b0d0737f84d09b61eee169a3bea75", + "content": "{\"temperature_c\": 14, \"condition\": \"light rain\"}" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state" + } + }, + "required": ["location"] + } + } + } + ] +}) +``` + +O modelo responde em texto, com `finish_reason` igual a `stop`: `The current weather in London is 14°C with light rain.` --- @@ -107,9 +157,7 @@ Quando o modelo seleciona uma ferramenta, a mensagem do assistente carrega um ar Os campos que um corpo de requisição carrega e a forma HTTP da mesma chamada. O restante do catálogo, com o id e as capacidades que cada modelo declara. - O produto que executa este modelo. - O runtime que contém o binding que os exemplos desta página chamam. A extensão do AI Inference que adapta um modelo com LoRA e os modelos que a aceitam. - As definições de id do modelo, comprimento de contexto e dos demais termos que esta página usa. + As definições de id do modelo, `Azion.AI.run` e dos demais termos que esta página usa. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/baai-bge-reranker-v2-m3.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/baai-bge-reranker-v2-m3.mdx index 60bbb06b36..00e6558b63 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/baai-bge-reranker-v2-m3.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/baai-bge-reranker-v2-m3.mdx @@ -42,7 +42,7 @@ Estes valores descrevem o modelo e não são campos do corpo da requisição. Pa ## Uso -Uma [função](/pt-br/documentacao/plataforma/functions/) invoca o modelo com `Azion.AI.run`, passando o id como primeiro argumento e o corpo da requisição como segundo. Este modelo não recebe um array `messages`: cada uma das duas operações abaixo tem o seu próprio corpo. Para enviar o mesmo corpo por HTTP, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +Uma [Function](/pt-br/documentacao/plataforma/functions/) invoca o modelo com `Azion.AI.run`, passando o id como primeiro argumento e o corpo da requisição como segundo. Este modelo não recebe um array `messages`. Um corpo sem `query` e `documents`, como um que carrega `text_1` e `text_2`, é recusado com `AIError: validation error: Required` em `/query` e `/documents`. Por HTTP, uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve um endpoint que recebe o mesmo corpo, com o id no campo `model`. Para esse endpoint, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). ### Reranking @@ -73,28 +73,32 @@ O modelo retorna um array `results` ordenado do maior `relevance_score` para o m { "index": 0, "document": { - "text": "Deep learning is a subset of machine learning that uses neural networks with many layers" + "text": "Deep learning is a subset of machine learning that uses neural networks with many layers", + "multi_modal": null }, "relevance_score": 0.99951171875 }, { "index": 2, "document": { - "text": "Deep learning enables computers to learn from large amounts of data" + "text": "Deep learning enables computers to learn from large amounts of data", + "multi_modal": null }, "relevance_score": 0.98291015625 }, { "index": 3, "document": { - "text": "I like pizza" + "text": "I like pizza", + "multi_modal": null }, "relevance_score": 0.00001621246337890625 }, { "index": 1, "document": { - "text": "The weather is nice today" + "text": "The weather is nice today", + "multi_modal": null }, "relevance_score": 0.000016033649444580078 } @@ -102,24 +106,6 @@ O modelo retorna um array `results` ordenado do maior `relevance_score` para o m } ``` -### Pontuação - -Uma requisição de pontuação carrega `text_1` e o array `text_2` que o modelo pontua em relação a ele: - -```ts -const modelResponse = await Azion.AI.run("baai-bge-reranker-v2-m3", { - "text_1": "What is deep learning?", - "text_2": [ - "Deep learning is a subset of machine learning that uses neural networks with many layers", - "The weather is nice today", - "Deep learning enables computers to learn from large amounts of data", - "I like pizza" - ] -}) -``` - -A resposta carrega o mesmo array `results`, com uma entrada e uma `relevance_score` para cada texto em `text_2`. - --- ## Recursos relacionados @@ -128,9 +114,7 @@ A resposta carrega o mesmo array `results`, com uma entrada e uma `relevance_sco Todos os campos que uma requisição de reranking aceita e o endpoint HTTP que recebe o mesmo corpo. Os outros modelos que AI Inference executa e o id ao qual cada um responde. - O produto que executa este modelo. - O produto cujo runtime contém o binding que os exemplos desta página chamam. As condições sob as quais a Azion encerra ou desprovisiona um modelo. - Onde id do modelo, comprimento de contexto e o restante do vocabulário do AI Inference são definidos. + Onde id do modelo, `Azion.AI.run` e o restante do vocabulário do AI Inference são definidos. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/gpt-oss-20b.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/gpt-oss-20b.mdx index 6f49831406..fa64a171b1 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/gpt-oss-20b.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/gpt-oss-20b.mdx @@ -1,8 +1,8 @@ --- title: GPT-OSS 20B description: >- - Invoque GPT-OSS 20B, um modelo de linguagem grande com comprimento de contexto - de 131k tokens, e envie uma requisição com chamada de ferramentas. + Invoque GPT-OSS 20B, um large language model open-weight com comprimento de + contexto de 131k tokens, e envie uma requisição com chamada de ferramentas. meta_tags: 'AI Inference, AI models, GPT-OSS 20B, large language model, tool calling, context length, Azion.AI.run' namespace: docs_edge_ai_models_gpt_oss_20b permalink: /documentacao/plataforma/ai-inference/gpt-oss-20b/ @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**GPT-OSS 20B** é um modelo de linguagem grande open-source com 20 bilhões de parâmetros, construído para geração de texto, conversação e outras tarefas de processamento de linguagem natural. Ele lê texto, retorna texto e aceita definições de ferramentas na requisição. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `gpt-oss-20b`. +**GPT-OSS 20B** é um large language model open-weight com 21 bilhões de parâmetros, projetado para raciocínio e tarefas de agentes. Ele raciocina antes de responder, lê texto, retorna texto e aceita definições de ferramentas na requisição. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `openai/gpt-oss-20b`. ## Detalhes do modelo @@ -23,8 +23,8 @@ O id do modelo é a string que seleciona este modelo, e é o primeiro argumento | Nome do modelo | GPT-OSS 20B | | Versão | 20B | | Categoria do modelo | Large Language Model (LLM) | -| Id do modelo | `gpt-oss-20b` | -| Tamanho | 20B parâmetros | +| Id do modelo | `openai/gpt-oss-20b` | +| Tamanho | 21B parâmetros | | Modelo no HuggingFace | [openai/gpt-oss-20b](https://huggingface.co/openai/gpt-oss-20b) | | Endpoint compatível com OpenAI | [OpenAI Chat API](https://developers.openai.com/api/reference/overview) | | Licença | [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) | @@ -44,26 +44,22 @@ Estes valores pertencem ao modelo e não fazem parte do corpo da requisição. P ## Uso -Uma [função](/pt-br/documentacao/plataforma/functions/) invoca o modelo com `Azion.AI.run`, passando o id como primeiro argumento e um corpo de requisição compatível com OpenAI como segundo. Os exemplos abaixo usam esse binding. Para enviar o mesmo corpo ao endpoint HTTP compatível com OpenAI, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +Uma [Function](/pt-br/documentacao/plataforma/functions/) invoca o modelo com `Azion.AI.run`, passando o id como primeiro argumento e um corpo de requisição compatível com OpenAI como segundo. Os exemplos abaixo usam esse binding. Por HTTP, uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve um endpoint que recebe o mesmo corpo, com o id no campo `model`. Para esse endpoint, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). ### Chat completion -Esta requisição carrega uma mensagem de sistema, uma mensagem de usuário e os campos de amostragem que moldam a saída: +Esta requisição carrega uma mensagem de usuário e limita a saída com `max_tokens`: ```ts -const modelResponse = await Azion.AI.run("gpt-oss-20b", { - "stream": false, - "max_tokens": 1024, - "temperature": 0.7, - "top_p": 0.9, +const modelResponse = await Azion.AI.run("openai/gpt-oss-20b", { + "max_tokens": 64, "messages": [ - { "role": "system", "content": "You are a helpful assistant." }, - { "role": "user", "content": "Name the European capitals." } + { "role": "user", "content": "Reply with the word: ready" } ] }) ``` -O modelo responde com uma entrada em `choices`, e o texto gerado fica em `choices[0].message.content`: +O modelo responde com uma entrada em `choices`. O texto gerado fica em `choices[0].message.content`, e o raciocínio que o precedeu fica em `reasoning_content`, que a mensagem também carrega como `reasoning`: ```json { @@ -76,8 +72,9 @@ O modelo responde com uma entrada em `choices`, e o texto gerado fica em `choice "index": 0, "message": { "role": "assistant", - "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", + "reasoning": "User: \"Reply with the word: ready\". They want the reply the word \"ready\". Probably just \"ready\".", + "reasoning_content": "User: \"Reply with the word: ready\". They want the reply the word \"ready\". Probably just \"ready\".", + "content": "ready", "tool_calls": [] }, "logprobs": null, @@ -86,21 +83,25 @@ O modelo responde com uma entrada em `choices`, e o texto gerado fica em `choice } ], "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 75, + "total_tokens": 110, + "completion_tokens": 35, "prompt_tokens_details": null }, "prompt_logprobs": null } ``` +O raciocínio sai do orçamento de `max_tokens`. Com um orçamento pequeno, o raciocínio pode usar todo ele, e a resposta então traz `content` como `null` e `finish_reason` como `length`. + +O campo `model` da resposta traz `gpt-oss-20b`, um id que `Azion.AI.run` recusa como entrada. Para chamar o modelo de novo, passe `openai/gpt-oss-20b`, e não o valor desse campo. + ### Chamada de ferramentas Uma requisição com chamada de ferramentas adiciona um array `tools` ao corpo. Cada entrada define `type` como `function` e carrega um objeto `function` com o nome que o modelo chama, uma descrição do que ele faz e seus `parameters` em formato JSON Schema: ```ts -const modelResponse = await Azion.AI.run("gpt-oss-20b", { +const modelResponse = await Azion.AI.run("openai/gpt-oss-20b", { "stream": false, "max_tokens": 1024, "messages": [ @@ -142,7 +143,8 @@ Quando o modelo seleciona uma ferramenta, ele retorna `content` como `null`, nom "index": 0, "message": { "role": "assistant", - "reasoning_content": null, + "reasoning": "We should call get_weather function.", + "reasoning_content": "We should call get_weather function.", "content": null, "tool_calls": [ { @@ -157,13 +159,13 @@ Quando o modelo seleciona uma ferramenta, ele retorna `content` como `null`, nom }, "logprobs": null, "finish_reason": "tool_calls", - "stop_reason": null + "stop_reason": 200012 } ], "usage": { - "prompt_tokens": 293, - "total_tokens": 313, - "completion_tokens": 20, + "prompt_tokens": 147, + "total_tokens": 178, + "completion_tokens": 31, "prompt_tokens_details": null }, "prompt_logprobs": null @@ -178,9 +180,7 @@ Quando o modelo seleciona uma ferramenta, ele retorna `content` como `null`, nom Todos os campos que um corpo de requisição aceita e o endpoint HTTP que recebe o mesmo corpo. Os outros modelos que AI Inference executa e o id ao qual cada um responde. - O produto que executa este modelo. - O produto cujo runtime contém o binding que os exemplos desta página chamam. As condições sob as quais a Azion encerra ou desprovisiona um modelo. - Onde id do modelo, comprimento de contexto e o restante do vocabulário do AI Inference são definidos. + Onde id do modelo, `Azion.AI.run` e o restante do vocabulário do AI Inference são definidos. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/mistral-3-small.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/mistral-3-small.mdx index 1d2fb6adfd..50853977d7 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/mistral-3-small.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/mistral-3-small.mdx @@ -12,11 +12,11 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Mistral 3 Small** é um large language model com 24 bilhões de parâmetros, construído para agentes conversacionais, geração de texto e chamada de ferramentas. Ele lê texto, retorna texto e aceita definições de ferramentas na requisição. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `casperhansen-mistral-small-24b-instruct-2501-awq`. +**Mistral 3 Small** é um large language model com 24 bilhões de parâmetros, construído para agentes conversacionais e chamada de ferramentas. Ele lê texto, retorna texto e aceita definições de ferramentas na requisição. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `casperhansen-mistral-small-24b-instruct-2501-awq`. ## Detalhes do modelo -O id do modelo é a string que seleciona este modelo, e é o primeiro argumento que `Azion.AI.run` recebe. O repositório no HuggingFace guarda o model card. +O id do modelo é a string que seleciona este modelo, e é o primeiro argumento que `Azion.AI.run` recebe. O repositório no HuggingFace indicado abaixo guarda os pesos quantizados com AWQ (Activation-aware Weight Quantization) e não tem model card. A descrição e a licença desta página seguem o card do [Mistral Small 24B Instruct 2501](https://huggingface.co/mistralai/Mistral-Small-24B-Instruct-2501), o modelo que esses pesos quantizam. | Detalhe | Valor | | --- | --- | @@ -44,7 +44,7 @@ Estes valores pertencem ao modelo e não fazem parte do corpo da requisição. P ## Uso -Uma [função](/pt-br/documentacao/plataforma/functions/) invoca o modelo com `Azion.AI.run`, passando o id como primeiro argumento e um corpo de requisição compatível com OpenAI como segundo. Os exemplos abaixo usam esse binding. Para enviar o mesmo corpo ao endpoint HTTP compatível com OpenAI, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +Uma [Function](/pt-br/documentacao/plataforma/functions/) invoca o modelo com `Azion.AI.run`, passando o id como primeiro argumento e um corpo de requisição compatível com OpenAI como segundo. Os exemplos abaixo usam esse binding. Por HTTP, uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve um endpoint que recebe o mesmo corpo, com o id no campo `model`. Para esse endpoint, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). ### Chat completion @@ -53,7 +53,7 @@ Esta requisição carrega uma mensagem de sistema e uma mensagem de usuário, e ```ts const modelResponse = await Azion.AI.run("casperhansen-mistral-small-24b-instruct-2501-awq", { "stream": false, - "max_tokens": 1024, + "max_tokens": 64, "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Name the European capitals." } @@ -75,24 +75,26 @@ O modelo responde com uma entrada em `choices`, e o texto gerado fica em `choice "message": { "role": "assistant", "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", + "content": "Sure, here are the capitals of the European countries:\n\n1. **Albania** - Tirana\n2. **Andorra** - Andorra la Vella\n3. **Armenia** - Yerevan (located in the Caucasus region, which is also geopolitically considered part of", "tool_calls": [] }, "logprobs": null, - "finish_reason": "stop", + "finish_reason": "length", "stop_reason": null } ], "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 17, + "total_tokens": 81, + "completion_tokens": 64, "prompt_tokens_details": null }, "prompt_logprobs": null } ``` +A resposta para nos 64 tokens que `max_tokens` permite, então `finish_reason` traz `length`. + ### Chamada de ferramentas Uma requisição de chamada de ferramentas adiciona um array `tools` ao corpo. Cada entrada define `type` como `function` e carrega um objeto `function` com o nome que o modelo chama, uma descrição do que ele faz e seus `parameters` no formato JSON Schema: @@ -144,11 +146,11 @@ Quando o modelo seleciona uma ferramenta, ele retorna `content` como `null`, nom "content": null, "tool_calls": [ { - "id": "chatcmpl-tool-0123456789abcdef0123456789abcdef", + "id": "kpkde3q4d", "type": "function", "function": { "name": "get_weather", - "arguments": "{\"location\": \"London\"}" + "arguments": "{\"location\": \"london\"}" } } ] @@ -159,9 +161,9 @@ Quando o modelo seleciona uma ferramenta, ele retorna `content` como `null`, nom } ], "usage": { - "prompt_tokens": 293, - "total_tokens": 313, - "completion_tokens": 20, + "prompt_tokens": 93, + "total_tokens": 115, + "completion_tokens": 22, "prompt_tokens_details": null }, "prompt_logprobs": null @@ -176,9 +178,7 @@ Quando o modelo seleciona uma ferramenta, ele retorna `content` como `null`, nom Todos os campos que um corpo de requisição aceita e o endpoint HTTP que recebe o mesmo corpo. Os outros modelos que AI Inference executa e o id ao qual cada um responde. - O produto que executa este modelo. - O produto cujo runtime contém o binding que os exemplos desta página chamam. - As condições sob as quais Azion encerra ou desprovisiona um modelo. - Onde id de modelo, comprimento de contexto e o restante do vocabulário do AI Inference são definidos. + As condições sob as quais a Azion encerra ou desprovisiona um modelo. + Onde id do modelo, `Azion.AI.run` e o restante do vocabulário do AI Inference são definidos. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/nanonets-ocr-r.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/nanonets-ocr-r.mdx index e90f479c42..733f929b22 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/nanonets-ocr-r.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/nanonets-ocr-r.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Nanonets-OCR-s** é um modelo de reconhecimento óptico de caracteres (OCR) que converte a imagem de um documento em Markdown estruturado. A saída preserva o layout da origem, incluindo títulos, listas, tabelas e tags básicas, para que outro modelo consiga interpretá-la. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `nanonets/Nanonets-OCR-s`. +**Nanonets-OCR-s** é um modelo de reconhecimento óptico de caracteres (OCR) que converte a imagem de um documento em Markdown estruturado. A saída preserva as tabelas, escreve as equações em LaTeX e envolve em tags as descrições de imagens, as assinaturas e as marcas-d'água, para que outro modelo consiga processá-la. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `nanonets/Nanonets-OCR-s`. ## Detalhes do modelo @@ -31,12 +31,13 @@ Os valores abaixo descrevem o modelo em si, e nenhum deles é um campo do corpo | --- | --- | | Dados de entrada | Texto e imagem | | Comprimento de contexto | 32k tokens | +| Chamada de ferramentas | Não | --- ## Uso -`Azion.AI.run` executa o modelo de dentro de uma [função](/pt-br/documentacao/plataforma/functions/): o id vai no primeiro argumento e um corpo de requisição compatível com OpenAI vai no segundo. O exemplo desta página chama o binding dessa forma. Para enviar o mesmo corpo por HTTP, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +`Azion.AI.run` executa o modelo de dentro de uma [Function](/pt-br/documentacao/plataforma/functions/): o id vai no primeiro argumento e um corpo de requisição compatível com OpenAI vai no segundo. O exemplo desta página chama o binding dessa forma. Por HTTP, uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve um endpoint que recebe o mesmo corpo, com o id no campo `model`. Para esse endpoint, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). ### OCR @@ -53,7 +54,7 @@ const modelResponse = await Azion.AI.run("nanonets/Nanonets-OCR-s", { { "type": "image_url", "image_url": { - "url": "data:image/png;base64,{img_base64}" + "url": "data:image/png;base64," } }, { @@ -66,21 +67,23 @@ const modelResponse = await Azion.AI.run("nanonets/Nanonets-OCR-s", { }) ``` -O modelo retorna uma entrada em `choices`, e o texto transcrito fica em `choices[0].message.content`: +Substitua `` pelo arquivo PNG codificado em base64. O campo `image_url.url` também aceita uma URL `https` que sirva uma imagem. Quando a URL não serve uma imagem, `Azion.AI.run` lança `Error: Request failed with status 500`. + +O modelo retorna uma entrada em `choices`, e o texto transcrito fica em `choices[0].message.content`. Para um PNG que mostra a palavra AZION, a resposta é: ```json { "id": "chatcmpl-0123456789abcdef0123456789abcdef", "object": "chat.completion", "created": 1767268800, - "model": "nanonets/Nanonets-OCR-s", + "model": "nanonets-nanonets-ocr-s", "choices": [ { "index": 0, "message": { "role": "assistant", "reasoning_content": null, - "content": "E = mc^2", + "content": "AZION", "tool_calls": [] }, "logprobs": null, @@ -89,9 +92,9 @@ O modelo retorna uma entrada em `choices`, e o texto transcrito fica em `choices } ], "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 182, + "total_tokens": 185, + "completion_tokens": 3, "prompt_tokens_details": null }, "prompt_logprobs": null @@ -106,9 +109,7 @@ O modelo retorna uma entrada em `choices`, e o texto transcrito fica em `choices Todos os campos que um corpo de requisição aceita e o endpoint HTTP que recebe o mesmo corpo. Os outros modelos que AI Inference executa e o id ao qual cada um responde. - O produto que executa este modelo. - O produto cujo runtime contém o binding que o exemplo desta página chama. As condições sob as quais a Azion encerra ou desprovisiona um modelo. - Onde id do modelo, comprimento de contexto e o restante do vocabulário do AI Inference são definidos. + Onde id do modelo, `Azion.AI.run` e o restante do vocabulário do AI Inference são definidos. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen-2-5-vl-3b.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen-2-5-vl-3b.mdx index c6c6a081b7..665da95af1 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen-2-5-vl-3b.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen-2-5-vl-3b.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Qwen2.5 VL AWQ 3B** é um vision-language model com 3 bilhões de parâmetros. Ele lê texto e imagens, retorna texto e realiza análise visual, raciocínio de agente, compreensão de vídeo longo, localização visual e geração de saída estruturada. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `qwen-qwen25-vl-3b-instruct-awq`. +**Qwen2.5 VL AWQ 3B** é um vision-language model com 3 bilhões de parâmetros. Ele lê texto e imagens, retorna texto e realiza análise visual, raciocínio de agente, localização visual e geração de saída estruturada. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `qwen-qwen25-vl-3b-instruct-awq`. ## Detalhes do modelo @@ -27,7 +27,7 @@ O id é o que uma requisição envia para alcançar este modelo, e `Azion.AI.run | Tamanho | 3B parâmetros | | Modelo no HuggingFace | [Qwen/Qwen2.5-VL-3B-Instruct-AWQ](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct-AWQ) | | Endpoint compatível com OpenAI | [OpenAI Chat API](https://developers.openai.com/api/reference/overview) | -| Licença | [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) | +| Licença | [Qwen Research License](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct-AWQ/blob/main/LICENSE) | ## Capacidades @@ -37,22 +37,23 @@ Estas capacidades são propriedades do modelo, e o corpo da requisição não as | --- | --- | | Dados de entrada | Texto e imagem | | Comprimento de contexto | 32k tokens | -| Chamada de ferramentas | Sim | +| Chamada de ferramentas | Só com a ferramenta nomeada | | Suporta LoRA | Sim | --- ## Uso -Você chama este modelo a partir de uma [função](/pt-br/documentacao/plataforma/functions/), por meio do binding `Azion.AI.run`. O primeiro argumento é o id do modelo, e o segundo é um corpo de requisição compatível com OpenAI. Cada exemplo desta página usa esse binding. Para a forma HTTP da mesma requisição, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +Você chama este modelo a partir de uma [Function](/pt-br/documentacao/plataforma/functions/), por meio do binding `Azion.AI.run`. O primeiro argumento é o id do modelo, e o segundo é um corpo de requisição compatível com OpenAI. Cada exemplo desta página usa esse binding. Por HTTP, uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve um endpoint que recebe o mesmo corpo, com o id no campo `model`. Para esse endpoint, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). ### Chat completion -Esta requisição carrega uma mensagem de sistema que define o comportamento do modelo e uma mensagem de usuário que contém o prompt: +Esta requisição carrega uma mensagem de sistema que define o comportamento do modelo e uma mensagem de usuário que contém o prompt, e limita a resposta com `max_tokens`: ```ts const modelResponse = await Azion.AI.run("qwen-qwen25-vl-3b-instruct-awq", { "stream": false, + "max_tokens": 64, "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Name the European capitals." } @@ -74,31 +75,36 @@ Uma entrada chega em `choices`, e o texto que o modelo gerou fica em `choices[0] "message": { "role": "assistant", "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", + "content": "Here are some of the European capitals:\n\n1. Berlin, Germany\n2. Paris, France\n3. Madrid, Spain\n4. Rome, Italy\n5. Vienna, Austria\n6. Stockholm, Sweden\n7. Copenhagen, Denmark\n8. Helsinki, Finland\n9. Oslo, Norway\n10", "tool_calls": [] }, "logprobs": null, - "finish_reason": "stop", + "finish_reason": "length", "stop_reason": null } ], "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 24, + "total_tokens": 88, + "completion_tokens": 64, "prompt_tokens_details": null }, "prompt_logprobs": null } ``` +A resposta para nos 64 tokens que `max_tokens` permite, então `finish_reason` traz `length`. + ### Chamada de ferramentas -Um array `tools` declara as funções que o modelo pode chamar. Cada entrada define `type` como `function` e carrega um objeto `function`. Esse objeto tem três campos: o `name` que o modelo retorna, uma `description` do que a função faz e os `parameters` que ela aceita, escritos como um objeto JSON Schema: +Um array `tools` declara as funções que o modelo pode chamar. Cada entrada define `type` como `function` e carrega um objeto `function`. Esse objeto tem três campos: o `name` que o modelo retorna, uma `description` do que a função faz e os `parameters` que ela aceita, escritos como um objeto JSON Schema. + +Este modelo retorna `tool_calls` quando a requisição nomeia a ferramenta em `tool_choice`. Uma requisição que carrega `tools` e deixa a escolha para o modelo falha, e `Azion.AI.run` lança `Error: Request failed with status 400`. Esta requisição nomeia `get_weather`: ```ts const modelResponse = await Azion.AI.run("qwen-qwen25-vl-3b-instruct-awq", { "stream": false, + "max_tokens": 64, "messages": [ { "role": "system", "content": "You are a helpful assistant with access to tools." }, { "role": "user", "content": "What is the weather in London?" } @@ -121,11 +127,12 @@ const modelResponse = await Azion.AI.run("qwen-qwen25-vl-3b-instruct-awq", { } } } - ] + ], + "tool_choice": { "type": "function", "function": { "name": "get_weather" } } }) ``` -Uma resposta que seleciona uma ferramenta carrega `null` em `content`, uma entrada em `tool_calls` com o nome da função e os argumentos que o modelo escolheu, e `tool_calls` em `finish_reason`: +A resposta carrega uma entrada em `tool_calls` com o nome da função e os argumentos que o modelo escolheu. `content` é uma string vazia, e `finish_reason` é `stop`, não `tool_calls`: ```json { @@ -139,10 +146,10 @@ Uma resposta que seleciona uma ferramenta carrega `null` em `content`, uma entra "message": { "role": "assistant", "reasoning_content": null, - "content": null, + "content": "", "tool_calls": [ { - "id": "chatcmpl-tool-0123456789abcdef0123456789abcdef", + "id": "chatcmpl-tool-213ac5dfd9d1487b8456755f291e95a4", "type": "function", "function": { "name": "get_weather", @@ -152,14 +159,14 @@ Uma resposta que seleciona uma ferramenta carrega `null` em `content`, uma entra ] }, "logprobs": null, - "finish_reason": "tool_calls", + "finish_reason": "stop", "stop_reason": null } ], "usage": { - "prompt_tokens": 293, - "total_tokens": 313, - "completion_tokens": 20, + "prompt_tokens": 30, + "total_tokens": 37, + "completion_tokens": 7, "prompt_tokens_details": null }, "prompt_logprobs": null @@ -181,13 +188,15 @@ const modelResponse = await Azion.AI.run("qwen-qwen25-vl-3b-instruct-awq", { "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, - { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } + { "type": "image_url", "image_url": { "url": "" } } ] } ] }) ``` +Substitua `` por uma URL `https` que sirva uma imagem ou por uma URL `data:` que carregue a imagem em base64. Quando a URL não serve uma imagem, `Azion.AI.run` lança `Error: Request failed with status 500`. + O modelo retorna o mesmo objeto de resposta de um chat completion, e o que ele leu na imagem fica em `choices[0].message.content`. --- @@ -198,9 +207,7 @@ O modelo retorna o mesmo objeto de resposta de um chat completion, e o que ele l Os campos da requisição, os objetos de mensagem e o endpoint HTTP que recebe o mesmo corpo. O catálogo de modelos que AI Inference executa, com o id e as capacidades de cada um. - O produto que carrega e executa este modelo. - O produto cujo runtime contém o binding que estes exemplos chamam. A extensão do AI Inference que adapta um modelo com LoRA, e os modelos que a aceitam. - Onde id do modelo, comprimento de contexto e o restante do vocabulário do AI Inference são definidos. + Onde id do modelo, `Azion.AI.run` e o restante do vocabulário do AI Inference são definidos. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen-2-5-vl-7b.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen-2-5-vl-7b.mdx index 52bdc7ad4b..093406e764 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen-2-5-vl-7b.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen-2-5-vl-7b.mdx @@ -1,7 +1,7 @@ --- title: Qwen2.5 VL AWQ 7B description: >- - Invoque Qwen2.5 VL AWQ 7B, um modelo de visão e linguagem com 7 bilhões de + Invoque Qwen2.5 VL AWQ 7B, um vision-language model com 7 bilhões de parâmetros, e envie texto e imagem na mesma requisição. meta_tags: 'AI Inference, AI models, Qwen2.5 VL AWQ 7B, vision-language model, multimodal input, tool calling, Azion.AI.run' namespace: docs_edge_ai_models_qwen_2_5_vl_7b @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Qwen2.5 VL AWQ 7B** é um modelo de visão e linguagem com 7 bilhões de parâmetros, construído para análise visual, raciocínio agêntico, compreensão de vídeos longos, localização visual e geração de saída estruturada. O modelo aceita texto e imagens na mesma requisição, retorna texto e recebe definições de ferramentas. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `qwen-qwen25-vl-7b-instruct-awq`. +**Qwen2.5 VL AWQ 7B** é um vision-language model com 7 bilhões de parâmetros, construído para análise visual, raciocínio de agente, localização visual e geração de saída estruturada. O modelo aceita texto e imagens na mesma requisição, retorna texto e chama uma ferramenta que a requisição nomeia. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa o modelo sob o id `qwen-qwen25-vl-7b-instruct-awq`. ## Detalhes do modelo @@ -31,20 +31,20 @@ Estes valores identificam o modelo. Uma requisição nomeia o id do modelo para ## Capacidades -Qwen2.5 VL AWQ 7B declara estas capacidades para si, e nenhuma delas é um campo da requisição. Para ler os campos que uma requisição de chat carrega, com seus tipos, padrões e limites, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +Estes valores são propriedades do modelo, e o corpo da requisição não os define. Para ler os campos que uma requisição de chat carrega, com seus tipos, padrões e limites, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). | Capacidade | Valor | | --- | --- | | Dados de entrada | Texto e imagem | | Comprimento de contexto | 32k tokens | -| Chamada de ferramentas | Sim | +| Chamada de ferramentas | Só com a ferramenta nomeada | | Suporta LoRA | Sim | --- ## Uso -Todos os exemplos desta página chamam `Azion.AI.run` de dentro de uma [função](/pt-br/documentacao/plataforma/functions/). O binding recebe o id do modelo como primeiro argumento e um corpo de requisição compatível com OpenAI como segundo, então o corpo nunca repete o id. Para enviar o mesmo corpo ao endpoint HTTP compatível com OpenAI, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +Todos os exemplos desta página chamam `Azion.AI.run` de dentro de uma [Function](/pt-br/documentacao/plataforma/functions/). O binding recebe o id do modelo como primeiro argumento e um corpo de requisição compatível com OpenAI como segundo, então o corpo não precisa do id: o primeiro argumento decide o modelo, e um campo `model` no corpo é ignorado. Por HTTP, uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve um endpoint que recebe o mesmo corpo, com o id no campo `model`. Para esse endpoint, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). ### Chat completion @@ -64,13 +64,14 @@ Com `stream` definido como `false`, a chamada resolve para uma resposta completa ### Chamada de ferramentas -Uma requisição com chamada de ferramentas mantém as mesmas mensagens e adiciona um array `tools`. Cada entrada declara `type` como `function`, nomeia a função, descreve o que ela faz e define seus `parameters` como um objeto JSON Schema: +Uma requisição com chamada de ferramentas adiciona um array `tools` às mensagens. Cada entrada declara `type` como `function`, nomeia a função, descreve o que ela faz e define seus `parameters` como um objeto JSON Schema. + +Este modelo retorna `tool_calls` quando a requisição nomeia a ferramenta em `tool_choice`. Uma requisição que carrega `tools` e deixa a escolha para o modelo falha, e `Azion.AI.run` lança `Error: Request failed with status 400`. Esta requisição nomeia `get_weather`: ```ts const modelResponse = await Azion.AI.run("qwen-qwen25-vl-7b-instruct-awq", { - "stream": false, + "max_tokens": 48, "messages": [ - { "role": "system", "content": "You are a helpful assistant with access to tools." }, { "role": "user", "content": "What is the weather in London?" } ], "tools": [ @@ -82,20 +83,18 @@ const modelResponse = await Azion.AI.run("qwen-qwen25-vl-7b-instruct-awq", { "parameters": { "type": "object", "properties": { - "location": { - "type": "string", - "description": "The city and state" - } + "location": { "type": "string" } }, "required": ["location"] } } } - ] + ], + "tool_choice": { "type": "function", "function": { "name": "get_weather" } } }) ``` -Uma função lê a resposta do modelo na primeira entrada de `choices` e age sobre ela, o que nesta requisição significa chamar `get_weather`. +A resposta carrega uma entrada em `tool_calls` que nomeia `get_weather` com os argumentos que o modelo escolheu. `content` é uma string vazia, e `finish_reason` é `stop`, não `tool_calls`. ### Entrada multimodal @@ -110,13 +109,15 @@ const modelResponse = await Azion.AI.run("qwen-qwen25-vl-7b-instruct-awq", { "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, - { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } + { "type": "image_url", "image_url": { "url": "" } } ] } ] }) ``` +Substitua `` por uma URL `https` que sirva uma imagem ou por uma URL `data:` que carregue a imagem em base64. Quando a URL não serve uma imagem, `Azion.AI.run` lança `Error: Request failed with status 500`. + O modelo lê a imagem a partir da URL que a requisição fornece e responde em texto em `modelResponse?.choices?.[0]?.message?.content`. --- @@ -127,9 +128,7 @@ O modelo lê a imagem a partir da URL que a requisição fornece e responde em t Como uma requisição chega a um modelo, pelo binding ou por HTTP, e o que o corpo dela carrega. O restante do catálogo, com as capacidades que cada modelo declara para si. - O que é AI Inference e o que ele faz com uma requisição a um modelo. - Onde o código desta página é executado e como você faz o deploy dele. A extensão do AI Inference que adapta um modelo com LoRA, e os modelos que a aceitam. - Os termos de AI Inference que esta página usa, definidos em um só lugar. + Onde id do modelo, `Azion.AI.run` e o restante do vocabulário do AI Inference são definidos. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen3-embedding-4b.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen3-embedding-4b.mdx index 639fef4d07..e45a31a9b7 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen3-embedding-4b.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/ai-models/qwen3-embedding-4b.mdx @@ -2,7 +2,7 @@ title: Qwen3 Embedding 4B description: >- Invoque Qwen3 Embedding 4B, um modelo de embedding multilíngue de 4B - parâmetros, e transforme texto em vetores para recuperação e classificação. + parâmetros, e transforme texto em vetores para recuperação, classificação e agrupamento. meta_tags: 'AI Inference, AI models, Qwen3 Embedding 4B, embedding model, vector embeddings, Azion.AI.run' namespace: docs_edge_ai_models_qwen_3_embedding_4b permalink: /documentacao/plataforma/ai-inference/qwen3-embedding-4b/ @@ -31,19 +31,19 @@ O id do modelo é a string que seleciona este modelo, e é o primeiro argumento ## Capacidades -A largura nativa de vetor do modelo é 2560, e o campo de requisição `dimensions` seleciona uma das larguras listadas abaixo. Para `dimensions`, `encoding_format` e o restante do corpo da requisição, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +Sem `dimensions`, o modelo retorna um vetor de largura 2560, a largura nativa dele. O campo de requisição `dimensions` seleciona uma das larguras menores listadas abaixo. Um valor fora da lista é aceito: 4096, que ainda retorna um vetor de largura 2560. Qualquer outro valor, inclusive 2560, é recusado com `AIError: validation error: Enum`. Para `dimensions`, `encoding_format` e o restante do corpo da requisição, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). | Capacidade | Valor | | --- | --- | | Dados de entrada | Texto | | Comprimento de contexto | 32k tokens | -| Dimensões de saída | 256, 512, 1024, 2048, 4096 | +| Dimensões de saída | 256, 512, 1024, 2048; 2560 sem `dimensions` | --- ## Uso -Uma [função](/pt-br/documentacao/plataforma/functions/) invoca o modelo com `Azion.AI.run`, passando o id como primeiro argumento e um corpo de requisição compatível com OpenAI como segundo. Os exemplos abaixo usam esse binding. Para enviar o mesmo corpo ao endpoint HTTP compatível com OpenAI, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +Uma [Function](/pt-br/documentacao/plataforma/functions/) invoca o modelo com `Azion.AI.run`, passando o id como primeiro argumento e um corpo de requisição compatível com OpenAI como segundo. Os exemplos abaixo usam esse binding. Por HTTP, uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve um endpoint que recebe o mesmo corpo, com o id no campo `model`. Para esse endpoint, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). ### Embedding @@ -64,17 +64,17 @@ O modelo responde com uma entrada em `data`, e o vetor fica em `data[0].embeddin "id": "embd-0123456789abcdef0123456789abcdef", "object": "list", "created": 1746821207, - "model": "Qwen/Qwen3-Embedding-4B", + "model": "qwen-qwen3-embedding-4b", "data": [ { "index": 0, "object": "embedding", - "embedding": [0.01, ..., 0.005] + "embedding": [-0.0009033476817421615, 0.020453155040740967, ..., -0.0008010818855836987] } ], "usage": { - "prompt_tokens": 11, - "total_tokens": 11, + "prompt_tokens": 9, + "total_tokens": 9, "completion_tokens": 0, "prompt_tokens_details": null } @@ -88,10 +88,8 @@ O modelo responde com uma entrada em `data`, e o vetor fica em `data[0].embeddin Todos os campos que um corpo de requisição aceita e o endpoint HTTP que recebe o mesmo corpo. - Onde os vetores que este modelo retorna são armazenados e consultados. - O produto que executa este modelo. - O produto cujo runtime contém o binding que os exemplos desta página chamam. + Onde os vetores que este modelo retorna são armazenados e consultados. As condições sob as quais a Azion encerra ou desprovisiona um modelo. - Onde id do modelo, comprimento de contexto e o restante do vocabulário do AI Inference são definidos. + Onde id do modelo, `Azion.AI.run` e o restante do vocabulário do AI Inference são definidos. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/boas-praticas.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/boas-praticas.mdx index 237f0aca85..46efde21d1 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/boas-praticas.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/boas-praticas.mdx @@ -1,8 +1,8 @@ --- -title: Boas práticas +title: Boas práticas para AI Inference description: >- - Proteja o endpoint que serve um modelo, copie o id que cada modelo declara e - decida o que alcança o modelo antes da chamada. + Proteja o endpoint que serve um modelo, escolha os modelos que ele alcança, + copie cada id e leia a resposta e os erros que uma chamada retorna. meta_tags: 'AI Inference, best practices, model id, authentication, Workload Domain, context length, optional chaining, Compute Time' namespace: docs_edge_ai_best_practices permalink: /documentacao/plataforma/ai-inference/boas-praticas/ @@ -11,61 +11,155 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Uma chamada de modelo é um código que pertence a você invocando um modelo que você não opera. Seu código escolhe qual modelo responde, o que chega até ele e o que o chamador recebe no fim. O modelo lê a requisição exatamente como ela chega, então as decisões que moldam uma resposta são tomadas antes da chamada. +O código que chama um modelo decide quem pode fazer a chamada, qual modelo responde, o que o modelo lê e o que o chamador recebe de volta. Cada uma dessas decisões é tomada no seu código, antes ou depois da chamada. Deixadas no padrão, um endpoint responde a qualquer um, um campo digitado errado não muda nada e não gera erro, e uma resposta lida de forma direta demais quebra no primeiro modelo que responde de outro jeito. -No [AI Inference](/pt-br/documentacao/plataforma/ai-inference/), o código que faz a chamada é uma [função](/pt-br/documentacao/plataforma/functions/), e a chamada é `Azion.AI.run`. Cada prática abaixo é uma das decisões que essa chamada deixa para você. Os valores em si pertencem a outras páginas. Os campos da requisição estão em [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/), e as condições que Azion aplica a um modelo estão em [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). O caminho que uma requisição percorre está em [Como AI Inference funciona](/pt-br/documentacao/plataforma/ai-inference/como-funciona/). +No [AI Inference](/pt-br/documentacao/plataforma/ai-inference/), esse código é uma [Function](/pt-br/documentacao/plataforma/functions/), e ela chama um modelo com `Azion.AI.run`. Os campos da requisição estão em [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/), as condições que Azion aplica a um modelo estão em [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/), e o caminho de uma requisição está em [Como AI Inference funciona](/pt-br/documentacao/plataforma/ai-inference/como-funciona/). -As seções seguem a ordem em que as decisões surgem: a autenticação que o endpoint não carrega, o id do modelo e as capacidades que um modelo declara. As duas últimas tratam da entrada que a função envia e da resposta que ela lê. +Em ordem, as práticas cobrem a checagem de cada requisição, os modelos que uma requisição alcança, o id do modelo, as capacidades de cada modelo, a grafia de cada campo, o tamanho da entrada e da saída, a leitura da resposta e os erros. Os espécimes são JavaScript para uma Function e corpos de requisição em JSON. --- -## A autenticação que o endpoint não carrega +## Confira cada requisição na Function antes de ela chamar um modelo + +O template [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) não configura nenhuma autenticação na frente do endpoint dele, e a regra dele executa a Function em todo path. Qualquer cliente que alcança o domínio pode, portanto, chamar um modelo, e cada chamada é cobrada em Compute Time e Requests. O custo de uma checagem é um segredo a guardar e um header que todo cliente envia. + +Esta Function recusa uma requisição cujo header `Authorization` não carrega o segredo, antes de `Azion.AI.run` rodar. O formato completo também carrega a checagem de modelo da próxima prática e o tratamento de erros da última: + +```js +const ALLOWED_MODELS = ["Qwen/Qwen3-30B-A3B-Instruct-2507-FP8"]; + +async function handleRequest(request) { + const secret = Azion.env.get("INFERENCE_SECRET"); + if (!secret || request.headers.get("Authorization") !== `Bearer ${secret}`) { + return new Response(JSON.stringify({ error: "Unauthorized" }), { + status: 401, + headers: { "Content-Type": "application/json" }, + }); + } + + const input = await request.json(); + const model = input["model"]; + if (!ALLOWED_MODELS.includes(model)) { + return new Response(JSON.stringify({ error: `${model} is not allowed` }), { + status: 403, + headers: { "Content-Type": "application/json" }, + }); + } + + try { + const modelResponse = await Azion.AI.run(model, input); + return new Response(JSON.stringify(modelResponse), { + headers: { "Content-Type": "application/json" }, + }); + } catch (e) { + console.error(`${e.name}: ${e.message}`); + if (e.message.includes("validation error")) { + return new Response(JSON.stringify({ error: `Invalid input for ${model}` }), { + status: 400, + headers: { "Content-Type": "application/json" }, + }); + } + if (e.message.includes("model not found")) { + return new Response(JSON.stringify({ error: `${model} not found or not allowed` }), { + status: 400, + headers: { "Content-Type": "application/json" }, + }); + } + return new Response(JSON.stringify({ error: "AI internal error" }), { + status: 500, + headers: { "Content-Type": "application/json" }, + }); + } +} + +addEventListener("fetch", (event) => { + event.respondWith(handleRequest(event.request)); +}); +``` + +`Azion.env.get` lê o segredo de uma variável de ambiente guardada na sua conta Azion, conforme [API de variáveis de ambiente](/pt-br/documentacao/devtools/runtime/api-reference/environment-variables/). Quando a variável não existe, a chamada retorna `undefined`, e a Function recusa todas as requisições. A checagem cobre todos os domínios do Workload: um domínio personalizado responde além do workload domain, e só o switch **Workload Domain Allow Access** do Workload fecha o workload domain. + +Para conferir, envie uma requisição sem o header: a Function responde `401`. -Uma aplicação implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) responde em um Workload Domain, na forma `xxxxxxxxxx.map.azionedge.net`, e serve nele um endpoint compatível com OpenAI. A autenticação nesse endpoint é inteiramente sua. Azion não emite nenhuma credencial para uma chamada de modelo nem exige uma. Uma requisição que alcança o domínio alcança a função, a menos que o seu próprio código a interrompa. +--- + +## Escolha na Function quais modelos uma requisição alcança + +A Function que o template instala passa o campo `model` do corpo da requisição para `Azion.AI.run` como ele chega. Um cliente pode, portanto, selecionar qualquer modelo que a conta pode chamar, inclusive um cujo contexto, capacidades ou consumo você nunca previu. O custo é uma lista a atualizar a cada modelo que você adota. + +Na Function da primeira prática, a lista é `const ALLOWED_MODELS = ["Qwen/Qwen3-30B-A3B-Instruct-2507-FP8"];`, e uma requisição que indica outro modelo recebe `403`. Para mapear nomes seus para ids de modelo, com uma chave por time, consulte [Rotear chamadas de modelo por uma Function de gateway](/pt-br/documentacao/guias/ai/inferencia/rotear-chamadas-de-modelo-por-uma-function-de-gateway/). + +Para conferir, envie uma requisição cujo `model` não está na lista: a Function responde `403`, e nenhum modelo roda. + +--- + +## Copie cada id de modelo da página do modelo, ou liste os ids com Azion.AI.models() + +Um modelo responde ao id dele e a nada mais: o primeiro argumento de `Azion.AI.run`, ou o campo `model` por HTTP, sem URL base nem host ao lado. Os ids não decorrem do nome do modelo. Duas formas podem selecionar o mesmo modelo, `Qwen/Qwen2.5-VL-3B-Instruct-AWQ` e `qwen-qwen25-vl-3b-instruct-awq`, e nenhuma regra simples transforma uma na outra: `Qwen2.5` vira `qwen25`. O GPT-OSS 20B responde a `openai/gpt-oss-20b`, enquanto `gpt-oss-20b` é recusado. -A consequência é o que uma aplicação implantada faz quando nada é acrescentado a ela. Ela responde a toda requisição que alcança o domínio, e cada requisição que o endpoint serve executa um modelo. Uma chamada de modelo consome Compute Time, a duração da execução ativa multiplicada pela memória alocada. Um endpoint aberto é, portanto, consumo que qualquer pessoa pode iniciar. Para a métrica e o valor cobrado, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#ai-inference). +Copie o id da página do modelo em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/), ou liste os ids que a sua conta pode chamar a partir de uma Function: -A verificação pertence à função, antes da chamada de modelo. A função recebe a requisição e a pré-processa, então ela é o lugar em que uma requisição pode ser rejeitada sem que um modelo seja executado. Associar um domínio personalizado no lugar do Workload Domain muda onde a aplicação responde, não o que ela verifica. +```js +const modelIds = await Azion.AI.models(); +``` + +Nunca use o campo `model` de uma resposta como id: ele carrega um id interno, e o GPT-OSS 20B retorna `gpt-oss-20b`, a forma que é recusada. + +Para conferir, execute a chamada uma vez: um id errado é recusado com `AIError: model not found or not allowed`. Uma conta sem acesso ao AI Inference recebe o mesmo erro, então confirme o acesso em [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/) primeiro. --- -## Ids de modelo, copiados em vez de derivados +## Envie a cada modelo somente as requisições que a página dele diz que ele serve -Um modelo é endereçado pelo seu id e por nada mais. O id é o primeiro argumento de `Azion.AI.run` e o campo `model` do corpo de uma requisição HTTP, e nenhuma URL base ou host o acompanha. +O que um modelo aceita pertence a esse modelo. Cada página em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/) declara o comprimento de contexto, de 8k a 131k tokens no catálogo, os tipos de entrada, somente texto ou texto e imagens, e a chamada de ferramentas: Sim, Só com a ferramenta nomeada ou Não. O servidor do modelo recusa um prompt maior que o contexto, e uma requisição com `tools` que deixa a escolha a um modelo cuja chamada de ferramentas não é Sim, com `Request failed with status 400`. A mensagem não diz qual valor causou a recusa. Quando uma página não declara nada, a capacidade é desconhecida, não ausente: confirme-a antes que o seu código dependa dela. -Os ids não compartilham uma forma única. `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` é o caminho do repositório do modelo, sem alteração. `casperhansen-mistral-small-24b-instruct-2501-awq` é o mesmo caminho com a barra substituída por um hífen. `qwen-qwen25-vl-3b-instruct-awq` está em minúsculas e também perdeu o ponto da versão. `gpt-oss-20b` descartou a organização por completo. +Por exemplo, o Qwen2.5 VL AWQ 3B e o 7B recusam uma requisição com `tools` que deixa a escolha para o modelo, e retornam `tool_calls` quando o corpo indica a ferramenta: `"tool_choice": {"type": "function", "function": {"name": "get_weather"}}`. O custo é uma checagem por modelo no seu código, já que a plataforma informa a incompatibilidade só como um status. -Nenhuma regra transforma o nome de um modelo no seu id. Um id montado a partir do nome está certo para alguns modelos do catálogo e errado para outros. O erro é uma string, e é por isso que ele parece correto. Copie o id da própria página do modelo em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/), onde cada página declara o id que alcança aquele modelo. +Para conferir, leia a capacidade na página do modelo sempre que uma chamada falhar com status `400`. --- -## As capacidades que um modelo declara para si +## Escreva cada campo da requisição como Invocação de modelos o lista -O que um modelo aceita é uma propriedade daquele modelo, e não do AI Inference. Cada página em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/) declara o seu próprio comprimento de contexto, os tipos de entrada que aceita e se suporta chamada de ferramentas. O catálogo não é uniforme em nenhum dos três. Os comprimentos de contexto vão de 8k tokens a 131k tokens. Alguns modelos aceitam apenas texto, e outros aceitam texto e imagens. A chamada de ferramentas é declarada como suportada em algumas páginas e não suportada em outras. +Um campo que o modelo não conhece é ignorado, sem erro. Um campo escrito errado, portanto, não muda nada na resposta, e nada avisa que ele não foi aplicado. O custo é uma conferência em [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) sempre que você acrescenta um campo. -Uma requisição que não corresponde é uma requisição que o modelo não consegue servir. Uma imagem enviada a um modelo que aceita apenas texto é uma delas. Um prompt mais longo que o contexto que o modelo aceita é outra. As duas são decididas no seu código antes da chamada, que é onde elas podem ser verificadas. +Um corpo que define a temperatura de amostragem a escreve `"temperature": 0.7`. Escrito como `"temprature": 0.7`, o campo é ignorado, e a requisição roda como se não tivesse temperatura. -Onde a página de um modelo não declara nada para uma capacidade, nada sobre aquela capacidade está declarado. Leia um campo em branco como desconhecido, e não como um sim ou um não, e confirme antes que um código dependa dele. +Para conferir, envie o campo uma vez com um valor além do limite dele, como `"temperature": 2.1`: um campo escrito certo é recusado com `validation error: Maximum`, e um escrito errado retorna uma resposta normal. --- -## A entrada decidida antes da chamada +## Envie ao modelo somente a entrada de que ele precisa e limite a saída + +Tudo o que um modelo lê vem da sua Function, na mesma execução que aguarda a resposta. O modelo lê o prompt inteiro, e o tempo que ele leva para gerar é tempo que a Function espera. Essa espera não conta no limite de 2 segundos de CPU da Function, mas conta no tempo de execução de 5 minutos dela, que é tempo de relógio, conforme [Limites de Functions](/pt-br/documentacao/plataforma/functions/limites/). AI Inference cobra Compute Time e Requests, e o Compute Time, a duração da execução ativa multiplicada pela memória alocada, cresce com uma geração mais longa. + +Envie a seção de um documento que responde à pergunta, não o documento inteiro, e defina `max_tokens` em todo corpo, como `"max_tokens": 1024`. O custo é uma margem a manter: o GPT-OSS 20B raciocina antes de responder, e com um `max_tokens` pequeno o raciocínio pode usar todo o orçamento e retornar `content` igual a `null`. + +Para conferir, leia `usage.prompt_tokens` e `usage.completion_tokens` na resposta antes e depois de mudar um prompt. + +--- + +## Leia a resposta com optional chaining e confira por que ela parou + +O texto gerado por um modelo de chat fica quatro níveis dentro da resposta, em `choices[0].message.content`, e esse texto nem sempre está lá. `content` é `null` quando o modelo retorna `tool_calls`, e no GPT-OSS 20B quando o raciocínio usa todo o `max_tokens`. Com `stream` igual a `true`, `Azion.AI.run` resolve para um iterador assíncrono de chunks, sem nenhum `choices[0].message`. -Tudo o que um modelo lê foi montado pela sua função, na mesma execução que faz a chamada. O pré-processamento fica de um lado de `Azion.AI.run` e a formatação da resposta do outro, e os dois são código que você escreveu. +Leia cada nível com optional chaining, para que um nível ausente retorne `undefined` em vez de lançar um erro dentro da Function: -A chamada é aguardada, então o tempo que o modelo passa gerando é tempo que a função passa esperando. O tamanho do que você envia faz parte disso. Um prompt que carrega um documento inteiro onde uma seção bastaria é lido por completo, dentro de uma execução medida enquanto ela acontece. +```js +const summary = modelResponse?.choices?.[0]?.message?.content?.trim(); +``` -Restringir a entrada é feito antes da chamada, em vez de corrigido depois dela. A resposta declara o que a requisição consumiu: `usage.prompt_tokens` carrega os tokens lidos da requisição, e `usage.total_tokens` carrega a requisição e a resposta juntas. Esses dois campos são a forma de medir uma mudança em um prompt. Para os campos da resposta, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +O custo é um desvio para o caso vazio. Para conferir, leia `choices[0].finish_reason` sempre que o texto vier vazio: `tool_calls` significa que o modelo escolheu uma ferramenta, e `length` significa que o `max_tokens` acabou. --- -## Optional chaining na resposta do modelo +## Distinga os três tipos de falha pela mensagem -Ler o texto que um modelo de chat gerou significa percorrer quatro níveis dentro de um objeto: `choices`, a sua primeira entrada, o `message` dessa entrada e o `content` dele. As funções de exemplo que Azion publica os percorrem como `modelResponse?.choices?.[0]?.message?.content`, com optional chaining em cada nível. +Uma chamada a `Azion.AI.run` que falha rejeita com um erro que carrega somente `name` e `message`, sem `code` nem `status`. A mensagem distingue os casos. `AIError: model not found or not allowed` cobre um id que não existe e uma conta sem acesso. `AIError: validation error` cobre um corpo que não corresponde ao schema do modelo, antes de o modelo rodar. `Error: Request failed with status ` cobre uma recusa do servidor do modelo, sem motivo. -A resposta não é idêntica para todo modelo e toda chamada. Ela carrega campos que apenas alguns modelos retornam, como o conteúdo de raciocínio e as probabilidades logarítmicas. Ler os níveis com optional chaining é o que impede que um nível ausente encerre a leitura. +A Function da primeira prática desvia pela mensagem: `e.message.includes("validation error")` e `e.message.includes("model not found")` respondem `400`, e qualquer outro erro responde `500`. Ela também escreve cada erro com `console.error`. O custo é que uma recusa do servidor do modelo chega ao chamador sem causa, então a Function não consegue dizer ao chamador o que mudar. Para todos os erros e as causas deles, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#erros). -A diferença está em onde uma falha cai. Com optional chaining, a função recebe `undefined` e decide o que o chamador obtém; sem ele, a própria leitura falha dentro da função. Uma das funções de exemplo que Azion publica encadeia `?.trim()` na mesma leitura, de modo que o valor é normalizado onde é obtido. +Para conferir, abra [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/): a fonte de dados Functions Console carrega as linhas que a Function escreve com `console.error`, mensagens `AIError` incluídas. --- @@ -73,13 +167,9 @@ A diferença está em onde uma falha cai. Com optional chaining, a função rece - O id a copiar e as capacidades que cada modelo declara para si. - Os campos da requisição que uma chamada aceita e o objeto de resposta que ela retorna. - As condições em que Azion encerra ou desprovisiona um modelo. - O que executa um modelo, e onde a parte de Azion termina e a sua começa. - Implante uma aplicação e envie uma primeira requisição a um modelo. - Os tetos da função dentro da qual uma chamada de modelo é executada. - Como o consumo de AI Inference é medido e cobrado. - Onde perguntar qual valor se aplica quando uma página não declara nenhum. + Todos os campos da requisição, o objeto de resposta e cada erro que uma chamada retorna. + A página de cada modelo, com o id e o contexto, a entrada e as ferramentas que ele serve. + Implante o template que serve o endpoint que estas práticas protegem. + Como Compute Time e Requests são medidos e cobrados. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/como-funciona.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/como-funciona.mdx index 3563959fc1..cedcf7ce9f 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/como-funciona.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/como-funciona.mdx @@ -3,7 +3,7 @@ title: Como AI Inference funciona description: >- Acompanhe uma chamada de modelo da requisição que chega até a resposta que retorna e veja onde termina a parte da Azion e começa a sua. -meta_tags: 'AI Inference, how it works, Azion.AI.run, invocation chain, Azion Cells, Orchestrator, OpenAI-compatible endpoint, model call' +meta_tags: 'AI Inference, how it works, Azion.AI.run, invocation chain, Workloads, Applications, Functions, OpenAI-compatible endpoint, model call' namespace: docs_edge_ai_how_it_works permalink: /documentacao/plataforma/ai-inference/como-funciona/ --- @@ -14,7 +14,7 @@ import DocItem from '@aziontech/webkit/doc-item' Quando uma aplicação precisa que um modelo responda algo, ela envia a entrada e mantém a requisição aberta enquanto o modelo gera uma resposta. Em seguida, ela retorna essa resposta a quem chamou. Toda chamada de modelo tem essa forma. O que muda de uma plataforma para outra é onde o modelo executa e quanto dele você opera. -[AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa os modelos, e quem chama um modelo é uma [função](/pt-br/documentacao/plataforma/functions/). A função alcança um modelo através de `Azion.AI.run`, o binding de runtime que recebe um id de modelo e um corpo de requisição no formato da OpenAI. A chamada acontece dentro da execução da função, então um único trecho do seu código contém tanto a requisição que chegou quanto a resposta que o modelo produziu. +[AI Inference](/pt-br/documentacao/plataforma/ai-inference/) é um recurso da plataforma que executa modelos de AI, e uma [Function](/pt-br/documentacao/plataforma/functions/) chama um modelo com `Azion.AI.run`. Esse binding de runtime recebe um id de modelo e um corpo de requisição. A chamada acontece dentro da execução da Function, então um único trecho do seu código contém tanto a requisição que chegou quanto a resposta que o modelo produziu. Três assuntos adjacentes têm páginas próprias. [LoRA Fine-Tune](/pt-br/documentacao/plataforma/ai-inference/lora-fine-tune/) é a extensão que adapta um modelo com LoRA, e nomeia os modelos que a aceitam. Os vetores que um modelo de embedding retorna são armazenados e consultados com [Vector Search](/pt-br/documentacao/plataforma/sql-database/vector-search/) no SQL Database. Para conhecer o corpo da requisição campo a campo, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). @@ -24,37 +24,42 @@ Os mecanismos são a chamada de modelo em si, a cadeia de invocação, o binding ## A chamada de modelo -Uma chamada de modelo começa no código que você implanta. `Azion.AI.run` é o binding de runtime que a faz, e recebe dois argumentos: o id do modelo e o corpo da requisição no formato da OpenAI. A chamada é assíncrona, então a função a aguarda e lê a resposta do modelo no valor resolvido. Para um modelo de chat, o texto gerado fica em `choices[0].message.content` dentro dessa resposta. +Uma chamada de modelo começa no código que você implanta. `Azion.AI.run` é o binding de runtime que a faz, e recebe dois argumentos: o id do modelo e o corpo da requisição. A chamada é assíncrona, então a Function a aguarda e lê a resposta do modelo no valor resolvido. Para um modelo de chat, o texto gerado fica em `choices[0].message.content` dentro dessa resposta. -O id é o único endereço de que o código precisa. Azion não publica nenhum endpoint de inferência próprio, então uma função não configura nenhuma URL base e não nomeia nenhum host para alcançar um modelo. Os ids de modelo não seguem uma forma única: alguns são um caminho de repositório, como `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`, e outros uma string em minúsculas, como `gpt-oss-20b`. Copie o id da própria página do modelo em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/) em vez de derivá-lo do nome do modelo. +O id é o único endereço que o código passa: `Azion.AI.run` não recebe nenhuma URL base, nenhum host e nenhuma credencial. Os ids de modelo não seguem uma forma única: alguns são um caminho de repositório, como `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`, e outros uma string em minúsculas, como `qwen-qwen25-vl-3b-instruct-awq`. Copie o id da própria página do modelo em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/) em vez de derivá-lo do nome do modelo, ou liste os ids que a sua conta pode chamar com `Azion.AI.models()`. Uma chamada é recusada com `AIError: model not found or not allowed` quando o id não existe ou quando a conta não tem acesso ao modelo, e o erro não diz qual dos dois. -Em torno da chamada, a função é código comum. Ela pré-processa a entrada antes de invocar o modelo e formata o que o modelo retorna antes que quem chamou veja. A mesma execução pode recuperar contexto de um armazenamento e alcançar um serviço externo. A recuperação, a chamada e a formatação da resposta acontecem dentro de uma requisição. +Em torno da chamada, a Function é código comum. Ela pode pré-processar a entrada antes de invocar o modelo e formatar o que o modelo retorna antes que quem chamou veja. A mesma execução também pode recuperar contexto de um armazenamento e alcançar um serviço externo, tudo dentro de uma requisição. --- ## A cadeia de invocação -Este diagrama traça uma requisição, do usuário até o modelo e de volta. Cada seta é uma passagem de uma parte da plataforma para a seguinte, e cada parte é nomeada na lista que segue. +Este diagrama traça uma requisição, do cliente até o modelo e de volta. As setas sólidas levam a requisição, e as setas pontilhadas levam a resposta. Cada rótulo começa com o número do seu passo abaixo. ```mermaid -%%{init: {"layout": "elk", "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% +%%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% flowchart TD - User(["Usuário"]) -->|"Requisição ao domínio da aplicação"| DC["Data center mais próximo"] - DC -->|"Encaminha a requisição"| App["A aplicação aplica suas políticas"] - App -->|"Chama a função"| Fn["A função pré-processa a entrada"] - Fn -->|"Azion.AI.run"| Cells["API do Azion Cells, parte do Orchestrator"] - Cells --> Model["AI Inference executa o modelo"] - Model -->|"A resposta volta pelo mesmo caminho"| User + Client(["Cliente"]) + WL["Workload"] + App["Application"] + Fn["Function"] + AI["AI Inference"] + Client -->|"1. requisição"| WL + WL -->|"1. requisição"| App + App -->|"2. Run Function"| Fn + Fn -->|"3. Azion.AI.run"| AI + AI -.->|"4. resposta do modelo"| Fn + Fn -.->|"5. resposta"| App + App -.->|"5. resposta"| Client ``` -Leia o diagrama como quatro movimentos: +1. A requisição chega a um data center perto do cliente por um domínio de um [Workload](/pt-br/documentacao/plataforma/workloads/). O deployment desse Workload define a Application que recebe a requisição. +2. Uma regra da Application executa a Function com o behavior _Run Function_. +3. A Function chama o modelo com `Azion.AI.run`, passando o id do modelo e o corpo da requisição. +4. AI Inference executa o modelo e retorna a resposta do modelo para a Function. +5. A Function monta a resposta dela a partir da resposta do modelo, e a Application a entrega ao cliente. -1. O usuário envia uma requisição ao domínio da aplicação. -2. O data center mais próximo recebe a requisição e a encaminha para a aplicação, que aplica suas políticas e chama a função. -3. A função orquestra a inferência. Ela pré-processa a entrada e chama o modelo com `Azion.AI.run`, através da API do Azion Cells. -4. A resposta volta ao usuário pelo mesmo caminho. - -Cinco partes sustentam essa cadeia. [Applications](/pt-br/documentacao/plataforma/applications/) é a camada de aplicação que recebe a requisição e aplica políticas a ela. Functions executa a lógica de inferência: orquestra a recuperação, integra serviços externos e emite a chamada de modelo. AI Inference executa os modelos, e a função que os chama é executada no [Azion Runtime](/pt-br/documentacao/devtools/runtime/). [Orchestrator](/pt-br/documentacao/plataforma/orchestrator/) gerencia as requisições para a execução no Azion Cells, e Azion Cells é a parte do Orchestrator que o binding alcança. A infraestrutura distribuída da Azion é onde tudo isso executa, e por isso o data center que responde é o mais próximo do usuário. +Quatro recursos da plataforma sustentam essa cadeia, na infraestrutura distribuída da Azion. Workloads recebe a requisição, e o deployment do Workload define a Application. [Applications](/pt-br/documentacao/plataforma/applications/) executa a regra que chama a Function. Functions executa o código que chama o modelo, no [Azion Runtime](/pt-br/documentacao/devtools/runtime/). AI Inference executa o modelo. --- @@ -62,11 +67,11 @@ Cinco partes sustentam essa cadeia. [Applications](/pt-br/documentacao/plataform Uma requisição alcança um modelo por uma de duas interfaces, e as duas terminam no mesmo binding. -A primeira é o próprio binding. Dentro de uma função, o código chama `Azion.AI.run`, e nada fica entre esse código e a chamada de modelo. A função decide qual modelo responde, o que o corpo da requisição carrega e o que acontece antes e depois. +A primeira é o próprio binding. Dentro de uma Function, o código chama `Azion.AI.run` diretamente. A Function decide qual modelo responde, o que o corpo da requisição carrega e o que acontece antes e depois. -A segunda é um endpoint HTTP compatível com OpenAI, e o mecanismo por trás dele é que Azion não o hospeda. O host é a aplicação que você implanta, então o endpoint é mais uma coisa que essa aplicação serve, no domínio em que ela responde. [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) traz o caminho, a forma do domínio e a requisição que o endpoint aceita. +A segunda é um endpoint HTTP compatível com OpenAI que uma Application implantada por você serve no domínio dela. O template [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) implanta uma Application desse tipo. [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) traz o caminho, a forma do domínio e a requisição que o endpoint aceita. -Atrás do endpoint ainda existe uma função, e ela chama `Azion.AI.run` como qualquer outra função. A segunda interface é, portanto, a primeira com uma aplicação à frente, publicada em um formato de requisição que os clientes já falam. Esse endpoint não carrega autenticação da Azion e Azion não emite nenhuma credencial para ele, então qualquer verificação que ele faça é uma que sua aplicação define. +Atrás do endpoint ainda existe uma Function, e ela chama `Azion.AI.run` como qualquer outra Function. Na Function que o template instala, o campo `model` do corpo da requisição seleciona o modelo, e a Function passa o corpo inteiro para o binding. A segunda interface é, portanto, a primeira com uma Application à frente, publicada em um formato de requisição que os clientes já falam. O template não configura nenhuma autenticação na frente do endpoint, então qualquer verificação que ele faça é uma que você acrescenta à sua Application. --- @@ -74,21 +79,23 @@ Atrás do endpoint ainda existe uma função, e ela chama `Azion.AI.run` como qu A cadeia de invocação cruza uma linha entre o que Azion opera e o que você implanta. Onde essa linha cai é o que indica de qual lado um problema está. -Azion executa os modelos e tudo que está abaixo deles: os próprios modelos, o hardware que os executa e a orquestração que coloca uma chamada no Azion Cells. Você não carrega nenhum modelo, não dimensiona nenhum cluster e não mantém nenhum servidor de inferência em execução. Você também não seleciona qual data center atende uma dada requisição, porque a requisição é respondida pelo mais próximo. +Azion executa os modelos e a infraestrutura que os executa. Você não carrega nenhum modelo, não dimensiona nenhum cluster e não mantém nenhum servidor de inferência em execução. Você também não seleciona qual data center atende uma requisição: a Azion a encaminha para um data center perto do cliente. + +É seu tudo que decide o que se pergunta ao modelo. A Function é o seu código: o tratamento da entrada, o prompt, o id do modelo, o corpo da requisição e a resposta que quem chamou recebe ao final. A Application à frente da Function também é sua, junto com o domínio em que o seu Workload responde e a autenticação que a Application verifica. Quando uma resposta está errada, comece pela entrada que sua Function enviou. -É seu tudo que decide o que se pergunta ao modelo. A função é o seu código: o tratamento da entrada, o prompt, o id do modelo, o corpo da requisição e a resposta que quem chamou recebe ao final. A aplicação à frente da função também é sua, junto com o domínio em que ela responde e a autenticação que ela verifica. Quando uma resposta está errada, a entrada que sua função enviou é o primeiro lugar a olhar, porque o modelo respondeu exatamente a ela. +Os modelos também têm termos próprios. Um modelo pode estar sujeito a termos de licença de terceiros, e você é responsável por cumpri-los e pela saída que o modelo gera. A Azion não verifica a precisão dessa saída. --- ## O que essa arquitetura custa -Executar um modelo de dentro de uma função mantém a requisição e a chamada de modelo em uma única execução. Três coisas pagam por isso. +Executar um modelo de dentro de uma Function mantém a requisição e a chamada de modelo em uma única execução. Três coisas pagam por isso. -A chamada de modelo acontece dentro de uma execução. A função a aguarda, então o tempo que o modelo leva para gerar é tempo que a função passa esperando, e a requisição fica aberta para os dois. Uma função que chama um modelo é, portanto, limitada por dois conjuntos de valores ao mesmo tempo: os seus próprios, em [Limites de Functions](/pt-br/documentacao/plataforma/functions/limites/), e os do modelo, em [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). +A chamada de modelo acontece dentro de uma execução. A Function a aguarda, então o tempo que o modelo leva para gerar é tempo que a Function passa esperando, e a requisição fica aberta para os dois. Essa espera conta no tempo de execução da Function, que é tempo de relógio, e não no tempo de CPU dela. Os limites da própria Function estão em [Limites de Functions](/pt-br/documentacao/plataforma/functions/limites/), e as condições que a Azion aplica a um modelo estão em [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). -Azion também limita o lado do modelo. Azion pode encerrar um modelo que consome mais do que a memória máxima definida, ou que executa por mais tempo do que o tempo máximo permitido. Um modelo que é criado e depois não é executado por mais de três dias pode ser desprovisionado. Para saber o que cada uma dessas condições cobre, consulte [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). +Azion também limita o lado do modelo. Azion pode encerrar, sem aviso prévio, um modelo que consome mais do que a memória máxima definida, ou que executa por mais tempo do que o tempo máximo permitido. Um modelo que é criado e depois não é executado por mais de três dias pode ser desprovisionado. Para saber o que cada uma dessas condições cobre, consulte [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). -O endpoint compatível com OpenAI é um formato que sua aplicação serve, não um serviço que Azion opera para você. Você constrói a aplicação que o expõe, você a mantém em execução e você a protege. Azion não entrega nenhum endpoint gerenciado para apontar um cliente. O endpoint é seu para mudar, e seu para manter respondendo. +O endpoint compatível com OpenAI é um formato que sua Application serve. Você implanta a Application que o expõe, você a mantém em execução e você a protege, então o endpoint é seu para mudar e seu para manter respondendo. --- @@ -97,11 +104,8 @@ O endpoint compatível com OpenAI é um formato que sua aplicação serve, não Todos os campos que o corpo da requisição aceita, nas duas interfaces. - Implante uma aplicação e envie uma primeira requisição a um modelo. - O id a passar e o que cada modelo declara sobre si. + Implante uma Application e envie uma primeira requisição a um modelo. As condições em que Azion encerra ou desprovisiona um modelo. - O runtime que contém o binding e os limites que restringem uma chamada. - A forma implantada em torno de uma chamada de modelo, em que sua aplicação é o endpoint de inferência. - Como o consumo de AI Inference é medido e cobrado. + A forma implantada em torno de uma chamada de modelo, em que sua Application é o endpoint de inferência. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/edge-ai-reference.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/edge-ai-reference.mdx index 35b389d1f7..d0d0943456 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/edge-ai-reference.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/edge-ai-reference.mdx @@ -1,8 +1,8 @@ --- title: AI Inference description: >- - Chame um modelo de linguagem, de visão, de embedding ou de reranking de dentro - de uma função com Azion.AI.run, em infraestrutura que você não provisiona. + Execute um modelo de linguagem, de visão, de embedding ou de reranking a + partir de uma Function com Azion.AI.run, sem infraestrutura para provisionar. meta_tags: 'AI Inference, AI models, Azion.AI.run, inference, LLM, VLM, embedding model, reranker, OpenAI-compatible API, Azion Runtime' namespace: docs_edge_ai_reference permalink: /documentacao/plataforma/ai-inference/ @@ -11,18 +11,51 @@ import DocButton from '~/components/webkit/DocButton.vue'; import DocCardGroup from '@aziontech/webkit/doc-card-group' import DocCard from '@aziontech/webkit/doc-card' -Inferência é o ato de executar um modelo de AI treinado. Você envia uma entrada e o modelo retorna uma saída calculada a partir dos pesos que ele aprendeu no treinamento: um texto gerado, um ranking ou um vetor de números que representa a entrada. Um modelo não responde nada enquanto esses pesos não estiverem carregados em memória, em hardware dimensionado para eles. Um serviço de inferência assume essa parte, mantendo os modelos carregados e colocando cada um atrás de uma requisição. +**AI Inference** é um recurso da plataforma que executa modelos de AI open source na infraestrutura distribuída da Azion, em resposta às chamadas que as suas [Functions](/pt-br/documentacao/plataforma/functions/) enviam. Executar um modelo treinado sobre uma entrada se chama inferência: o modelo calcula uma saída a partir dos pesos que aprendeu no treinamento. Essa saída pode ser um texto gerado, um ranking ou um vetor de números que representa a entrada. Um modelo só responde depois que os pesos dele estão em memória, em hardware dimensionado para eles. Um serviço de inferência mantém os modelos em memória, então você não provisiona hardware para eles. -**AI Inference** executa os modelos na infraestrutura distribuída da Azion, no [Azion Runtime](/pt-br/documentacao/devtools/runtime/). Um modelo não é um objeto que você cria. Você nomeia um modelo pelo id dele dentro de uma [função](/pt-br/documentacao/plataforma/functions/), e essa chamada é o que o invoca. Use AI Inference para gerar texto a partir de um prompt ou para ler o texto de uma imagem. Você também pode usá-lo para transformar um documento em um vetor para recuperação ou para ranquear um conjunto de documentos em relação a uma consulta. +Uma Function passa um id de modelo e um corpo de requisição para `Azion.AI.run` e depois aguarda a resposta do modelo. Use AI Inference para gerar texto a partir de um prompt, extrair o texto de uma imagem, converter um documento em um vetor para recuperação ou ranquear um conjunto de documentos em relação a uma consulta. - + --- -## Chamada de modelo +## Caminho da requisição -Uma função alcança um modelo por meio de `Azion.AI.run`, o binding do runtime que recebe o id do modelo e um corpo de requisição compatível com OpenAI: +Uma Function chama um modelo enquanto trata uma requisição, então a requisição fica aberta até a resposta do modelo voltar. O diagrama acompanha uma requisição do cliente até o modelo e de volta. + +As setas sólidas levam a requisição, e as setas pontilhadas levam a resposta. Cada rótulo começa com o número do seu passo abaixo. + +```mermaid +%%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% +flowchart TD + Client(["Cliente"]) + WL["Workload"] + App["Application"] + Fn["Function"] + AI["AI Inference"] + Client -->|"1. requisição"| WL + WL -->|"1. requisição"| App + App -->|"2. Run Function"| Fn + Fn -->|"3. Azion.AI.run"| AI + AI -.->|"4. resposta do modelo"| Fn + Fn -.->|"5. resposta"| App + App -.->|"5. resposta"| Client +``` + +1. A requisição chega a um data center perto do cliente por um domínio do seu [Workload](/pt-br/documentacao/plataforma/workloads/). O deployment desse Workload define a [Application](/pt-br/documentacao/plataforma/applications/) que a recebe. +2. Uma regra da Application executa a Function com o behavior _Run Function_. +3. A Function passa o id do modelo e o corpo da requisição para `Azion.AI.run`. +4. AI Inference executa o modelo e retorna a resposta dele para a Function. +5. A Function monta a resposta dela a partir da resposta do modelo, e a Application a entrega ao cliente. + +Workloads recebe a requisição, Applications executa a regra e Functions executa o seu código no [Azion Runtime](/pt-br/documentacao/devtools/runtime/). Para ver qual lado desse caminho a Azion opera e qual lado é seu, consulte [Como AI Inference funciona](/pt-br/documentacao/plataforma/ai-inference/como-funciona/). + +--- + +## Código da Function + +Este código de Function envia uma requisição de chat a um modelo e lê o texto gerado: ```ts const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { @@ -36,63 +69,41 @@ const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", const answer = modelResponse?.choices?.[0]?.message?.content ``` -- O primeiro argumento é o id do modelo, a string à qual o modelo responde. Os ids não seguem uma forma única, então copie o id declarado na página do próprio modelo em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). -- O segundo argumento é o corpo da requisição. `messages` carrega a conversa e campos como `stream`, `max_tokens` e `temperature` moldam a saída. Todos os campos que um corpo aceita estão em [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). -- A chamada é assíncrona. A função a aguarda e o texto gerado fica em `choices[0].message.content` no valor resolvido. -- O id seleciona o modelo e o código não nomeia nenhum host, nenhuma URL base nem nenhuma credencial. +- `Azion.AI.run` recebe primeiro o id do modelo: a string à qual um modelo responde. Os ids não seguem um padrão único, então copie cada um da página do modelo em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). +- O corpo da requisição vem em segundo. `messages` guarda a conversa, e campos como `stream`, `max_tokens` e `temperature` controlam a saída. [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) lista todos os campos que um corpo aceita. +- `Azion.AI.run` retorna uma promise. A Function a aguarda e encontra o texto gerado em `choices[0].message.content` do valor resolvido. +- O código não passa nenhum host, nenhuma URL base e nenhuma credencial: o id do modelo é o único endereço. -Se você já escreveu código para o formato de chat completions da OpenAI, o corpo da requisição e o objeto de resposta são os que você já conhece, e o binding é o que muda. - ---- - -## Caminho de invocação - -Uma chamada de modelo não sai da requisição que a iniciou. A função que já está tratando a requisição é a que chama o modelo, então a chamada é um passo dentro de uma execução, e não uma ida e volta a um serviço separado. - -```mermaid -%%{init: {"layout": "elk", "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% -flowchart TD - User(["Usuário"]) -->|"Requisição para o domínio da aplicação"| DC["Data center mais próximo"] - DC --> App["A aplicação aplica as suas políticas"] - App --> Fn["A função chama Azion.AI.run"] - Fn --> Cells["Azion Cells API, parte do Orchestrator"] - Cells --> Model["AI Inference executa o modelo"] - Model -->|"A resposta volta pelo mesmo caminho"| User -``` - -1. Um usuário envia uma requisição para o domínio da sua aplicação. -2. O data center mais próximo recebe a requisição e a encaminha para a aplicação, que aplica as suas políticas e chama a função. -3. A função pré-processa a entrada e chama o modelo com `Azion.AI.run`, por meio da Azion Cells API. -4. A resposta volta para o usuário pelo mesmo caminho. - -Quatro produtos sustentam essa cadeia. [Applications](/pt-br/documentacao/plataforma/applications/) recebe a requisição e aplica políticas a ela, [Functions](/pt-br/documentacao/plataforma/functions/) executa o código que faz a chamada, [Orchestrator](/pt-br/documentacao/plataforma/orchestrator/) coloca a chamada na Azion Cells e AI Inference executa o modelo. Para a mesma cadeia com a linha traçada entre o que a Azion opera e o que é seu, consulte [Como AI Inference funciona](/pt-br/documentacao/plataforma/ai-inference/como-funciona/). +Um corpo de requisição ou um objeto de resposta escrito para o formato de chat completions da OpenAI é lido da mesma forma aqui, e só a chamada que o envia muda. --- ## Escopo e limites -- **Modelos**: AI Inference executa um catálogo de modelos open source. Ele reúne large language models, vision language models que leem texto e imagens, um modelo de embedding e um reranker. Cada página de modelo declara o id ao qual o modelo responde e as capacidades que ele suporta. Para o catálogo, consulte [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). -- **Tamanho do contexto**: um valor por modelo, de 8k tokens a 131k tokens no catálogo. Dimensione um prompt em relação ao modelo que você chama, e não em relação ao catálogo. -- **Entrada**: todos os modelos leem texto. Os modelos cuja entrada também cobre imagens leem uma imagem passada como URL, em uma parte de conteúdo da mensagem. -- **Interfaces**: duas delas alcançam os mesmos modelos. Uma função chama `Azion.AI.run` diretamente, ou uma aplicação que você implanta serve um endpoint compatível com OpenAI em `/v1/chat/completions` no domínio dela e chama o binding por trás dele. As duas carregam o mesmo corpo de requisição, documentado em [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). -- **Gerenciamento**: AI Inference não tem uma superfície de gerenciamento própria nem uma API própria. Você não cria, não configura nem implanta um modelo. Você chama um modelo pelo id de dentro de uma função, então a função é o objeto que você cria e gerencia, pelas interfaces que [Functions](/pt-br/documentacao/plataforma/functions/) declara. -- **Adaptação de modelos**: adaptar um modelo a uma tarefa com Low-Rank Adaptation é [LoRA Fine-Tune](/pt-br/documentacao/plataforma/ai-inference/lora-fine-tune/), uma extensão do AI Inference. As páginas de modelo declaram quais modelos aceitam essa adaptação. -- **Vetores**: um modelo de embedding retorna vetores e [SQL Database](/pt-br/documentacao/plataforma/sql-database/) os armazena e consulta. As consultas semânticas e híbridas de que um fluxo de retrieval-augmented generation se serve estão em [Vector Search](/pt-br/documentacao/plataforma/sql-database/vector-search/). -- **Encerramento**: a Azion pode encerrar um modelo que consome mais do que a memória máxima definida ou que roda por mais tempo do que o tempo máximo permitido. Um modelo criado e depois não executado por mais de três dias pode ser desprovisionado. Para o que cada condição cobre, consulte [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). -- **Observabilidade**: uma chamada de modelo roda dentro de uma função, em uma aplicação, então o que ela fez em produção é lido onde esse tráfego é lido. [Real-Time Metrics](/pt-br/documentacao/plataforma/real-time-metrics/) reporta o tráfego, e [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/) carrega as requisições e os logs. -- **Cobrança**: para saber como o consumo de uma chamada de modelo é medido e cobrado, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#ai-inference). - -Azion não hospeda nenhum endpoint de inferência e não emite nenhuma credencial para uma chamada de modelo. O endpoint compatível com OpenAI pertence a uma aplicação que você implanta, e a autenticação na frente dele é você quem define. +- **Acesso**: nos planos Hobby e Pro, AI Inference está disponível sob solicitação, sujeito a aprovação. Para o acesso que cada plano dá, consulte [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). +- **Modelos**: o catálogo reúne large language models open source, vision language models que leem texto e imagens, um modelo de embedding e um reranker. Cada página de modelo declara o id a passar e as capacidades que o modelo suporta, e `Azion.AI.models()` retorna os ids que a sua conta pode chamar. Para a lista completa, consulte [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). +- **Tamanho do contexto**: o contexto que um modelo aceita varia por modelo, de 8k a 131k tokens no catálogo. Confira a página do modelo que você chama antes de dimensionar um prompt. +- **Entrada**: todos os modelos aceitam texto. Um modelo que também aceita imagens lê cada imagem a partir de uma URL, dentro de uma parte de conteúdo da mensagem. +- **Streaming**: com `stream` definido como `true`, o modelo transmite a resposta em partes em vez de retorná-la inteira. O endpoint do AI Inference Starter Kit repassa essa transmissão como server-sent events, uma linha `data:` por parte, terminando com `data: [DONE]`. +- **Interfaces**: uma Function chama `Azion.AI.run`, que não recebe nenhuma credencial. Por HTTP, uma Application implantada a partir do template [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve um endpoint compatível com OpenAI no domínio dela. O campo `model` do corpo da requisição seleciona o modelo, e o template não configura nenhuma autenticação na frente do endpoint. As duas interfaces carregam o corpo de requisição que [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) documenta. +- **Teste local**: sob `azion dev`, `Azion.AI` é `undefined`, então teste as chamadas de modelo em uma Function publicada. Para o erro que a chamada local lança, consulte [API de AI Inference](/pt-br/documentacao/devtools/runtime/api-reference/ai/). +- **Gerenciamento**: o Azion Console não tem uma tela de AI Inference, e nem a API v4 da Azion nem a Azion CLI têm uma operação para AI Inference ou para os modelos dele. A entidade que você cria e gerencia é a Function que chama um modelo, pelas interfaces que [Functions](/pt-br/documentacao/plataforma/functions/) documenta. +- **Adaptação de modelos**: [LoRA Fine-Tune](/pt-br/documentacao/plataforma/ai-inference/lora-fine-tune/), uma extensão do AI Inference, adapta um modelo a uma tarefa com Low-Rank Adaptation. Cada página de modelo declara se o modelo a aceita. +- **Vetores**: [SQL Database](/pt-br/documentacao/plataforma/sql-database/) armazena e consulta os vetores que um modelo de embedding retorna. [Vector Search](/pt-br/documentacao/plataforma/sql-database/vector-search/) cobre a busca semântica que um fluxo de retrieval-augmented generation executa sobre eles. +- **Encerramento**: a Azion pode encerrar um modelo, sem aviso prévio, quando ele consome mais do que a memória máxima definida ou executa por mais tempo do que o tempo máximo permitido. Um modelo criado e não executado por mais de três dias pode ser desprovisionado. [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/) cobre cada condição. +- **Termos dos modelos**: um modelo pode estar sujeito a termos de licença de terceiros, e você é responsável por cumpri-los e pela saída que o modelo gera. A Azion não verifica a precisão dessa saída. +- **Observabilidade**: como uma chamada de modelo roda dentro de uma Function em uma Application, o tráfego dela aparece onde aparece o tráfego dessa Application. [Real-Time Metrics](/pt-br/documentacao/plataforma/real-time-metrics/) o reporta, e [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/) carrega as requisições e os logs de console da Function, incluindo as mensagens `AIError`. +- **Cobrança**: [Preços](/pt-br/documentacao/fundamentos/precos/#ai-inference) informa como uma chamada de modelo é medida e cobrada. --- ## Próximos passos - + - - - + + + diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/glossario.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/glossario.mdx index be11f6d1db..a746e445a3 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/glossario.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/glossario.mdx @@ -1,24 +1,23 @@ --- title: Glossário description: >- - Consulte o significado de cada termo usado na documentação de AI Inference, de - Azion.AI.run e Azion Cells a Compute Time e Workload Domain. + Consulte os termos que a documentação de AI Inference usa, de Azion.AI.run e + do id do modelo a Compute Time e ao workload domain. meta_tags: 'ai inference, glossary, terms, definitions, azion.ai.run, model id, compute time, workload domain' namespace: docs_edge_ai_glossary permalink: /documentacao/plataforma/ai-inference/glossario/ --- -Os termos abaixo são o vocabulário da documentação de [AI Inference](/pt-br/documentacao/plataforma/ai-inference/), e cada definição traz o link da página que apresenta o termo. +Definições dos termos que a documentação de **AI Inference** usa. | Termo | Definição | | --- | --- | -| AI Inference | O produto que executa modelos de inteligência artificial na infraestrutura distribuída global da Azion em resposta a uma requisição. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) chama cada modelo por meio de `Azion.AI.run`, de dentro de uma [função](/pt-br/documentacao/plataforma/functions/), portanto você não provisiona infraestrutura para executar um modelo. | -| AI Inference Starter Kit | O template que implanta uma aplicação com uma API compatível com OpenAI na frente de AI Inference. [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) cria a aplicação e a função que chama o modelo, e a aplicação responde em um Workload Domain. | -| Azion Cells | A funcionalidade de [Orchestrator](/pt-br/documentacao/plataforma/orchestrator/) pela qual AI Inference executa um modelo. Uma chamada a `Azion.AI.run` alcança o modelo por meio da Azion Cells API. | -| Azion Runtime | O ambiente de execução do JavaScript de uma [função](/pt-br/documentacao/plataforma/functions/), construído sobre padrões Web. A função que chama um modelo é executada em [Azion Runtime](/pt-br/documentacao/devtools/runtime/). | -| `Azion.AI.run` | O binding de runtime que uma [função](/pt-br/documentacao/plataforma/functions/) chama para executar um modelo. Ele recebe o id do modelo e um corpo de requisição e retorna o objeto que o modelo produz, como `choices[0].message.content` para um modelo de chat. [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) documenta cada campo do corpo. | -| Compute Time | O medidor de uso da execução de um modelo, expresso em GB-hora. Para AI Inference e LoRA Fine-Tune, é o tempo de execução ativa em horas multiplicado pela memória alocada em gigabytes. A [página de preços](/pt-br/documentacao/fundamentos/precos/#ai-inference) informa a tarifa. | -| id do modelo | A string que identifica um modelo para `Azion.AI.run`, passada como o primeiro argumento dele. Duas convenções estão em uso: o caminho do repositório no HuggingFace, como `Qwen/Qwen3-Embedding-4B`, e uma forma em minúsculas sem barra, como `gpt-oss-20b`. Cada [página de modelo](/pt-br/documentacao/plataforma/ai-inference/modelos/) indica o id a usar para aquele modelo. | -| LoRA Fine-Tune | O recurso da plataforma que estende [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) com o fine-tuning de modelos suportados por meio de Low-Rank Adaptation. [LoRA Fine-Tune](/pt-br/documentacao/plataforma/ai-inference/lora-fine-tune/) é executado na infraestrutura da Azion, e as [páginas dos modelos](/pt-br/documentacao/plataforma/ai-inference/modelos/) indicam quais modelos o suportam. | -| OpenAI-compatible API | O formato de requisição e de resposta que AI Inference aceita para um modelo de chat, equivalente ao formato de chat completions da OpenAI. O endpoint que serve esse formato pertence à aplicação que você mesmo implanta, em um Workload Domain, e AI Inference não publica um endpoint próprio. [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) traz o corpo da requisição e a resposta. | -| Workload Domain | O hostname somente leitura que a Azion atribui a um [workload](/pt-br/documentacao/plataforma/workloads/) na criação, no formato `xxxxxxxxxx.map.azionedge.net`. Uma aplicação implantada a partir de [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve o próprio endpoint compatível com OpenAI nesse domínio. Um domínio personalizado responde junto com ele. | +| AI Inference | Um recurso da plataforma que executa modelos de AI open source na infraestrutura distribuída da Azion, em resposta às chamadas que as suas Functions enviam. Uma [Function](/pt-br/documentacao/plataforma/functions/) chama um modelo com `Azion.AI.run`, então você não provisiona infraestrutura para executar um. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) descreve o caminho da requisição e o escopo. | +| AI Inference Starter Kit | Um template do Azion Console que implanta uma Application que serve uma API compatível com OpenAI, com a Function que chama o modelo. O [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) também cria o Workload e o deployment dele, e a API responde no workload domain. | +| Azion Runtime | O runtime JavaScript de [Functions](/pt-br/documentacao/plataforma/functions/), que executa o handler de uma Function na infraestrutura distribuída da Azion. `Azion.AI.run` é uma das APIs da Azion desse runtime, então a Function que chama um modelo executa no [Azion Runtime](/pt-br/documentacao/devtools/runtime/). | +| `Azion.AI.run` | O binding de runtime que uma Function chama para executar um modelo. Ele recebe o id do modelo e um corpo de requisição, e nenhuma credencial, e resolve no objeto de resposta, como um `chat.completion` para um modelo de chat, ou num iterador de partes quando `stream` é `true`. [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) documenta cada campo. | +| Compute Time | O medidor de uso de AI Inference e de LoRA Fine-Tune: a duração da execução ativa em horas multiplicada pela memória alocada em gigabytes, expressa em GB-hora. A [página de preços](/pt-br/documentacao/fundamentos/precos/#ai-inference) informa a tarifa. | +| id do modelo | A string que seleciona um modelo: o primeiro argumento de `Azion.AI.run`, ou o campo `model` do corpo de uma requisição HTTP. Duas formas selecionam o mesmo modelo, um caminho de repositório como `Qwen/Qwen3-Embedding-4B` e uma forma em minúsculas como `qwen-qwen3-embedding-4b`. Cada [página de modelo](/pt-br/documentacao/plataforma/ai-inference/modelos/) indica um id a usar, e `Azion.AI.models()` retorna os ids que a sua conta pode chamar. | +| LoRA Fine-Tune | Um recurso da plataforma que estende [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) com o fine-tuning de modelos suportados por meio de Low-Rank Adaptation, na infraestrutura da Azion. As [páginas de modelo](/pt-br/documentacao/plataforma/ai-inference/modelos/) indicam quais modelos o suportam, e [LoRA Fine-Tune](/pt-br/documentacao/plataforma/ai-inference/lora-fine-tune/) o descreve. | +| OpenAI-compatible API | O endpoint HTTP que uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve no domínio dela. Ele recebe um corpo de requisição no formato de chat completions da OpenAI, com o id do modelo em `model`, e o repassa para `Azion.AI.run`. [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) documenta o corpo e a resposta. | +| workload domain | O hostname somente leitura que a Azion atribui a um [Workload](/pt-br/documentacao/plataforma/workloads/) na criação, no formato `.map.azionedge.net` na infraestrutura de produção. Uma Application implantada a partir do AI Inference Starter Kit serve a API compatível com OpenAI nesse domínio. O [glossário de Workloads](/pt-br/documentacao/plataforma/workloads/glossario/) o define por completo. | diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/invocacao-de-modelos.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/invocacao-de-modelos.mdx index be769b35c2..35bfd82129 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/invocacao-de-modelos.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/invocacao-de-modelos.mdx @@ -1,7 +1,7 @@ --- title: Invocação de modelos description: >- - Envie uma requisição a um modelo do AI Inference a partir de uma função ou por + Envie uma requisição a um modelo do AI Inference a partir de uma Function ou por HTTP e consulte os campos que o corpo da requisição aceita. meta_tags: 'AI Inference, model invocation, Azion.AI.run, chat completions, request schema, messages, embeddings, reranking' namespace: docs_edge_ai_model_invocation @@ -12,15 +12,23 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Você invoca um modelo com duas coisas: o id do modelo e um corpo de requisição compatível com OpenAI. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) aceita essa requisição por duas interfaces, e as duas alcançam os mesmos modelos. Você chama o binding `Azion.AI.run` dentro de uma [função](/pt-br/documentacao/plataforma/functions/), ou envia uma requisição POST para o endpoint HTTP compatível com OpenAI servido pela aplicação que você implanta. Os campos da requisição são os mesmos nas duas interfaces. +Você invoca um modelo com duas coisas: o id do modelo e um corpo de requisição no formato que o modelo recebe. Para um modelo de chat, esse corpo segue o formato de chat completions da OpenAI. [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) aceita essa requisição por duas interfaces, e as duas alcançam os mesmos modelos. Você chama o binding `Azion.AI.run` dentro de uma [Function](/pt-br/documentacao/plataforma/functions/), ou envia uma requisição POST para o endpoint HTTP compatível com OpenAI que uma Application implantada a partir de um template serve. Os campos da requisição são os mesmos nas duas interfaces, e por HTTP o corpo também carrega o id do modelo. ## O binding Azion.AI.run -`Azion.AI.run` é o binding de runtime que uma função chama para invocar um modelo. Ele recebe o id do modelo e o corpo da requisição que esta página descreve, e a chamada é assíncrona. O binding pertence ao runtime, e não ao AI Inference, então os parâmetros, a chamada e o valor de retorno dele estão documentados com os outros bindings do runtime, em [AI Inference API](/pt-br/documentacao/devtools/runtime/api-reference/ai/). +`Azion.AI.run` é o binding de runtime que uma Function chama para invocar um modelo. Ele recebe primeiro o id do modelo e depois o corpo da requisição que esta página descreve, e a chamada é assíncrona. O primeiro argumento decide o modelo, então o corpo não precisa do id, e um campo `model` no corpo é ignorado. O binding não recebe credencial, URL base nem host. O binding pertence ao runtime, e não ao AI Inference, então os parâmetros, a chamada e o valor de retorno dele estão documentados com os outros bindings do runtime, em [AI Inference API](/pt-br/documentacao/devtools/runtime/api-reference/ai/). + +`Azion.AI.models()` retorna uma promise que resolve para um array com os ids de modelo que a sua conta pode chamar: + +```ts +const modelIds = await Azion.AI.models() +``` ## O endpoint HTTP -O endpoint HTTP aceita uma requisição POST para `/v1/chat/completions` com um corpo JSON. Azion não hospeda esse endpoint. O host é a aplicação que você implanta, que responde no Workload Domain do workload que a serve, na forma `xxxxxxxxxx.map.azionedge.net`, ou em um domínio personalizado desse workload. Uma aplicação implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve o endpoint nesse domínio. +Uma Application implantada a partir do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/) serve o endpoint nos domínios do Workload dela: o workload domain, na forma `xxxxxxxxxx.map.azionedge.net`, ou um domínio personalizado desse Workload. A Function que o template instala lê o id do modelo no campo `model` do corpo e passa o corpo inteiro para `Azion.AI.run`. + +O endpoint recebe uma requisição `POST` com um corpo JSON que carrega `model`, em qualquer path do domínio. `/v1/chat/completions` é o path que os clientes da OpenAI usam, e o mesmo endpoint também serve corpos de embedding e de reranking. O header `Content-Type` precisa ser exatamente `application/json`: um header que acrescenta um parâmetro `charset` é recusado. O template não configura nenhuma autenticação na frente do endpoint. Quando você adiciona autenticação à sua Application, inclua o header que ela exige, por exemplo `-H "Authorization: Bearer [TOKEN VALUE]"`. Uma requisição a um modelo de chat por HTTP: @@ -28,45 +36,104 @@ Uma requisição a um modelo de chat por HTTP: curl -X POST https:///v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ - "model": "Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", - "max_tokens": 500, + "model": "qwen-qwen25-vl-3b-instruct-awq", + "max_tokens": 16, "messages": [ - { "role": "user", "content": "Name three European capitals." } + { "role": "user", "content": "Name one European capital." } ] }' ``` -Azion não emite nenhuma credencial para uma chamada de modelo, e o endpoint não carrega autenticação da Azion. A autenticação é o que você adiciona à sua própria aplicação. Quando sua aplicação exige um header, inclua-o na requisição, por exemplo `-H "Authorization: Bearer [TOKEN VALUE]"`. +O endpoint retorna o objeto que o modelo retorna: + +```json +{ + "id": "chatcmpl-0cb926279c564d868e3e3e8a2fc20313", + "object": "chat.completion", + "created": 1794444659, + "model": "qwen-qwen25-vl-3b-instruct-awq", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "Paris, France is a European capital.", + "refusal": null, + "annotations": null, + "audio": null, + "function_call": null, + "tool_calls": [], + "reasoning_content": null + }, + "logprobs": null, + "finish_reason": "stop", + "stop_reason": null + } + ], + "service_tier": null, + "system_fingerprint": null, + "usage": { + "prompt_tokens": 24, + "total_tokens": 33, + "completion_tokens": 9, + "prompt_tokens_details": null + }, + "prompt_logprobs": null, + "kv_transfer_params": null +} +``` --- ## Campos da requisição -Estes campos formam o corpo de uma requisição a um modelo de chat, seja pelo binding, seja por HTTP. Por HTTP, o corpo também carrega um campo `model` com o id do modelo. Pelo binding, o primeiro parâmetro carrega o id e o corpo não o repete. Cada modelo de chat indica a [OpenAI Chat API](https://developers.openai.com/api/reference/overview) como o endpoint com o qual é compatível, então um campo se comporta como esse schema descreve. Os tipos, os padrões e os limites abaixo são os que AI Inference declara. Um traço na coluna Padrão significa que o schema não define padrão para o campo. +Estes campos formam o corpo de uma requisição a um modelo de chat, seja pelo binding, seja por HTTP. Por HTTP, o corpo também carrega um campo `model` com o id do modelo. Pelo binding, o primeiro parâmetro carrega o id. Cada modelo de chat indica a [OpenAI Chat API](https://developers.openai.com/api/reference/overview) como o endpoint com o qual é compatível. Os tipos, os padrões e os limites abaixo são os que o schema de requisição dos modelos de chat declara. Um traço na coluna Padrão significa que o schema não define padrão para o campo. | Campo | Tipo | Obrigatório | Padrão | Descrição | | --- | --- | --- | --- | --- | -| `messages` | array | Sim | — | A conversa enviada ao modelo. Cada entrada é um objeto de mensagem de system, user ou assistant. | +| `messages` | array | Sim | — | A conversa enviada ao modelo. Cada entrada é um objeto de mensagem de system, user, assistant ou tool. | | `temperature` | number | Não | — | Temperatura de amostragem. Mínimo `0`, máximo `2`. | -| `top_p` | number | Não | `1` | Valor de amostragem top-p. Mínimo `0`, máximo `1`. | +| `top_p` | number | Não | — | Valor de amostragem top-p. Máximo `1`. | | `n` | integer | Não | `1` | Número de respostas a gerar. Mínimo `1`. | | `stream` | boolean | Não | `false` | Envia a resposta em stream em vez de retorná-la inteira. Aceita `true` ou `false`. | -| `max_tokens` | integer | Não | — | Número máximo de tokens que o modelo gera. Mínimo `1`. | -| `presence_penalty` | number | Não | `0` | Penalidade de presença aplicada à saída. Mínimo `-2`, máximo `2`. | -| `frequency_penalty` | number | Não | `0` | Penalidade de frequência aplicada à saída. Mínimo `-2`, máximo `2`. | -| `tools` | array | Não | — | As definições de ferramentas que o modelo pode chamar, em um modelo que declara Tool calling entre suas capacidades. As páginas dos modelos que a suportam mostram o formato. | +| `max_tokens` | integer | Não | — | Número máximo de tokens que o modelo gera para cada resposta. Mínimo `1`. | +| `presence_penalty` | number | Não | — | Penalidade de presença aplicada à saída. Máximo `2`. | +| `frequency_penalty` | number | Não | — | Penalidade de frequência aplicada à saída. Máximo `2`. | +| `tools` | array | Não | — | As definições de ferramentas que o modelo pode chamar. As páginas dos modelos que a suportam mostram o formato. | + +Um valor além de um mínimo ou de um máximo é recusado com `validation error: Minimum` ou `validation error: Maximum` antes de o modelo rodar. O validador também aceita `top_p` até `0` e as duas penalidades até `-2`, mas o servidor do modelo recusa uma requisição que define `temperature` e `top_p` como `0` e as duas penalidades como `-2` ao mesmo tempo. Com `n` igual a `2`, `choices` carrega duas entradas, e `max_tokens` vale para cada uma. + +Um campo que o modelo não conhece é ignorado, sem erro. Um nome de campo escrito errado, portanto, não muda nada na resposta: confira cada nome com as tabelas desta página. O context length, o tool calling e os tipos de entrada que um modelo aceita são valores por modelo, e não fazem parte deste schema. Para o modelo que você chama, consulte [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). -## Objetos de mensagem +### Escolha de ferramenta, seed, parada e log probabilities -Cada entrada do array `messages` é um objeto de mensagem, e o campo `role` indica qual dos três objetos ela é. Cada objeto exige `role` e `content`. O campo `role` é um enum com um único valor, então o objeto e o role são a mesma escolha. O campo `content` recebe texto como string ou, em um modelo que aceita imagens, um array de partes de conteúdo. +Os modelos de chat também aceitam os campos abaixo, que o schema de requisição não lista. As descrições valem para o Qwen3 30B A3B Instruct 2507 FP8. -| Role | Objeto do schema | Campos obrigatórios | +| Campo | Tipo | Descrição | | --- | --- | --- | -| `system` | `SystemMessage` | `role`, `content` | -| `user` | `UserMessage` | `role`, `content` | -| `assistant` | `AssistantMessage` | `role`, `content` | +| `tool_choice` | string ou object | Como o modelo escolhe uma ferramenta: `auto`, `none`, `required` ou um objeto que indica uma função. | +| `seed` | integer | Uma semente de amostragem: a mesma requisição com o mesmo `seed` pode retornar a mesma saída. | +| `stream_options` | object | Opções de uma resposta em stream, como `{"include_usage": true}`. Exige `stream` igual a `true`. | +| `logprobs` | boolean | Com `true`, preenche `choices[].logprobs` com a log probability de cada token gerado. | +| `top_logprobs` | integer | O número de tokens alternativos listados para cada token gerado, com `logprobs` igual a `true`. | +| `stop` | array de strings | Sequências que encerram a geração antes de serem escritas. | + +`auto` é o comportamento sem `tool_choice`, `required` força uma chamada de ferramenta e `none` impede `tool_calls`. Com `none`, o Qwen3 30B ainda pode escrever a chamada como texto em `content`. No Qwen2.5 VL AWQ 3B e no 7B, um objeto que indica a ferramenta retorna `tool_calls`, com `finish_reason` igual a `stop`. Um `seed` que não é inteiro, um `tool_choice` fora desses valores e `stream_options` sem `stream` são recusados com `Request failed with status 400`. + +Com `logprobs`, cada entrada de `choices[].logprobs.content` carrega `token`, `logprob`, `bytes` e `top_logprobs`. Com `stop`, a resposta termina antes da sequência, e `finish_reason` é `stop`. + +## Objetos de mensagem + +Cada entrada do array `messages` é um objeto de mensagem, e o campo `role` indica qual dos quatro objetos ela é. O campo `content` recebe texto como string ou, em um modelo que aceita imagens, um array de partes de conteúdo. + +| Role | Campos obrigatórios | +| --- | --- | +| `system` | `role`, `content` | +| `user` | `role`, `content` | +| `assistant` | `role`, `content`; `content` é `null` quando a mensagem carrega `tool_calls` | +| `tool` | `role`, `tool_call_id`, `content` | Um array `messages` que carrega um turno anterior: @@ -81,6 +148,33 @@ Um array `messages` que carrega um turno anterior: } ``` +Quando um modelo chama uma ferramenta, a resposta dele carrega `tool_calls`, com `content` igual a `null` e `finish_reason` igual a `tool_calls`. Para devolver o resultado, envie a conversa de novo com a mensagem do assistant como o modelo a retornou, seguida de uma mensagem `tool`. O `tool_call_id` dessa mensagem é o `id` da chamada de ferramenta, e o `content` dela carrega o resultado. O modelo então responde em texto. Um array `messages` que devolve o resultado de uma ferramenta, enviado com o mesmo array `tools` da primeira requisição: + +```json +{ + "messages": [ + { "role": "system", "content": "You are a helpful assistant with access to tools." }, + { "role": "user", "content": "What is the weather in London?" }, + { + "role": "assistant", + "content": null, + "tool_calls": [ + { + "id": "chatcmpl-tool-789b0d0737f84d09b61eee169a3bea75", + "type": "function", + "function": { "name": "get_weather", "arguments": "{\"location\": \"London\"}" } + } + ] + }, + { + "role": "tool", + "tool_call_id": "chatcmpl-tool-789b0d0737f84d09b61eee169a3bea75", + "content": "{\"temperature_c\": 14, \"condition\": \"light rain\"}" + } + ] +} +``` + Um modelo que aceita imagens recebe `content` como um array de partes de conteúdo em vez de uma string. Cada parte indica o seu `type` e carrega o campo que esse tipo usa. As páginas dos modelos que aceitam imagens mostram esse formato; um modelo somente de texto recebe a string. | Parte de conteúdo | Tipo | Carrega | @@ -88,7 +182,7 @@ Um modelo que aceita imagens recebe `content` como um array de partes de conteú | `type` | string | Qual é o tipo desta parte: `text` ou `image_url`. | | `text` | string | O texto da parte, quando `type` é `text`. | | `image_url` | object | A imagem da parte, quando `type` é `image_url`. | -| `image_url.url` | string | A URL de onde o modelo lê a imagem. | +| `image_url.url` | string | Uma URL `https` que serve a imagem, ou uma URL `data:` com a imagem em base64. | Um array `content` que carrega texto e uma imagem: @@ -97,39 +191,65 @@ Um array `content` que carrega texto e uma imagem: "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, - { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } + { "type": "image_url", "image_url": { "url": "" } } ] } ``` -Para saber se um modelo aceita imagens, consulte os tipos de entrada na página dele em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). +A URL precisa servir uma imagem que o modelo consiga buscar. Uma URL que não serve imagem falha com `Request failed with status 500`, que não indica a imagem como causa. Para saber se um modelo aceita imagens, consulte os tipos de entrada na página dele em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). + +--- + +## Respostas em stream + +Com `stream` igual a `true`, as duas interfaces entregam a resposta em chunks, cada um um objeto `chat.completion.chunk`. O texto de cada chunk fica em `choices[0].delta.content`, e o último chunk de texto carrega `finish_reason`. + +- **Pelo binding**, `Azion.AI.run` resolve para um iterador assíncrono de objetos de chunk já interpretados, que a Function lê com `for await`. Nenhum item `[DONE]` chega ao iterador. +- **Por HTTP**, o endpoint responde com `Content-Type: text/event-stream`, uma linha `data:` por chunk e uma linha final `data: [DONE]`. + +`usage` chega somente quando o corpo define `stream_options` como `{"include_usage": true}`. Ele vem em um chunk a mais no fim, cujo array `choices` é vazio: + +```json +{ + "id": "chatcmpl-2d0e9241b82048c49b9f946c746818b1", + "object": "chat.completion.chunk", + "created": 1794443931, + "model": "qwen-qwen3-30b-a3b-instruct-2507-fp8", + "choices": [], + "usage": { + "prompt_tokens": 20, + "total_tokens": 30, + "completion_tokens": 10 + } +} +``` --- ## Requisições de embedding -Um modelo de embedding recebe um corpo de requisição que o schema de chat não define. `input` carrega o texto a converter em embedding e é o único campo obrigatório. Os outros dois definem o vetor retornado, e cada um aceita um conjunto fixo de valores; um valor fora do conjunto não faz parte do schema. +Um modelo de embedding recebe um corpo de requisição que o schema de chat não define. `input` carrega o texto a converter em embedding e é o único campo obrigatório. Os outros dois definem o vetor retornado, e cada um aceita um conjunto fixo de valores. Um valor fora do conjunto é recusado com `validation error: Enum`. | Campo | Tipo | Obrigatório | Descrição | | --- | --- | --- | --- | -| `input` | string ou array | Sim | O texto a converter em embedding. Um array contém strings, integers ou arrays de integers. | +| `input` | string ou array de strings | Sim | O texto a converter em embedding. Um array retorna um embedding por string. | | `encoding_format` | string | Não | A codificação do embedding na resposta: `float` ou `base64`. | | `dimensions` | integer | Não | O tamanho do vetor que o modelo retorna: `256`, `512`, `1024`, `2048` ou `4096`. | -Para armazenar os vetores que um modelo de embedding retorna e consultá-los, consulte [Vector Search](/pt-br/documentacao/plataforma/sql-database/vector-search/). +Sem `dimensions`, o Qwen3 Embedding 4B retorna um vetor de 2560 números. Com `dimensions` igual a `4096`, a requisição é aceita e o vetor continua com 2560 números. Com `base64`, o embedding é uma string que decodifica em floats de 32 bits little-endian, 4 bytes por dimensão. Os vetores vêm normalizados para comprimento 1. + +Para armazenar os vetores que um modelo de embedding retorna e consultá-los, consulte [Vector search](/pt-br/documentacao/plataforma/sql-database/vector-search/). ## Requisições de reranking -Uma requisição de reranking não carrega um array `messages`. Em vez disso, ela carrega um de dois pares de entrada, e cada par contém um valor único e uma coleção a ser pontuada contra esse valor. Uma requisição usa um par ou o outro, e o schema indica `query` e `documents` como o par obrigatório. +Uma requisição de reranking não carrega um array `messages`. Ela carrega uma consulta e os documentos a classificar em relação a ela, e os dois são obrigatórios. | Campo | Tipo | Carrega | | --- | --- | --- | | `query` | string | A consulta contra a qual os documentos são classificados. | | `documents` | array de strings | Os documentos a classificar por relevância em relação a `query`. | -| `text_1` | string | O primeiro texto que o modelo processa. | -| `text_2` | array de strings | Os textos que o modelo pontua em relação a `text_1`. | -| `top_n` | integer | Declarado pelo schema, que não indica padrão nem limites. | -| `max_tokens_per_doc` | integer | Declarado pelo schema, que não indica padrão nem limites. | +| `top_n` | integer | O número de resultados a retornar, das maiores pontuações para as menores. | +| `max_tokens_per_doc` | integer | Declarado pelo schema, que não indica padrão nem limites. Aceito, sem efeito documentado. | --- @@ -137,6 +257,8 @@ Uma requisição de reranking não carrega um array `messages`. Em vez disso, el Um modelo retorna um objeto, qualquer que seja a interface que carregou a requisição. O formato depende do que o modelo faz, e os três abaixo cobrem todos os modelos do catálogo. As páginas dos modelos mostram um payload completo para os modelos que têm um. +O campo `model` carrega o id interno do modelo na conta, em minúsculas com hífens, que pode ser diferente do id que a requisição enviou. Uma requisição a `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` retorna `qwen-qwen3-30b-a3b-instruct-2507-fp8`, e o GPT-OSS 20B retorna `gpt-oss-20b`, um id que `Azion.AI.run` recusa como entrada. Não use o campo `model` de uma resposta como id. + Um modelo de chat retorna um objeto `chat.completion`: | Campo | Tipo | Carrega | @@ -144,23 +266,28 @@ Um modelo de chat retorna um objeto `chat.completion`: | `id` | string | O identificador desta completion. | | `object` | string | `chat.completion`. | | `created` | integer | Quando a completion foi criada. | -| `model` | string | O id do modelo que respondeu. | +| `model` | string | O id interno do modelo que respondeu. | | `choices` | array | As respostas geradas, uma entrada por resposta solicitada em `n`. | | `choices[].index` | integer | A posição da entrada em `choices`. | | `choices[].message` | object | A mensagem gerada. | | `choices[].message.role` | string | `assistant`. | -| `choices[].message.content` | string | O texto gerado. É daqui que uma resposta de chat é lida. | -| `choices[].message.reasoning_content` | string | O raciocínio que o modelo retornou, quando ele retorna algum. | -| `choices[].message.tool_calls` | array | As ferramentas que o modelo escolheu chamar, em um modelo que declara Tool calling entre suas capacidades. | -| `choices[].finish_reason` | string | Por que a geração parou, como `stop` ou `tool_calls`. | -| `choices[].stop_reason` | string | A condição de parada que encerrou a geração. | -| `choices[].logprobs` | object | As log probabilities, quando o modelo as retorna. | +| `choices[].message.content` | string ou null | O texto gerado. É daqui que uma resposta de chat é lida. | +| `choices[].message.reasoning_content` | string ou null | O raciocínio que o modelo retornou, quando ele retorna algum. | +| `choices[].message.reasoning` | string ou null | O mesmo raciocínio, no Qwen3 30B e no GPT-OSS 20B. | +| `choices[].message.tool_calls` | array | As ferramentas que o modelo escolheu chamar. | +| `choices[].finish_reason` | string | Por que a geração parou, como `stop`, `length` ou `tool_calls`. | +| `choices[].stop_reason` | string, integer ou null | A condição de parada que encerrou a geração. | +| `choices[].logprobs` | object ou null | As log probabilities, quando a requisição define `logprobs`. | | `usage` | object | Os tokens que a requisição e a resposta consumiram. | | `usage.prompt_tokens` | integer | Os tokens lidos da requisição. | | `usage.completion_tokens` | integer | Os tokens gerados na resposta. | | `usage.total_tokens` | integer | Os dois somados. | -| `usage.prompt_tokens_details` | object | O detalhamento dos tokens do prompt. | -| `prompt_logprobs` | object | As log probabilities do prompt, quando o modelo as retorna. | +| `usage.prompt_tokens_details` | object ou null | O detalhamento dos tokens do prompt. | +| `prompt_logprobs` | object ou null | As log probabilities do prompt, quando o modelo as retorna. | + +`content` é `null` quando a mensagem carrega `tool_calls`. Ele também pode ser `null` no GPT-OSS 20B, que preenche `reasoning_content` primeiro: com um `max_tokens` pequeno, o raciocínio pode usar todo o orçamento, e `finish_reason` é `length`. + +Uma resposta de chat também carrega campos que esta tabela não descreve: `refusal`, `annotations`, `audio` e `function_call` na mensagem; `token_ids` em cada choice no Qwen3 30B; e `service_tier`, `system_fingerprint`, `prompt_token_ids` e `kv_transfer_params` no nível de cima. Um modelo de embedding retorna um objeto `list` cujo array `data` contém um embedding por entrada: @@ -169,38 +296,63 @@ Um modelo de embedding retorna um objeto `list` cujo array `data` contém um emb | `id` | string | O identificador desta resposta. | | `object` | string | `list`. | | `created` | integer | Quando a resposta foi criada. | -| `model` | string | O id do modelo que respondeu. | +| `model` | string | O id interno do modelo que respondeu. | | `data` | array | Os embeddings, um por entrada. | | `data[].index` | integer | A posição da entrada em `data`. | | `data[].object` | string | `embedding`. | -| `data[].embedding` | array de números | O vetor, do tamanho selecionado em `dimensions`. | -| `usage` | object | Os tokens que a requisição consumiu. | +| `data[].embedding` | array de números ou string | O vetor, ou a string base64 dele quando `encoding_format` é `base64`. | +| `usage` | object | Os tokens que a requisição consumiu: `prompt_tokens`, `total_tokens`, `completion_tokens` e `prompt_tokens_details`. | Um modelo de reranking retorna os resultados classificados: | Campo | Tipo | Carrega | | --- | --- | --- | | `id` | string | O identificador desta resposta. | -| `model` | string | O id do modelo que respondeu. | +| `model` | string | O id interno do modelo que respondeu. | | `results` | array | As entradas classificadas, da maior pontuação para a menor. | -| `results[].index` | integer | A posição que a entrada ocupava na coleção de entrada. | +| `results[].index` | integer | A posição que a entrada ocupava em `documents`. | | `results[].document` | object | A entrada que foi classificada. | | `results[].document.text` | string | O texto dessa entrada. | +| `results[].document.multi_modal` | null | Um campo que o reranker retorna sem valor. | | `results[].relevance_score` | number | O quanto o modelo julgou a entrada relevante. | | `usage.total_tokens` | integer | Os tokens que a requisição consumiu. | --- +## Erros + +`Azion.AI.run` rejeita com um objeto de erro que carrega somente `name` e `message`, sem campo `code` nem `status`. Leia `message` para distinguir os casos: + +| Erro | Causa | O que fazer | +| --- | --- | --- | +| `AIError: model not found or not allowed` | O id do modelo não existe, ou a conta não tem acesso ao AI Inference. A mensagem não diz qual. | Copie o id da página do modelo, ou liste os ids com `Azion.AI.models()`. Para o acesso, consulte [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). | +| `AIError: validation error: {path: ""}` | O corpo não corresponde ao schema do modelo. O modelo não roda. | Corrija o campo que `path` indica. | +| `Error: Request failed with status ` | O servidor do modelo recusou uma requisição que passou na validação. A mensagem não traz o motivo. | Confira os valores que o servidor do modelo recusa, listados abaixo. | + +O `` da validação é `Required` para um campo ausente, `WrongType` para um valor do tipo errado, com um `detail` como `The value must be integer`, `Minimum` ou `Maximum` para um valor além de um limite, `Enum` para um valor fora de um conjunto fixo, ou `OneOf` para uma mensagem que não corresponde a nenhum objeto de mensagem. + +O servidor do modelo recusa estes casos com status `400`: um prompt maior que o contexto que o modelo serve, que a mensagem não indica como causa; `temperature` e `top_p` em `0` com as duas penalidades em `-2`; uma requisição com `tools` sem `tool_choice` no Qwen2.5 VL AWQ 3B, no Qwen2.5 VL AWQ 7B ou no Nanonets-OCR-s; um `seed` que não é inteiro; um `tool_choice` desconhecido; e `stream_options` sem `stream`. Uma `image_url` que não serve imagem falha com status `500`. + +O endpoint do AI Inference Starter Kit retorna os próprios erros como um corpo JSON com um campo `error`: + +| Status | Corpo | Causa | +| --- | --- | --- | +| `400` | `{"error":"Request must be a POST request with JSON body"}` | O método não é `POST`, ou `Content-Type` não é exatamente `application/json`. | +| `400` | `{"error":"Invalid JSON in request body"}` | O corpo não é um JSON válido. | +| `400` | `{"error":"Missing 'model' field in request body"}` | O corpo não tem o campo `model`. | +| `400` | `{"error":" not found or not allowed"}` | O binding recusou o id com `model not found or not allowed`. | +| `400` | `{"error":"Invalid input for "}` | O binding recusou o corpo com um `validation error`. | +| `500` | `{"error":"AI internal error"}` | Qualquer outro erro, como uma recusa do servidor do modelo. | + +--- + ## Recursos relacionados - O binding que uma função chama, com os parâmetros e o valor de retorno dele. - O que executa um modelo e de onde a requisição desta página é servida. - Implante uma aplicação e envie uma primeira requisição a um modelo. + O binding que uma Function chama, com os parâmetros e o valor de retorno dele. O id a passar e as capacidades que cada modelo declara para si. - As condições em que Azion encerra ou desprovisiona um modelo. - O runtime que contém o binding e os limites que restringem uma chamada. - Como o consumo de AI Inference é medido e cobrado. + O que executa um modelo e de onde a requisição desta página é servida. + Quem pode chamar um modelo em cada plano, e quando Azion encerra ou desprovisiona um. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/limites.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/limites.mdx index 2fada1424f..b54067a50a 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/limites.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/limites.mdx @@ -1,8 +1,8 @@ --- title: Limites do AI Inference description: >- - Consulte as condições em que Azion encerra ou desprovisiona um modelo do AI - Inference e onde cada limite restante é declarado. + Consulte quem pode chamar o AI Inference em cada plano, as condições em que + Azion encerra ou desprovisiona um modelo e onde cada outro limite é declarado. meta_tags: 'AI Inference, limits, model limits, memory, execution time, termination, deprovisioning, context length' namespace: docs_edge_ai_limits permalink: /documentacao/plataforma/ai-inference/limites/ @@ -12,7 +12,21 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Um modelo no [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) encontra dois tipos de limite. O primeiro é uma condição: Azion encerra um modelo que consome memória demais ou que executa por tempo demais, e desprovisiona um modelo que nunca é executado. O segundo é um valor declarado que delimita uma chamada, como um campo da requisição ou o comprimento de contexto de um modelo. Esta página traz as condições e indica a página que declara cada valor. +Uma chamada de modelo no [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) encontra três tipos de limite. O primeiro é o acesso, que depende do plano da conta. O segundo é uma condição: Azion pode encerrar a execução de um modelo que consome memória demais ou que executa por tempo demais, e pode desprovisionar um modelo que é criado e não é executado por mais de três dias. O terceiro é um valor declarado que delimita uma chamada, como um campo da requisição ou o comprimento de contexto de um modelo. Esta página traz o acesso e as condições e indica a página que declara cada valor. + +## Acesso por plano + +O acesso ao AI Inference depende do plano. Os planos são os que a [página de preços da Azion](https://www.azion.com/en/pricing/) lista. + +| Plano | Acesso ao AI Inference | +| --- | --- | +| Hobby | Sob solicitação, sujeito a aprovação | +| Pro | Sob solicitação, sujeito a aprovação | +| Enterprise | Custom | + +Uma conta sem acesso recebe `AIError: model not found or not allowed` para todo id de modelo. É o mesmo erro que um id de modelo que não existe retorna, então o erro sozinho não distingue os dois casos. + +--- ## Encerramento e desprovisionamento de modelos @@ -28,13 +42,15 @@ Azion aplica as condições abaixo a todo modelo. As duas primeiras delimitam um ## Limites declarados em outras páginas -Os valores que delimitam uma chamada de modelo pertencem ao modelo, ao schema da requisição ou à função que faz a chamada. Cada um é declarado na página que o detém. Para dimensionar um prompt, consulte o comprimento de contexto na página do modelo que você chama. +Os valores que delimitam uma chamada de modelo pertencem ao modelo, ao schema da requisição ou à Function que faz a chamada. Cada um é declarado na página que o detém. Para dimensionar um prompt, consulte o comprimento de contexto na página do modelo que você chama. | Limite | O que delimita | Onde é declarado | | --- | --- | --- | | Comprimento de contexto | O contexto que um modelo aceita, em tokens. Cada página de modelo declara o próprio valor. | [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/) | -| Limites dos campos da requisição | Os valores que `temperature`, `top_p`, `n`, `presence_penalty` e `frequency_penalty` aceitam. | [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) | -| Limites de Functions | O tamanho do código, a memória, o tempo de execução e as requisições de saída da função que chama o modelo. | [Limites de Functions](/pt-br/documentacao/plataforma/functions/limites/) | +| Limites dos campos da requisição | Os valores que `temperature`, `top_p`, `n`, `max_tokens`, `presence_penalty` e `frequency_penalty` aceitam. | [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/) | +| Limites de Functions | O tamanho do código, a memória, o tempo de execução e as requisições de saída da Function que chama o modelo. | [Limites de Functions](/pt-br/documentacao/plataforma/functions/limites/) | + +O tempo que uma Function espera dentro de `Azion.AI.run` não conta no limite de 2 segundos de CPU da Function. Por exemplo, uma geração de 2048 tokens que leva cerca de 20 segundos termina sem que a Function seja encerrada. O tempo de execução de 5 minutos de uma Function é tempo de relógio e inclui operações assíncronas, então a espera conta nele. --- @@ -43,9 +59,7 @@ Os valores que delimitam uma chamada de modelo pertencem ao modelo, ao schema da Os campos da requisição que uma chamada de modelo aceita, com os limites de cada um. - O catálogo a abrir para consultar o comprimento de contexto e o id de um modelo. - Os valores que delimitam a função dentro da qual uma chamada de modelo executa. - O que executa um modelo e a que as condições desta página se aplicam. + Os valores que delimitam a Function dentro da qual uma chamada de modelo executa. A métrica em que uma chamada de modelo é medida e o valor cobrado por ela. Onde perguntar qual valor se aplica quando esta página não declara nenhum. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/lora-fine-tune.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/lora-fine-tune.mdx index ce2318b674..369b1a6789 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/lora-fine-tune.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/lora-fine-tune.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Low-Rank Adaptation (LoRA) adapta um modelo a uma tarefa com o treinamento de um conjunto pequeno de pesos adicionais, em vez de retreinar o modelo inteiro. **LoRA Fine-Tune** aplica esse método a modelos suportados na infraestrutura da Azion, como uma extensão de [AI Inference](/pt-br/documentacao/plataforma/ai-inference/). LoRA se aplica a alguns modelos e não a outros, e a página de cada modelo declara qual é o caso. +Low-Rank Adaptation (LoRA) adapta um modelo a uma tarefa com o treinamento de um conjunto pequeno de pesos adicionais, em vez de retreinar o modelo inteiro. **LoRA Fine-Tune** é um recurso da plataforma que estende [AI Inference](/pt-br/documentacao/plataforma/ai-inference/) com esse método, para modelos suportados, na infraestrutura da Azion. LoRA se aplica a alguns modelos e não a outros, e a página de cada modelo declara qual é o caso. ## Modelos suportados @@ -36,7 +36,9 @@ Para conhecer a categoria, o id, o comprimento do contexto e os tipos de entrada ## Relação com AI Inference -LoRA Fine-Tune é um recurso da plataforma próprio, que estende AI Inference. A adaptação é executada na infraestrutura da Azion, sem infraestrutura para você provisionar ou gerenciar. Você é responsável pelos dados de treinamento, pelas entradas e saídas do modelo e pela licença de terceiros do modelo que você adapta. +LoRA Fine-Tune estende AI Inference. A adaptação é executada na infraestrutura da Azion, sem infraestrutura para você provisionar ou gerenciar. Você é responsável pelos dados de treinamento, pelas entradas e saídas do modelo, pela licença de terceiros do modelo que você adapta, pela conformidade com os termos aplicáveis e pela segurança e legalidade do seu uso. + +Nenhuma interface pública cria ou treina um adaptador, o conjunto de pesos adicionais que LoRA treina para um modelo. Azion Console não tem tela de LoRA Fine-Tune, e nem a Azion API v4 nem a Azion CLI têm uma operação para ele. --- @@ -51,9 +53,7 @@ LoRA Fine-Tune é cobrado por duas métricas, Compute Time e Requests, e é medi A categoria, o id, o comprimento do contexto e os tipos de entrada de todos os modelos que AI Inference executa. - O produto que LoRA Fine-Tune estende e que executa os modelos. O que executa um modelo e onde termina a parte da Azion em uma chamada de modelo. - O corpo da requisição e o binding pelos quais uma chamada a um modelo viaja. A tarifa cobrada pelo Compute Time e pelos Requests de LoRA Fine-Tune. Onde perguntar o que esta página não declara sobre adaptar um modelo. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/modelos.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/modelos.mdx index be007750c7..a001466772 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/modelos.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/modelos.mdx @@ -12,29 +12,46 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -[AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa os modelos desta página. Você seleciona um modelo pelo id, uma string à qual o modelo responde, e não pelo nome sob o qual ele aparece listado. Cada linha do catálogo carrega esse id ao lado das capacidades que a página do modelo declara para si. Para conhecer o corpo da requisição em que o id viaja, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). +[AI Inference](/pt-br/documentacao/plataforma/ai-inference/) executa os modelos desta página. Você seleciona um modelo pelo id, uma string à qual o modelo responde, e não pelo nome sob o qual ele aparece listado. Cada linha do catálogo carrega esse id ao lado das capacidades do modelo. Para conhecer o corpo da requisição em que o id viaja, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). ## Catálogo de modelos -Cada linha é um modelo, e o nome do modelo leva à página do modelo, que traz um exemplo de requisição. A coluna Categoria indica LLM para um large language model, VLM para um vision language model, Embedding ou Reranker. Um traço significa que a página do modelo não declara valor para aquela capacidade. +Cada linha é um modelo, e o nome do modelo leva à página do modelo, que traz um exemplo de requisição. A coluna Categoria assume um de quatro valores: + +- **LLM**: um large language model, que lê texto e retorna texto. +- **VLM**: um vision language model, que lê texto e imagens e retorna texto. +- **Embedding**: um modelo que retorna um vetor que representa o texto de entrada. +- **Reranker**: um modelo que pontua um conjunto de documentos em relação a uma consulta. + +Um traço significa que a página do modelo não declara valor para aquela capacidade. | Modelo | Categoria | Entrada | Comprimento de contexto | Tamanho | Chamada de ferramentas | LoRA | Id do modelo | | --- | --- | --- | --- | --- | --- | --- | --- | | [Mistral 3 Small (24B AWQ)](/pt-br/documentacao/plataforma/ai-inference/mistral-3-small/) | LLM | Texto | 32k tokens | 24B parâmetros | Sim | Não | `casperhansen-mistral-small-24b-instruct-2501-awq` | | [BAAI/bge-reranker-v2-m3](/pt-br/documentacao/plataforma/ai-inference/baai-bge-reranker-v2-m3/) | Reranker | Texto | 8k tokens | 568M parâmetros | — | Não | `baai-bge-reranker-v2-m3` | | [InternVL3](/pt-br/documentacao/plataforma/ai-inference/internvl3/) | VLM | Texto e imagem | 16k tokens | 1B parâmetros | Não | Não | `opengvlab-internvl3-1b-instruct` | -| [Qwen2.5 VL AWQ 3B](/pt-br/documentacao/plataforma/ai-inference/qwen-2-5-vl-3b/) | VLM | Texto e imagem | 32k tokens | 3B parâmetros | Sim | Sim | `qwen-qwen25-vl-3b-instruct-awq` | -| [Qwen2.5 VL AWQ 7B](/pt-br/documentacao/plataforma/ai-inference/qwen-2-5-vl-7b/) | VLM | Texto e imagem | 32k tokens | 7B parâmetros | Sim | Sim | `qwen-qwen25-vl-7b-instruct-awq` | -| [Qwen3 30B A3B Instruct 2507 FP8](/pt-br/documentacao/plataforma/ai-inference/qwen3-30ba3b/) | LLM | Texto | 64k tokens | 30B parâmetros | Sim | Sim | `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` | +| [Qwen2.5 VL AWQ 3B](/pt-br/documentacao/plataforma/ai-inference/qwen-2-5-vl-3b/) | VLM | Texto e imagem | 32k tokens | 3B parâmetros | Só com a ferramenta nomeada | Sim | `qwen-qwen25-vl-3b-instruct-awq` | +| [Qwen2.5 VL AWQ 7B](/pt-br/documentacao/plataforma/ai-inference/qwen-2-5-vl-7b/) | VLM | Texto e imagem | 32k tokens | 7B parâmetros | Só com a ferramenta nomeada | Sim | `qwen-qwen25-vl-7b-instruct-awq` | +| [Qwen3 30B A3B Instruct 2507 FP8](/pt-br/documentacao/plataforma/ai-inference/qwen3-30ba3b/) | LLM | Texto | 64k tokens | 30,5B parâmetros | Sim | Sim | `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` | | [Qwen3 Embedding 4B](/pt-br/documentacao/plataforma/ai-inference/qwen3-embedding-4b/) | Embedding | Texto | 32k tokens | 4B parâmetros | — | — | `Qwen/Qwen3-Embedding-4B` | -| [Nanonets-OCR-s](/pt-br/documentacao/plataforma/ai-inference/nanonets-ocr-s/) | — | Texto e imagem | 32k tokens | — | — | — | `nanonets/Nanonets-OCR-s` | -| [GPT-OSS 20B](/pt-br/documentacao/plataforma/ai-inference/gpt-oss-20b/) | LLM | Texto | 131k tokens | 20B parâmetros | Sim | Não | `gpt-oss-20b` | +| [Nanonets-OCR-s](/pt-br/documentacao/plataforma/ai-inference/nanonets-ocr-s/) | — | Texto e imagem | 32k tokens | — | Não | — | `nanonets/Nanonets-OCR-s` | +| [GPT-OSS 20B](/pt-br/documentacao/plataforma/ai-inference/gpt-oss-20b/) | LLM | Texto | 131k tokens | 21B parâmetros | Sim | Não | `openai/gpt-oss-20b` | + +A chamada de ferramentas aparece como Sim quando uma requisição que carrega um array `tools` retorna `tool_calls`, com o modelo escolhendo a ferramenta. Qwen2.5 VL AWQ 3B, Qwen2.5 VL AWQ 7B e Nanonets-OCR-s recusam essa requisição com `Request failed with status 400`. Os dois modelos Qwen2.5 VL retornam `tool_calls` quando `tool_choice` nomeia a ferramenta, com `finish_reason` igual a `stop` e `content` igual a uma string vazia. --- ## Ids de modelo -Um id de modelo é a string que seleciona o modelo: o primeiro argumento de `Azion.AI.run` dentro de uma [função](/pt-br/documentacao/plataforma/functions/) e o campo `model` do corpo de uma requisição HTTP. Os ids não compartilham uma forma única. Alguns são minúsculos e separados por hífen, sem barra, e outros carregam um prefixo de publicador e capitalização mista. Copie um id da tabela caractere por caractere, em vez de derivá-lo do nome do modelo. +Um id de modelo é a string que seleciona o modelo: o primeiro argumento de `Azion.AI.run` dentro de uma [Function](/pt-br/documentacao/plataforma/functions/) e o campo `model` do corpo de uma requisição enviada ao endpoint HTTP do [AI Inference Starter Kit](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/frameworks/ai-inference-starter-kit/). Um modelo pode responder a duas formas do id: uma forma de repositório, como `Qwen/Qwen2.5-VL-3B-Instruct-AWQ`, e uma forma em minúsculas com hífens, como `qwen-qwen25-vl-3b-instruct-awq`. As duas formas selecionam o mesmo modelo. A forma em minúsculas não decorre da forma de repositório por uma regra simples, então copie um id da tabela caractere por caractere, em vez de derivá-lo do nome do modelo. + +Para listar os ids que a sua conta pode chamar, nas duas formas, chame `Azion.AI.models()` a partir de uma Function. Ele retorna uma promise que resolve para um array de strings de id: + +```ts +const modelIds = await Azion.AI.models() +``` + +O campo `model` de uma resposta traz o id interno da conta para o modelo, que pode ser diferente do id que a requisição enviou. Uma requisição para `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8` retorna `qwen-qwen3-30b-a3b-instruct-2507-fp8`, e GPT-OSS 20B retorna `gpt-oss-20b`, um id que `Azion.AI.run` recusa como entrada. Não passe o campo `model` de uma resposta como id. --- @@ -43,10 +60,8 @@ Um id de modelo é a string que seleciona o modelo: o primeiro argumento de `Azi O corpo da requisição em que um id viaja e as duas interfaces que o carregam. - O produto que executa os modelos deste catálogo. A extensão do AI Inference por trás da coluna LoRA. - Onde os vetores que um modelo de embedding retorna são armazenados e consultados. - O produto cujo binding de runtime recebe os ids desta tabela. + Onde os vetores que um modelo de embedding retorna são armazenados e consultados. Onde id de modelo, LoRA Fine-Tune e o restante do vocabulário do AI Inference são definidos. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/primeiros-passos.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/primeiros-passos.mdx index a4e058b8bd..c006bcd518 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/primeiros-passos.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/primeiros-passos.mdx @@ -2,7 +2,7 @@ title: Primeiros passos com AI Inference description: >- Implante o template AI Inference Starter Kit e envie uma primeira requisição - de chat a um modelo no domínio da sua própria aplicação. + de chat a um modelo no domínio que o template cria. meta_tags: 'AI Inference, quickstart, AI Inference Starter Kit, first inference, chat completions, Workload Domain, Azion.AI.run' namespace: docs_edge_ai_quickstart permalink: /documentacao/plataforma/ai-inference/primeiros-passos/ @@ -14,24 +14,24 @@ import DocStep from '@aziontech/webkit/doc-step' Este guia conduz você até a primeira resposta de um modelo do AI Inference. -- Implante o template AI Inference Starter Kit como uma aplicação. -- Abra o Workload Domain que a implantação atribui ao workload que serve a aplicação. +- Implante o template AI Inference Starter Kit como uma Application. +- Abra o workload domain do Workload que o template cria. - Envie uma requisição de chat a um modelo e leia a resposta que ele retorna. -- Altere o modelo que a função chama. +- Chame outro modelo mudando um campo da requisição. -A implantação cria três objetos, e uma requisição passa por todos eles: +O template cria estas entidades, e uma requisição passa por elas nesta ordem: -1. O **Workload Domain** é o endereço para o qual um cliente envia a requisição. Azion o atribui ao workload que serve a aplicação, na forma `xxxxxxxxxx.map.azionedge.net`. -2. A **aplicação** recebe a requisição nesse domínio, aplica suas políticas e chama a função. -3. A **função** contém o código que chama o modelo com `Azion.AI.run` e retorna a resposta do modelo. +1. Um **Workload**, com o deployment dele. O Workload recebe a requisição no workload domain dele, na forma `xxxxxxxxxx.map.azionedge.net`, e o deployment dele define a Application. +2. Uma **Application**, com Cache, Functions e Application Accelerator ativados. A única regra dela executa a Function em todo path, pela Function Instance, e ignora o cache. +3. Uma **Function** e a **Function Instance** dela, que vincula a Function à Application. A Function lê o id do modelo no campo `model` do corpo da requisição, passa o corpo inteiro para `Azion.AI.run` e retorna a resposta do modelo. -Você não escreve nenhum código para chegar à primeira resposta. O template cria os três objetos, e a função que ele instala já serve um endpoint compatível com OpenAI. +A Application e a Function recebem o nome que você insere, seguido do sufixo "(Build at …)". Você não escreve nenhum código para chegar à primeira resposta: a Function que o template instala já serve um endpoint compatível com OpenAI. --- ## Pré-requisitos -Este guia requer uma conta Azion. O template cria todos os outros objetos que o guia usa: a aplicação, a função e o domínio. +Este guia requer uma conta Azion com acesso ao AI Inference. Nos planos Hobby e Pro, o acesso está disponível sob solicitação, sujeito a aprovação. Para o acesso que cada plano dá, consulte [Limites do AI Inference](/pt-br/documentacao/plataforma/ai-inference/limites/). O template cria todas as outras entidades que o guia usa. --- @@ -41,48 +41,52 @@ Este guia requer uma conta Azion. O template cria todos os outros objetos que o O template usa [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/), [Functions](/pt-br/documentacao/plataforma/functions/) e [AI Inference](/pt-br/documentacao/plataforma/ai-inference/). Esses produtos podem gerar custos de uso. Para conhecer os valores, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#ai-inference). ::: -Para criar a aplicação que responde às requisições de modelo: +Para criar a Application que responde às requisições de modelo: - + Acesse [Azion Console](https://console.azion.com/) e selecione **+ Create**. - - + - Insira um nome para a aplicação. Por exemplo: `ai-inference-quickstart`. + Em **Start from Template**, selecione **AI Inference Starter Kit**. + + + + + Em **Application Name**, insira um nome feito de letras, números e sublinhados. Por exemplo: `ai_inference_quickstart`. Um hífen é recusado com "The use of accents and/or special characters is not allowed." -Uma janela mostra os logs da implantação enquanto ela é executada. Quando ela termina, a página mostra informações sobre a aplicação e as opções para continuar. +Uma janela mostra os logs da implantação enquanto ela é executada. Quando ela termina, a página mostra o domínio em **Visit site**, a opção **Add custom domain**, os **Deployment logs** e **Resources created**, que lista o Workload e a Application. -A aplicação existe, com uma função que chama um modelo e um domínio que a serve. +O Workload, a Application e a Function existem, e a Function responde a toda requisição que chega ao domínio. --- -## Abra o domínio da aplicação +## Abra o workload domain -Azion atribui um Workload Domain ao workload que serve a aplicação durante a implantação. O domínio tem a forma `xxxxxxxxxx.map.azionedge.net` e é o endereço para o qual um cliente envia uma requisição de modelo. A página da implantação mostra o link para a aplicação. +O domínio em **Visit site** é o workload domain do Workload, na forma `xxxxxxxxxx.map.azionedge.net`. É o endereço para o qual um cliente envia uma requisição de modelo. -Para ver a aplicação no navegador, selecione o link. +Para conferir que o domínio responde, selecione **Visit site**. :::note[nota] -A aplicação leva alguns minutos para se propagar aos data centers da Azion. Até que ela se propague, o domínio não resolve e a página não abre. Aguarde alguns minutos e selecione o link novamente. +O deployment leva alguns minutos para se propagar aos data centers da Azion. Até que ele se propague, o domínio responde com o `404` de placeholder da Azion. Aguarde alguns minutos e selecione **Visit site** novamente. ::: -O domínio resolve, e a aplicação responde nele. Copie o domínio: a requisição ao modelo vai para ele. +A página mostra `{"error":"Request must be a POST request with JSON body"}`. Essa resposta vem da Function, que aceita somente uma requisição `POST` com um corpo JSON. Copie o domínio: a requisição ao modelo vai para ele. --- ## Envie uma requisição ao modelo -A aplicação serve um endpoint compatível com OpenAI em `/v1/chat/completions` no domínio dela. O corpo da requisição indica o modelo no campo `model` e carrega a conversa em `messages`. +A Function responde em qualquer path do domínio, e `/v1/chat/completions` é o path que os clientes da OpenAI usam. O corpo da requisição indica o modelo no campo `model` e carrega a conversa em `messages`. O header `Content-Type` precisa ser exatamente `application/json`. -A função que o template instala chama `Qwen/Qwen3-30B-A3B-Instruct-2507-FP8`. Para enviar uma requisição de chat a ele, substitua `` pelo domínio da sua aplicação e execute: +Para enviar uma requisição de chat ao Qwen3 30B A3B Instruct 2507 FP8, substitua `` pelo domínio que você copiou e execute: ```bash curl -X POST https:///v1/chat/completions \ @@ -100,85 +104,79 @@ curl -X POST https:///v1/chat/completions \ }' ``` -O modelo responde com uma entrada em `choices`, e o texto gerado fica em `choices[0].message.content`: +O modelo responde com uma entrada em `choices`, e o texto gerado fica em `choices[0].message.content`. A resposta abaixo encurta esse texto: ```json { - "id": "chatcmpl-example", + "id": "chatcmpl-784835050db84a289185baceb0ccbc8e", "object": "chat.completion", - "created": 1767268800, - "model": "Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", + "created": 1794444653, + "model": "qwen-qwen3-30b-a3b-instruct-2507-fp8", "choices": [ { "index": 0, "message": { "role": "assistant", - "reasoning_content": null, - "content": "Sure! Here is a list of some European capitals...", - "tool_calls": [] + "content": "There are 44 sovereign countries in Europe, each with its own capital city. Here is a list of all the European capitals:...", + "refusal": null, + "annotations": null, + "audio": null, + "function_call": null, + "tool_calls": [], + "reasoning": null, + "reasoning_content": null }, "logprobs": null, "finish_reason": "stop", - "stop_reason": null + "stop_reason": null, + "token_ids": null } ], + "service_tier": null, + "system_fingerprint": null, "usage": { - "prompt_tokens": 9, - "total_tokens": 527, - "completion_tokens": 518, + "prompt_tokens": 24, + "total_tokens": 620, + "completion_tokens": 596, "prompt_tokens_details": null }, - "prompt_logprobs": null + "prompt_logprobs": null, + "prompt_token_ids": null, + "kv_transfer_params": null } ``` -Você tem a sua primeira resposta de modelo, servida pela sua própria aplicação. - -Azion não emite nenhuma credencial para essa requisição, e o endpoint não carrega autenticação da Azion. Quando você adiciona autenticação à sua aplicação, inclua o header que ela exige, por exemplo `-H "Authorization: Bearer [TOKEN VALUE]"`. Para conhecer todos os campos que um corpo de requisição aceita, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). - ---- - -## (Opcional) Altere o modelo que a função chama - -A função que o template implantou contém a chamada ao modelo, e o primeiro argumento de `Azion.AI.run` é o id do modelo. A página da função tem três abas: +O campo `model` carrega o id interno do modelo na conta, `qwen-qwen3-30b-a3b-instruct-2507-fp8`, que é diferente do id que a requisição enviou. -- **Main Settings** renomeia a função e altera as configurações básicas dela. -- **Code** contém o código da função. -- **Arguments** define os argumentos que a função usa. +Você tem a sua primeira resposta de modelo, servida pela sua própria Application. -Para chamar um modelo diferente: +Se a conta não tem acesso ao AI Inference, ou se o id do modelo está errado, o endpoint responde `400` com `{"error":" not found or not allowed"}`. Para todos os erros que o endpoint retorna, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#erros). - - +O template não configura nenhuma autenticação na frente do endpoint, então qualquer cliente que alcança o domínio pode chamar um modelo. Quando você adiciona autenticação à sua Application, inclua o header que ela exige, por exemplo `-H "Authorization: Bearer [TOKEN VALUE]"`. Para conhecer todos os campos que um corpo de requisição aceita, consulte [Invocação de modelos](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/). - Acesse [Azion Console](https://console.azion.com/) > **Functions**. +--- - - +## (Opcional) Chame outro modelo - Selecione a função que tem o mesmo nome da aplicação. +A Function lê o id do modelo na requisição, então chamar outro modelo muda somente o campo `model` do corpo. O código da Function não precisa de nenhuma mudança. A forma dos ids varia entre os modelos, então copie o id da própria página do modelo em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). - - +Para enviar uma requisição de chat ao Qwen2.5 VL AWQ 3B, execute: - Na aba **Code**, altere o primeiro argumento de `Azion.AI.run`. A chamada tem esta forma: - - ```ts - const modelResponse = await Azion.AI.run("Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", { - "stream": true, +```bash +curl -X POST https:///v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "qwen-qwen25-vl-3b-instruct-awq", + "max_tokens": 16, "messages": [ - { "role": "system", "content": "You are a helpful assistant." }, - { "role": "user", "content": "Name the European capitals." } + { "role": "user", "content": "Name one European capital." } ] - }) - return modelResponse - ``` + }' +``` - - - +A resposta carrega `"model": "qwen-qwen25-vl-3b-instruct-awq"`, e `choices[0].message.content` contém a resposta desse modelo, como `Paris, France is a European capital.` -A função chama o modelo cujo id está salvo na aba **Code**. A forma dos ids varia entre os modelos, então copie o id da própria página do modelo em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). +A mesma Function respondeu às duas requisições. O código dela fica na aba **Code** da Function, que o item **Functions** do menu do Console abre. --- @@ -188,7 +186,7 @@ A função chama o modelo cujo id está salvo na aba **Code**. A forma dos ids v - - - + + + diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/solucao-de-problemas.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/solucao-de-problemas.mdx new file mode 100644 index 0000000000..6a336674fc --- /dev/null +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/ai-inference/solucao-de-problemas.mdx @@ -0,0 +1,232 @@ +--- +title: Solucione problemas de AI Inference +description: Encontre a causa de uma chamada de modelo recusada, de uma resposta diferente do pedido e de um erro do endpoint do AI Inference Starter Kit. +meta_tags: 'ai inference, troubleshooting, errors, azion.ai.run, model not found or not allowed, validation error, request failed, starter kit, endpoint' +namespace: documentation_products_ai_inference_troubleshooting +permalink: /documentacao/plataforma/ai-inference/solucao-de-problemas/ +--- + +import FrameBox from '@aziontech/webkit/frame-box' +import ItemList from '@aziontech/webkit/item-list' +import DocItem from '@aziontech/webkit/doc-item' + +Esta página cobre os sintomas de uma chamada de modelo ao [AI Inference](/pt-br/documentacao/plataforma/ai-inference/), feita por uma Function com `Azion.AI.run` ou enviada ao endpoint do AI Inference Starter Kit. Um erro citado do binding é a `message` do erro que `Azion.AI.run` lança. Um erro citado do endpoint é o campo `error` da resposta JSON dele. + +--- + +## Uma chamada de modelo falha com model not found or not allowed + +`Azion.AI.run` lança este erro, e o modelo não executa: + +```text +AIError: model not found or not allowed +``` + +O id do modelo não existe, ou a conta não tem acesso ao AI Inference. A mensagem não diz qual dos dois. Um valor de `model` copiado de uma resposta anterior também pode falhar, porque a resposta traz o id interno da conta, que o binding pode recusar como entrada. + +- **Copie o id da página do modelo**: cada página em [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/#ids-de-modelo) informa um id que responde. +- **Liste os ids que a conta pode chamar**: `Azion.AI.models()` os retorna, como mostra [Listar modelos](/pt-br/documentacao/devtools/runtime/api-reference/ai/#listar-modelos). +- **Confira o acesso do plano**: nos planos Hobby e Pro, AI Inference está disponível sob solicitação, conforme [Acesso por plano](/pt-br/documentacao/plataforma/ai-inference/limites/#acesso-por-plano). + +Com um id dessa lista, a chamada retorna a resposta do modelo. + +--- + +## Uma chamada de modelo falha com um erro de validação + +`Azion.AI.run` lança um erro que nomeia um tipo e um campo, e o modelo não executa: + +```text +AIError: validation error: Required { + path: "/query", +} +``` + +O corpo da requisição não corresponde ao schema do modelo. `Required` marca um campo ausente, `WrongType` um valor do tipo errado, `Minimum` ou `Maximum` um valor além de um limite, `Enum` um valor fora de um conjunto fixo e `OneOf` uma mensagem que não corresponde a nenhum objeto de mensagem. + +- **Corrija o campo que path nomeia**: [Campos da requisição](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#campos-da-requisicao) lista cada campo com o tipo e os limites dele. +- **Use query e documents no reranker**: o reranker BAAI recusa o par `text_1` e `text_2` com `Required`, conforme [Requisições de reranking](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#requisicoes-de-reranking). +- **Escolha uma largura da lista para dimensions**: o Qwen3 Embedding 4B recusa um valor fora da lista dele com `Enum`, conforme [Requisições de embedding](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#requisicoes-de-embedding). + +Quando o corpo corresponde ao schema, a chamada retorna a resposta do modelo. + +--- + +## Uma chamada de modelo falha com Request failed with status 400 + +`Azion.AI.run` lança um erro que traz um status e nenhum motivo: + +```text +Error: Request failed with status 400 +``` + +O servidor do modelo recusou uma requisição que passou na validação. As causas observadas são: uma requisição com `tools` sem `tool_choice` no Qwen2.5 VL AWQ 3B, no Qwen2.5 VL AWQ 7B ou no Nanonets-OCR-s; um prompt maior que o contexto que o modelo serve; `stream_options` sem `stream`; um `tool_choice` desconhecido; um `seed` que não é inteiro; e `temperature` e `top_p` em `0` com as duas penalidades em `-2`. + +- **Nomeie a ferramenta nos modelos Qwen2.5 VL**: uma ferramenta nomeada em `tool_choice` retorna `tool_calls`, como mostra [Chamada de ferramentas](/pt-br/documentacao/plataforma/ai-inference/qwen-2-5-vl-3b/#chamada-de-ferramentas). O Nanonets-OCR-s não aceita ferramentas. +- **Encurte o prompt**: [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/) informa o comprimento de contexto de cada modelo. +- **Confira os valores na lista**: [Erros](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#erros) lista cada requisição que o servidor do modelo recusa. + +Depois da mudança, a chamada retorna a resposta do modelo. + +--- + +## Uma requisição com imagem falha com Request failed with status 500 + +Uma requisição com uma parte `image_url` lança este erro: + +```text +Error: Request failed with status 500 +``` + +A URL em `image_url.url` não serve uma imagem, então o modelo não tem o que ler. + +- **Use uma URL que sirva uma imagem**: uma URL `https` que retorne a imagem, ou uma URL `data:` que carregue a imagem em base64, conforme [Objetos de mensagem](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#objetos-de-mensagem). + +Com uma URL que serve uma imagem, o modelo responde em texto. + +--- + +## O GPT-OSS 20B não retorna conteúdo + +Uma resposta do GPT-OSS 20B traz `content` como `null` e `finish_reason` como `length`. + +O modelo raciocina antes de responder, e o raciocínio conta no `max_tokens`. Com um `max_tokens` pequeno, o raciocínio usa todo o orçamento, e não sobra texto de resposta. O próprio raciocínio fica em `reasoning_content`. + +- **Aumente o max_tokens**: deixe espaço para o raciocínio e para a resposta, como mostra [Chat completion](/pt-br/documentacao/plataforma/ai-inference/gpt-oss-20b/#chat-completion). + +Com espaço para os dois, `content` traz a resposta e `finish_reason` é `stop`. + +--- + +## Um embedding tem 2560 valores em vez de 4096 + +Uma requisição ao Qwen3 Embedding 4B com `dimensions` definido como `4096` retorna um vetor de 2560 valores, que não corresponde a uma coluna vetorial declarada para 4096 valores. + +O modelo aceita `4096`, mas o maior vetor dele tem 2560 valores. Uma requisição sem `dimensions` também retorna 2560 valores. + +- **Peça uma largura que o modelo retorna**: `256`, `512`, `1024` ou `2048` retornam essa largura, conforme [Embedding](/pt-br/documentacao/plataforma/ai-inference/qwen3-embedding-4b/#embedding). +- **Dimensione a coluna para 2560 valores**: quando a requisição pede `4096` ou nenhuma largura, declare a coluna vetorial com 2560 valores. + +O vetor e a coluna passam a ter a mesma largura. + +--- + +## Um campo da requisição não tem efeito + +Um campo no corpo da requisição não muda nada na resposta, e nenhum erro é retornado. + +O binding aceita um campo que o modelo não conhece e o ignora, então um nome de campo escrito errado passa sem aviso. Um campo `model` no corpo também é ignorado: o primeiro argumento de `Azion.AI.run` decide o modelo. + +- **Escreva o campo como a referência o lista**: [Campos da requisição](/pt-br/documentacao/plataforma/ai-inference/invocacao-de-modelos/#campos-da-requisicao) traz cada nome. +- **Passe o id do modelo como primeiro argumento**: altere o primeiro argumento de `Azion.AI.run` para chamar outro modelo. + +Com o campo escrito como listado, a resposta o reflete. + +--- + +## Azion.AI é undefined quando a Function roda localmente + +Sob `azion dev`, uma chamada a `Azion.AI.run` lança este erro: + +```text +TypeError: Cannot read properties of undefined (reading 'run') +``` + +`Azion.AI` só existe em uma Function implantada. Sob `azion dev`, ele é `undefined`, conforme a [API de AI Inference](/pt-br/documentacao/devtools/runtime/api-reference/ai/). + +- **Teste as chamadas de modelo em uma Function implantada**: implante a Function e envie a requisição ao domínio dela. + +Em uma Function implantada, a chamada retorna a resposta do modelo. + +--- + +## O endpoint responde Request must be a POST request with JSON body + +O endpoint do AI Inference Starter Kit responde `400` com este corpo: + +```json +{"error":"Request must be a POST request with JSON body"} +``` + +A Function que o template instala aceita só uma requisição `POST` cujo header `Content-Type` seja exatamente `application/json`. Um navegador que abre o domínio envia um `GET`, e um cliente que acrescenta `; charset=utf-8` ao header também é recusado. + +- **Envie uma requisição POST**: os [primeiros passos](/pt-br/documentacao/plataforma/ai-inference/primeiros-passos/#envie-uma-requisicao-ao-modelo) mostram uma com `curl`. +- **Envie o header sem parâmetro**: defina `Content-Type` como `application/json`. + +O endpoint então retorna a resposta do modelo. + +--- + +## O endpoint responde Missing model field ou Invalid JSON + +O endpoint do AI Inference Starter Kit responde `400` com um destes corpos: + +```json +{"error":"Missing 'model' field in request body"} +{"error":"Invalid JSON in request body"} +``` + +A Function que o template instala lê o id do modelo do campo `model` do corpo. Um corpo sem `model`, ou um corpo que não é um JSON válido, para antes da chamada de modelo. + +- **Acrescente o campo model**: defina `model` como um id de [Modelos de AI](/pt-br/documentacao/plataforma/ai-inference/modelos/). +- **Envie um JSON válido**: confira as aspas do corpo que o seu cliente envia. + +O endpoint então retorna a resposta do modelo. + +--- + +## O endpoint responde AI internal error + +O endpoint do AI Inference Starter Kit responde `500` com este corpo: + +```json +{"error":"AI internal error"} +``` + +O binding lançou um erro diferente de `model not found or not allowed` e de um erro de validação, como uma recusa do servidor do modelo. O corpo não traz esse erro, mas a Function que o template instala o escreve no console. + +- **Leia a linha de console da requisição**: a fonte de dados [Functions Console](/pt-br/documentacao/plataforma/real-time-events/fontes-de-dados/#functions-console) do Real-Time Events traz as linhas que uma Function escreve, incluindo o nome e a mensagem do erro. +- **Associe a mensagem à causa dela**: as entradas acima cobrem cada mensagem observada. + +A linha de console nomeia a recusa, e a correção para essa mensagem se aplica. + +--- + +## O endpoint responde 404 logo depois da implantação + +Logo depois que você implanta o AI Inference Starter Kit, o domínio em **Visit site** responde `404` com a página de placeholder da Azion. + +A implantação ainda não se propagou aos data centers da Azion. A propagação leva vários minutos. + +- **Repita a requisição depois de alguns minutos**: como descreve [Abra o workload domain](/pt-br/documentacao/plataforma/ai-inference/primeiros-passos/#abra-o-workload-domain). + +Quando a implantação se propaga, o domínio responde com a resposta da Function. + +--- + +## Application Name é recusado quando você implanta o template + +Quando você implanta o AI Inference Starter Kit, o campo **Application Name** mostra esta mensagem: + +```text +The use of accents and/or special characters is not allowed. +``` + +O campo aceita só letras, números e sublinhados, então um hífen é recusado. + +- **Use sublinhados**: insira um nome como `ai_inference_starter_kit`, o padrão. + +O botão **Deploy** então implanta o template. + +--- + +## Recursos relacionados + + + + Cada campo da requisição, os campos da resposta e os erros do binding e do endpoint. + O id, o comprimento de contexto e as capacidades de cada modelo. + O acesso por plano e quando a Azion encerra ou desprovisiona um modelo. + Implante o template e envie uma primeira requisição a um modelo. + + diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/deploy/edge-orchestrator/edge-services.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/deploy/edge-orchestrator/edge-services.mdx index f4df8941be..010dd7ec7c 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/deploy/edge-orchestrator/edge-services.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/deploy/edge-orchestrator/edge-services.mdx @@ -28,9 +28,9 @@ Configure os gatilhos de instalação, desinstalação e recarregamento e defina ## Como funciona -Ao utilizar a Azion como sua plataforma de Edge, você pode criar e customizar serviços para serem executados na sua rede Edge privada e híbrida. O Azion Edge Services funciona por meio de gatilhos para instalação, desinstalação e recarregamento, com definição das dependências entre os recursos, e implementa nativamente um conjunto de funcionalidades da Azion, como Applications, Firewall e Functions, utilizando como base a tecnologia de Azion Cells. +Ao utilizar a Azion como sua plataforma de Edge, você pode criar e customizar serviços para serem executados na sua rede Edge privada e híbrida. O Azion Edge Services funciona por meio de gatilhos para instalação, desinstalação e recarregamento, com definição das dependências entre os recursos, e implementa nativamente um conjunto de funcionalidades da Azion, como Applications, Firewall e Functions. -Dessa forma, permite construir Applications para uma grande variedade de casos de uso, que variam desde uma CDN de alta escala e qualidade até a hospedagem de aplicações web, aplicações de AI, VR e muitas outras. Para isso, *ative* o **Azion Cells** e defina os **Edge Nodes** que devem receber determinadas aplicações, tudo controlado pelo painel de controle da Azion ou APIs, em uma interface centralizada e com diferentes controles de acesso. +Dessa forma, permite construir Applications para uma grande variedade de casos de uso, que variam desde uma CDN de alta escala e qualidade até a hospedagem de aplicações web, aplicações de AI, VR e muitas outras. Para isso, defina os **Edge Nodes** que devem receber determinadas aplicações, tudo controlado pelo painel de controle da Azion ou APIs, em uma interface centralizada e com diferentes controles de acesso. ## Resources diff --git a/apps/docs/src/nav/trees/ai-inference.json b/apps/docs/src/nav/trees/ai-inference.json index 1502e68706..61623c214a 100644 --- a/apps/docs/src/nav/trees/ai-inference.json +++ b/apps/docs/src/nav/trees/ai-inference.json @@ -160,6 +160,17 @@ "pt-br": "boas-praticas" } }, + { + "page": "documentation_products_ai_inference_troubleshooting", + "label": { + "en": "Troubleshooting", + "pt-br": "Solução de problemas" + }, + "slug": { + "en": "troubleshooting", + "pt-br": "solucao-de-problemas" + } + }, { "page": "docs_edge_ai_glossary", "label": { @@ -172,27 +183,19 @@ } }, { + "page": "documentation_pricing", + "hash": "ai-inference", "label": { - "en": "Management", - "pt-br": "Gerenciamento" + "en": "Pricing", + "pt-br": "Preços" }, - "items": [ - { - "page": "documentation_pricing", - "hash": "ai-inference", - "label": { - "en": "Pricing", - "pt-br": "Preços" - }, - "linkOnly": true - }, - { - "tree": "changelog", - "label": { - "en": "Changelog" - } - } - ] + "linkOnly": true + }, + { + "tree": "changelog", + "label": { + "en": "Changelog" + } } ] }