Documentation
¶
Overview ¶
Package sapaicore implements the ADK Go v2 model.LLM interface for SAP AI Core.
It bridges Google's Agent Development Kit with SAP AI Core's inference API, supporting two modes of operation:
Orchestration: a single deployment handles all models via the SAP AI Core harmonized API. Supports extended thinking, response format, tool calling, server-side timeout/retry, content filtering, data masking, translation, model fallback, and prompt caching.
Foundation-models: per-model deployment IDs with a direct OpenAI-compatible chat completions API.
Quick Start ¶
provider, err := sapaicore.NewProvider(
sapaicore.WithEndpoint("https://api.ai.prod.us-east-1.aws.ml.hana.ondemand.com"),
sapaicore.WithAuth(clientID, clientSecret, authURL),
sapaicore.WithOrchestration(), // auto-discovers deployment
)
if err != nil {
log.Fatal(err)
}
llm, err := provider.Model("gpt-4.1")
Both streaming and non-streaming generation are supported via the standard ADK model.LLM interface.
Index ¶
- Variables
- type AzureContentSafetyConfig
- type AzureThreshold
- type CacheTTL
- type CustomEntity
- type DPIEntity
- type FilteringConfig
- type InputFilterConfig
- type LlamaGuardConfig
- type MaskFileInputMethod
- type MaskingConfig
- type MaskingEntity
- func ConstantEntity(entity DPIEntity, replacement string) MaskingEntity
- func CustomMaskingEntity(regex, replacement string) MaskingEntity
- func FabricatedEntity(entity DPIEntity) MaskingEntity
- func StandardEntities(entities []DPIEntity) []MaskingEntity
- func StandardEntity(entity DPIEntity) MaskingEntity
- type MaskingMethod
- type ModelOption
- func WithModelFallback(models ...string) ModelOption
- func WithModelFiltering(cfg *FilteringConfig) ModelOption
- func WithModelMasking(cfg MaskingConfig) ModelOption
- func WithModelParams(params map[string]any) ModelOption
- func WithModelPromptCaching(ttl ...CacheTTL) ModelOption
- func WithModelTranslation(cfg TranslationConfig) ModelOption
- func WithoutFiltering() ModelOption
- func WithoutMasking() ModelOption
- func WithoutTranslation() ModelOption
- type Option
- func WithAuth(clientID, clientSecret, authURL string) Option
- func WithDeploymentID(id string) Option
- func WithDeployments(deployments map[string]string) Option
- func WithEndpoint(endpoint string) Option
- func WithFallback(models ...string) Option
- func WithFiltering(cfg *FilteringConfig) Option
- func WithHTTPClient(client *http.Client) Option
- func WithHeaders(headers http.Header) Option
- func WithMasking(cfg MaskingConfig) Option
- func WithMaxRetries(n int) Option
- func WithOrchestration() Option
- func WithPromptCaching(ttl ...CacheTTL) Option
- func WithResourceGroup(group string) Option
- func WithStreamOptions(opts StreamOptions) Option
- func WithTimeout(seconds int) Option
- func WithTranslation(cfg TranslationConfig) Option
- type OutputFilterConfig
- type Provider
- type StreamOptions
- type TranslationConfig
- type TranslationInputConfig
- type TranslationOutputConfig
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrMissingConfig = errors.New("sapaicore: missing required configuration") ErrDeploymentNotFound = errors.New("sapaicore: deployment not found for model") ErrDiscovery = errors.New("sapaicore: orchestration deployment discovery") )
var CommonPIIEntities = []DPIEntity{ EntityPerson, EntityOrg, EntityEmail, EntityPhone, EntityAddress, }
CommonPIIEntities covers the most frequently masked PII types: person names, organizations, email, phone, and addresses.
Functions ¶
This section is empty.
Types ¶
type AzureContentSafetyConfig ¶ added in v0.3.0
type AzureContentSafetyConfig struct {
Hate AzureThreshold
SelfHarm AzureThreshold
Sexual AzureThreshold
Violence AzureThreshold
// PromptShield enables jailbreak/prompt-injection detection (input only).
PromptShield bool
}
type AzureThreshold ¶ added in v0.3.0
type AzureThreshold int
AzureThreshold controls Azure Content Safety sensitivity. Values map to SAP AI Core API thresholds (0/2/4/6): lower = stricter.
const ( AzureThresholdAllowSafe AzureThreshold = 0 AzureThresholdAllowSafeLow AzureThreshold = 2 AzureThresholdAllowSafeLowMedium AzureThreshold = 4 AzureThresholdAllowAll AzureThreshold = 6 )
type CacheTTL ¶ added in v0.3.0
type CacheTTL string
CacheTTL controls the time-to-live for prompt cache entries.
type CustomEntity ¶ added in v0.3.0
type DPIEntity ¶ added in v0.3.0
type DPIEntity string
const ( EntityPerson DPIEntity = "profile-person" EntityOrg DPIEntity = "profile-org" EntityUniversity DPIEntity = "profile-university" EntityLocation DPIEntity = "profile-location" EntityEmail DPIEntity = "profile-email" EntityPhone DPIEntity = "profile-phone" EntityAddress DPIEntity = "profile-address" EntitySAPIDsInternal DPIEntity = "profile-sapids-internal" EntitySAPIDsPublic DPIEntity = "profile-sapids-public" EntityURL DPIEntity = "profile-url" EntityUsernamePassword DPIEntity = "profile-username-password" EntityNationalID DPIEntity = "profile-nationalid" EntityIBAN DPIEntity = "profile-iban" EntitySSN DPIEntity = "profile-ssn" EntityCreditCard DPIEntity = "profile-credit-card-number" EntityPassport DPIEntity = "profile-passport" EntityDriverLicense DPIEntity = "profile-driverlicense" EntityNationality DPIEntity = "profile-nationality" EntityReligiousGroup DPIEntity = "profile-religious-group" EntityPoliticalGroup DPIEntity = "profile-political-group" EntityPronounsGender DPIEntity = "profile-pronouns-gender" EntityEthnicity DPIEntity = "profile-ethnicity" EntityGender DPIEntity = "profile-gender" EntitySexualOrientation DPIEntity = "profile-sexual-orientation" EntityTradeUnion DPIEntity = "profile-trade-union" EntitySensitiveData DPIEntity = "profile-sensitive-data" )
type FilteringConfig ¶ added in v0.3.0
type FilteringConfig struct {
Input *InputFilterConfig
Output *OutputFilterConfig
}
FilteringConfig configures content filtering. Orchestration-mode only.
type InputFilterConfig ¶ added in v0.3.0
type InputFilterConfig struct {
AzureContentSafety *AzureContentSafetyConfig
LlamaGuard *LlamaGuardConfig
}
type LlamaGuardConfig ¶ added in v0.3.0
type LlamaGuardConfig struct {
ViolentCrimes bool
NonViolentCrimes bool
SexCrimes bool
ChildExploitation bool
Defamation bool
SpecializedAdvice bool
Privacy bool
IntellectualProperty bool
IndiscriminateWeapons bool
Hate bool
SelfHarm bool
SexualContent bool
Elections bool
CodeInterpreterAbuse bool
}
LlamaGuardConfig enables Llama Guard 3 8B categories.
type MaskFileInputMethod ¶ added in v0.4.0
type MaskFileInputMethod string
MaskFileInputMethod controls how file inputs interact with masking. Required when file parts are present and masking is configured.
const ( MaskFileAnonymization MaskFileInputMethod = "anonymization" MaskFileSkip MaskFileInputMethod = "skip" )
type MaskingConfig ¶ added in v0.3.0
type MaskingConfig struct {
// Method defaults to [Anonymization] if empty.
Method MaskingMethod
// Entities to mask. Use [StandardEntities]([CommonPIIEntities]) for quick setup.
Entities []MaskingEntity
// Allowlist contains strings that should never be masked even if they match.
Allowlist []string
// MaskGroundingInput controls whether grounding module input is also masked.
MaskGroundingInput bool
// MaskFileInputMethod controls how file inputs are handled by masking.
// Required when file content blocks are present in the request.
MaskFileInputMethod MaskFileInputMethod
}
MaskingConfig configures data masking. Orchestration-mode only.
type MaskingEntity ¶ added in v0.3.0
type MaskingEntity struct {
// contains filtered or unexported fields
}
MaskingEntity is either a standard DPIEntity or a CustomEntity.
func ConstantEntity ¶ added in v0.4.0
func ConstantEntity(entity DPIEntity, replacement string) MaskingEntity
ConstantEntity replaces matches with a fixed value followed by an incrementing number.
func CustomMaskingEntity ¶ added in v0.3.0
func CustomMaskingEntity(regex, replacement string) MaskingEntity
func FabricatedEntity ¶ added in v0.4.0
func FabricatedEntity(entity DPIEntity) MaskingEntity
FabricatedEntity replaces matches with realistic fake data appropriate to the entity type.
func StandardEntities ¶ added in v0.3.0
func StandardEntities(entities []DPIEntity) []MaskingEntity
func StandardEntity ¶ added in v0.3.0
func StandardEntity(entity DPIEntity) MaskingEntity
type MaskingMethod ¶ added in v0.3.0
type MaskingMethod string
const ( Anonymization MaskingMethod = "anonymization" Pseudonymization MaskingMethod = "pseudonymization" )
type ModelOption ¶
type ModelOption func(*modelConfig)
ModelOption configures a specific model instance returned by Provider.Model.
func WithModelFallback ¶ added in v0.3.0
func WithModelFallback(models ...string) ModelOption
func WithModelFiltering ¶ added in v0.3.0
func WithModelFiltering(cfg *FilteringConfig) ModelOption
WithModelFiltering overrides provider-level filtering for this model. Pass nil for the same defaults as WithFiltering.
func WithModelMasking ¶ added in v0.3.0
func WithModelMasking(cfg MaskingConfig) ModelOption
WithModelMasking overrides provider-level masking for this model.
func WithModelParams ¶
func WithModelParams(params map[string]any) ModelOption
WithModelParams adds extra parameters forwarded directly to the model. In orchestration mode these go into model.params (e.g. thinking, reasoning_effort). In foundation-models mode these are merged into the top-level request body.
If a key conflicts with a field set via [genai.GenerateContentConfig] (e.g. "seed", "top_k", "logprobs"), the WithModelParams value takes precedence. This allows overriding any first-class parameter when needed.
Example ¶
package main
import (
"context"
"fmt"
"log"
sapaicore "github.com/PedroKlein/adk-provider-sapaicore"
)
func main() {
provider, err := sapaicore.NewProvider(context.Background(),
sapaicore.WithEndpoint("https://api.ai.prod.us-east-1.aws.ml.hana.ondemand.com"),
sapaicore.WithAuth("client-id", "client-secret", "https://auth.example.com/oauth/token"),
sapaicore.WithDeploymentID("d1234abc"),
)
if err != nil {
log.Fatal(err)
}
// Enable extended thinking for Claude models.
llm, err := provider.Model("anthropic--claude-4.5-sonnet",
sapaicore.WithModelParams(map[string]any{
"thinking": map[string]any{"type": "enabled", "budget_tokens": 16384},
"max_tokens": 64000,
}),
)
if err != nil {
log.Fatal(err)
}
fmt.Println(llm.Name())
}
Output: anthropic--claude-4.5-sonnet
func WithModelPromptCaching ¶ added in v0.3.0
func WithModelPromptCaching(ttl ...CacheTTL) ModelOption
func WithModelTranslation ¶ added in v0.3.0
func WithModelTranslation(cfg TranslationConfig) ModelOption
WithModelTranslation overrides provider-level translation for this model.
func WithoutFiltering ¶ added in v0.3.0
func WithoutFiltering() ModelOption
func WithoutMasking ¶ added in v0.3.0
func WithoutMasking() ModelOption
func WithoutTranslation ¶ added in v0.3.0
func WithoutTranslation() ModelOption
type Option ¶
type Option func(*providerConfig)
Option configures a Provider.
func WithAuth ¶
WithAuth sets the OAuth2 client credentials. authURL is the token endpoint, e.g. "https://xxx.authentication.xxx.hana.ondemand.com/oauth/token".
func WithDeploymentID ¶
WithDeploymentID enables orchestration mode using a specific deployment ID.
func WithDeployments ¶
WithDeployments enables foundation-models mode with per-model deployment IDs.
func WithEndpoint ¶
func WithFallback ¶ added in v0.3.0
WithFallback configures model fallback. The service tries the primary model first, then each fallback in order. Fallback models inherit all module configs. Orchestration-mode only.
func WithFiltering ¶ added in v0.3.0
func WithFiltering(cfg *FilteringConfig) Option
WithFiltering enables content filtering. Orchestration-mode only.
Pass nil for sensible defaults: Azure Content Safety ALLOW_SAFE on all categories with prompt_shield, applied to both input and output.
func WithHTTPClient ¶
func WithHeaders ¶
func WithMasking ¶ added in v0.3.0
func WithMasking(cfg MaskingConfig) Option
WithMasking enables PII redaction before messages reach the LLM. Orchestration-mode only. Method defaults to Anonymization if empty.
func WithMaxRetries ¶
WithMaxRetries sets the server-side retry count for LLM requests. Default is 2 retries.
func WithOrchestration ¶
func WithOrchestration() Option
WithOrchestration enables orchestration mode by automatically discovering the orchestration deployment. It queries the SAP AI Core deployments API at provider creation time to find the running orchestration deployment.
func WithPromptCaching ¶ added in v0.3.0
WithPromptCaching adds cache_control annotations to the system message and tool definitions. Orchestration-mode only. Non-Anthropic models ignore the annotation. Default TTL is 5m. Pass CacheTTL1h for 1-hour caching on supported models.
func WithResourceGroup ¶
Example ¶
package main
import (
"context"
"fmt"
"log"
sapaicore "github.com/PedroKlein/adk-provider-sapaicore"
)
func main() {
provider, err := sapaicore.NewProvider(context.Background(),
sapaicore.WithEndpoint("https://api.ai.prod.us-east-1.aws.ml.hana.ondemand.com"),
sapaicore.WithAuth("client-id", "client-secret", "https://auth.example.com/oauth/token"),
sapaicore.WithDeploymentID("d1234abc"),
sapaicore.WithResourceGroup("my-team-rg"),
)
if err != nil {
log.Fatal(err)
}
llm, err := provider.Model("gpt-4.1")
if err != nil {
log.Fatal(err)
}
fmt.Println(llm.Name())
}
Output: gpt-4.1
func WithStreamOptions ¶ added in v0.3.0
func WithStreamOptions(opts StreamOptions) Option
func WithTimeout ¶
WithTimeout sets the server-side LLM request timeout in seconds. Default is 600 seconds.
func WithTranslation ¶ added in v0.3.0
func WithTranslation(cfg TranslationConfig) Option
WithTranslation enables input/output translation. Orchestration-mode only.
type OutputFilterConfig ¶ added in v0.3.0
type OutputFilterConfig struct {
AzureContentSafety *AzureContentSafetyConfig
LlamaGuard *LlamaGuardConfig
// Overlap sets the number of characters from previous chunks sent as additional
// context to the filtering service during streaming. Only relevant when streaming.
Overlap int
}
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider creates model.LLM instances backed by SAP AI Core deployments.
func NewProvider ¶
NewProvider validates the given options and returns a ready-to-use Provider. It returns ErrMissingConfig if required options are absent.
If no mode is specified, orchestration auto-discovery is used by default. NewProvider makes an HTTP call to discover the orchestration deployment ID when auto-discovery is active.
ctx is used for any HTTP calls made during provider initialization (e.g. orchestration deployment discovery). It does not affect subsequent Model() or GenerateContent() calls.
Example (FoundationModels) ¶
package main
import (
"context"
"fmt"
"log"
sapaicore "github.com/PedroKlein/adk-provider-sapaicore"
)
func main() {
provider, err := sapaicore.NewProvider(context.Background(),
sapaicore.WithEndpoint("https://api.ai.prod.us-east-1.aws.ml.hana.ondemand.com"),
sapaicore.WithAuth("client-id", "client-secret", "https://auth.example.com/oauth/token"),
sapaicore.WithDeployments(map[string]string{
"gpt-4.1": "d1234abc",
"gpt-4.1-mini": "d5678def",
}),
)
if err != nil {
log.Fatal(err)
}
llm, err := provider.Model("gpt-4.1")
if err != nil {
log.Fatal(err)
}
fmt.Println(llm.Name())
}
Output: gpt-4.1
Example (Orchestration) ¶
package main
import (
"context"
"fmt"
"log"
sapaicore "github.com/PedroKlein/adk-provider-sapaicore"
)
func main() {
provider, err := sapaicore.NewProvider(context.Background(),
sapaicore.WithEndpoint("https://api.ai.prod.us-east-1.aws.ml.hana.ondemand.com"),
sapaicore.WithAuth("client-id", "client-secret", "https://auth.example.com/oauth/token"),
sapaicore.WithDeploymentID("d1234abc"), // or use WithOrchestration() for auto-discovery
)
if err != nil {
log.Fatal(err)
}
llm, err := provider.Model("gpt-4.1")
if err != nil {
log.Fatal(err)
}
fmt.Println(llm.Name())
}
Output: gpt-4.1
func (*Provider) Model ¶
Model returns a model.LLM for the given model name.
In orchestration mode, name is any SAP AI Core model identifier (e.g. "gpt-4.1", "anthropic--claude-4.5-sonnet").
In foundation-models mode, name must exist in the map provided to WithDeployments. Returns ErrDeploymentNotFound if the name is not registered.
type StreamOptions ¶ added in v0.3.0
type StreamOptions struct {
// ChunkSize is the minimum characters per chunk that post-LLM modules operate on.
ChunkSize int
// Delimiters to split text into chunks. Required when translation is active with streaming.
Delimiters []string
}
StreamOptions configures global streaming behavior for orchestration modules.
type TranslationConfig ¶ added in v0.3.0
type TranslationConfig struct {
Input *TranslationInputConfig
Output *TranslationOutputConfig
}
TranslationConfig configures translation. Orchestration-mode only. At least one of Input or Output must be set.
type TranslationInputConfig ¶ added in v0.3.0
type TranslationOutputConfig ¶ added in v0.3.0
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
auth
Package auth manages OAuth2 client-credentials tokens with thread-safe caching.
|
Package auth manages OAuth2 client-credentials tokens with thread-safe caching. |
|
convert
Package convert transforms between Google genai types and OpenAI-compatible wire types.
|
Package convert transforms between Google genai types and OpenAI-compatible wire types. |
|
foundation
Package foundation implements the SAP AI Core foundation-models mode strategy.
|
Package foundation implements the SAP AI Core foundation-models mode strategy. |
|
openai
Package openai defines wire types for the OpenAI-compatible chat completions format used by both SAP AI Core API modes.
|
Package openai defines wire types for the OpenAI-compatible chat completions format used by both SAP AI Core API modes. |
|
orchestration
Package orchestration implements the SAP AI Core orchestration mode strategy.
|
Package orchestration implements the SAP AI Core orchestration mode strategy. |
|
request
Package request provides shared HTTP execution for SAP AI Core inference requests.
|
Package request provides shared HTTP execution for SAP AI Core inference requests. |
|
stream
Package stream handles Server-Sent Events parsing and incremental aggregation of streaming chat completion responses.
|
Package stream handles Server-Sent Events parsing and incremental aggregation of streaming chat completion responses. |
|
Package smoketest provides integration tests against a live SAP AI Core instance.
|
Package smoketest provides integration tests against a live SAP AI Core instance. |