mcpField
S
sap-cloud-sdk-ai-python

sap-cloud-sdk-ai-python

github.com/secondsky开发480562 次安装3 周前更新
代码仓库

关于 sap-cloud-sdk-ai-python

用于通过 SAP AI Core 使用 SAP Generative AI Hub 与 Orchestration Service 构建应用的 Python SDK 技能,涵盖原生模型客户端、LangChain、文档 grounding、评估及迁移到更名后的 `sap-ai-sdk-gen`。

主要功能

  1. 01各提供商的原生模型客户端
  2. 02LangChain LLM 与嵌入集成
  3. 03用于模板处理和过滤的编排
  4. 04文档 grounding 与提示词注册表
  5. 05模型评估及 SAP RPT-1 支持
  6. 06`sap-ai-sdk-gen` 迁移指南

适用场景

  1. 01通过 SAP AI Core 调用支持的提供商模型
  2. 02使用 SAP AI Core 构建 LangChain 应用
  3. 03应用编排模块进行过滤或数据屏蔽
  4. 04从 `generative-ai-hub-sdk` 迁移

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/secondsky/sap-skills --skill sap-cloud-sdk-ai-python

安装后在 Claude Code 中输入/sap-cloud-sdk-ai-python确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
agents/
openai.yaml
references/
getting-started-auth.md
langchain-guide.md
native-clients-guide.md
orchestration-guide.md
troubleshooting.md

详细介绍

SAP Cloud SDK for AI(Python)

软件包更名:PyPI 软件包 generative-ai-hub-sdk 已弃用(v4.12.4 是最后一个版本)。 其后继软件包是 sap-ai-sdk-gen(根据截至 2026-06-15 的公开 PyPI 注册表信息,当前版本为 v6.10.0)。引用 generative-ai-hub-sdk 的代码和教程应迁移到 sap-ai-sdk-gen;导入名称仍为 gen_ai_hub。

SAP Generative AI Hub 和 Orchestration Service 的官方 Python SDK。它封装了模型提供商(OpenAI、Amazon Bedrock、Google GenAI)的原生 SDK,并提供统一的 LangChain 集成和完整的 Orchestration 客户端——所有请求均通过 SAP AI Core 路由,并使用统一身份验证。软件包的最新状态已通过注册表验证;AI Core 的运行时行为和具体模型的可用性仍需在目标租户中验证。

相关技能

  • sap-ai-core:SAP AI Core 中的平台设置、部署、资源组和模型管理
  • sap-cloud-sdk-ai:此 SDK 的 JavaScript/TypeScript 和 Java 版本
  • sap-hana-ml:HANA 侧的 Python 机器学习
  • sap-dependency-security:Pip 依赖项管理规范和升级模式
相关外部技能

如果你的任务涉及在 Databricks 中工作(笔记本、Unity Catalog、Spark、 SAP Business Data Cloud 中的 SAP Databricks),请考虑安装 Databricks agent skills plugin。 询问对方是否需要安装帮助——切勿未经询问就安装。

何时使用此技能

在以下情况下使用此技能:

  • 构建通过 SAP AI Core / Generative AI Hub 调用大模型的 Python 应用程序
  • 使用 gen_ai_hub Python 软件包(安装名称为 sap-ai-sdk-gen)
  • 通过 SAP 的代理集成 OpenAI、Amazon Bedrock 或 Google GenAI 模型
  • 使用 SAP AI Core 作为后端实现 LangChain 链
  • 从 Python 使用 Orchestration Service(模板化、过滤、脱敏、基于知识)
  • 将代码从已弃用的 generative-ai-hub-sdk 迁移到 sap-ai-sdk-gen
  • 通过 SAP AI Core 生成嵌入
  • 使用 SAP RPT-1(Relational Pretrained Transformer)进行表格预测

目录

快速入门

原生 OpenAI 聊天补全
from gen_ai_hub.proxy.native.openai import chat

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is SAP BTP?"}
]

response = chat.completions.create(
    model_name="gpt-4o-mini",
    messages=messages
)
print(response.choices[0].message.content)
Orchestration Service
from gen_ai_hub.orchestration_v2 import (
    OrchestrationConfig, OrchestrationService,
    ModuleConfig, PromptTemplatingModuleConfig,
    Template, UserMessage, LLMModelDetails
)

config = OrchestrationConfig(
    modules=ModuleConfig(
        prompt_templating=PromptTemplatingModuleConfig(
            prompt=Template(
                template=[UserMessage(role="user", content="{{?question}}")]
            ),
            model=LLMModelDetails(name="gpt-4o-mini")
        )
    )
)

service = OrchestrationService(config=config)
response = service.run(placeholder_values={"question": "What is SAP?"})
print(response.final_result.choices[0].message.content)

安装

# All providers + LangChain support
pip install "sap-ai-sdk-gen[all]"

# Default (OpenAI only, no LangChain)
pip install sap-ai-sdk-gen

# Specific providers (without LangChain)
pip install "sap-ai-sdk-gen[google, amazon]"

身份验证

SDK 通过 AICoreV2Client.from_env() 读取凭据,并按以下顺序解析:

  1. 传递给 GenAIHubProxyClient(...) 的关键字参数
  2. 环境变量 — AICORE_CLIENT_ID、AICORE_CLIENT_SECRET、 AICORE_AUTH_URL、AICORE_BASE_URL、AICORE_RESOURCE_GROUP
  3. 配置文件 — $AICORE_HOME/config.json(或由 AICORE_CONFIG 设置的路径); 使用 AICORE_PROFILE 选择命名配置
  4. VCAP_SERVICES — 在 Cloud Foundry/Kyma 上绑定 AI Core 服务时自动使用
本地开发(环境变量)
export AICORE_CLIENT_ID="sb-..."
export AICORE_CLIENT_SECRET="..."
export AICORE_AUTH_URL="https://<tenant>.authentication.sap.hana.ondemand.com/oauth/token"
export AICORE_BASE_URL="https://api.ai.prod.eu-central-1.aws.ml.hana.ondemand.com/v2"
export AICORE_RESOURCE_GROUP="default"
配置文件配置
# ~/.aicore/config.json
{
  "AICORE_CLIENT_ID": "sb-...",
  "AICORE_CLIENT_SECRET": "...",
  "AICORE_AUTH_URL": "https://<tenant>.authentication.sap.hana.ondemand.com/oauth/token",
  "AICORE_BASE_URL": "https://api.ai.prod.eu-central-1.aws.ml.hana.ondemand.com/v2",
  "AICORE_RESOURCE_GROUP": "default"
}

有关身份验证设置和故障排除的详细信息,请参阅 references/getting-started-auth.md。

可用模块

模块导入路径用途
代理(原生客户端)gen_ai_hub.proxy.native.*直接访问各提供商的模型
LangChain 集成gen_ai_hub.proxy.langchaininit_llm、init_embedding_model、ChatOpenAI 等
编排gen_ai_hub.orchestration_v2模板化、过滤、脱敏、知识落地
文档知识落地gen_ai_hub.document_grounding流水线、向量、检索 API
提示词注册表gen_ai_hub.prompt_registry模板管理和配置存储
评估gen_ai_hub.evaluations模型评估运行和指标
SAP RPT-1gen_ai_hub.proxy.native.sap表格预测(分类、回归)
各提供商的原生客户端
提供商导入路径主要类
OpenAIgen_ai_hub.proxy.native.openaiOpenAI、completions、chat、embeddings、responses
Amazon Bedrockgen_ai_hub.proxy.native.amazonSession、ClientWrapper
Google GenAIgen_ai_hub.proxy.native.google_genaiClient
SAP RPT-1gen_ai_hub.proxy.native.sapRPTClient、RPTRequest

支持的模型

生成式 AI Hub 目录包含来自多个提供商的模型。权威模型 ID 请查阅 SAP 的模型目录 以及目标租户目录。示例系列:

提供商示例系列
OpenAIGPT 系列聊天、多模态、推理和嵌入模型
Anthropic(通过 Bedrock)Claude 系列模型
AmazonNova/Titan 系列模型
GoogleGemini 系列模型
MistralMistral 系列模型
SAP启用时提供的 RPT 系列表格预测模型

核心功能

使用 OpenAI 客户端完成聊天
from gen_ai_hub.proxy.native.openai import OpenAI

client = OpenAI()
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Explain CAP in one paragraph."}]
)
print(response.choices[0].message.content)
流式传输
from gen_ai_hub.proxy.native.openai import OpenAI

client = OpenAI()
stream = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Explain SAP CAP."}],
    stream=True
)
for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
嵌入
from gen_ai_hub.proxy.native.openai import embeddings

response = embeddings.create(
    input="Every decoding is another encoding.",
    model_name="text-embedding-3-small"
)
print(response.data[0].embedding)
LangChain 集成
from gen_ai_hub.proxy.langchain import init_llm, init_embedding_model

llm = init_llm("gpt-4o-mini", max_tokens=300)
result = llm.invoke("What is SAP BTP?")
print(result.content)

embeddings = init_embedding_model("text-embedding-3-small")
vector = embeddings.embed_query("SAP Business Technology Platform")
内容过滤(通过编排)
from gen_ai_hub.orchestration_v2 import (
    OrchestrationConfig, OrchestrationService,
    ModuleConfig, PromptTemplatingModuleConfig,
    Template, UserMessage, LLMModelDetails,
    FilteringModuleConfig, InputFiltering, OutputFiltering,
    AzureContentSafetyInput, AzureContentSafetyOutput, AzureThreshold
)

config = OrchestrationConfig(
    modules=ModuleConfig(
        prompt_templating=PromptTemplatingModuleConfig(
            prompt=Template(template=[UserMessage(role="user", content="{{?question}}")]),
            model=LLMModelDetails(name="gpt-4o-mini")
        ),
        filtering=FilteringModuleConfig(
            input=InputFiltering(filters=[
                AzureContentSafetyInput(hate=AzureThreshold.ALLOW_SAFE, violence=AzureThreshold.ALLOW_SAFE)
            ]),
            output=OutputFiltering(filters=[
                AzureContentSafetyOutput(hate=AzureThreshold.ALLOW_SAFE, violence=AzureThreshold.ALLOW_SAFE)
            ])
        )
    )
)

service = OrchestrationService(config=config)
response = service.run(placeholder_values={"question": "Explain SAP."})
数据脱敏(通过编排)
from gen_ai_hub.orchestration_v2 import (
    OrchestrationConfig, OrchestrationService,
    ModuleConfig, PromptTemplatingModuleConfig,
    Template, UserMessage, LLMModelDetails,
    MaskingModuleConfig, MaskingProviderConfig,
    DPIStandardEntity, MaskingMethod, DataMaskingProviderName
)

config = OrchestrationConfig(
    modules=ModuleConfig(
        prompt_templating=PromptTemplatingModuleConfig(
            prompt=Template(template=[UserMessage(role="user", content="{{?text}}")]),
            model=LLMModelDetails(name="gpt-4o-mini")
        ),
        masking=MaskingModuleConfig(
            masking_providers=[
                MaskingProviderConfig(
                    type=DataMaskingProviderName.SAP_DATA_PRIVACY_INTEGRATION,
                    method=MaskingMethod.ANONYMIZATION,
                    entities=[
                        DPIStandardEntity(type="profile-email"),
                        DPIStandardEntity(type="profile-person")
                    ]
                )
            ]
        )
    )
)

service = OrchestrationService(config=config)
response = service.run(placeholder_values={"text": "Contact [email protected] for details."})
文档知识落地(通过编排)
from gen_ai_hub.orchestration_v2 import (
    OrchestrationConfig, OrchestrationService,
    ModuleConfig, PromptTemplatingModuleConfig,
    Template, UserMessage, LLMModelDetails,
    GroundingModuleConfig, DocumentGroundingConfig,
    DocumentGroundingFilter, DocumentGroundingPlaceholders,
    GroundingSearchConfig, DataRepositoryType, GroundingType
)

config = OrchestrationConfig(
    modules=ModuleConfig(
        prompt_templating=PromptTemplatingModuleConfig(
            prompt=Template(template=[UserMessage(role="user", content="{{?question}}")]),
            model=LLMModelDetails(name="gpt-4o-mini")
        ),
        grounding=GroundingModuleConfig(
            type=GroundingType.DOCUMENT_GROUNDING_SERVICE,
            config=DocumentGroundingConfig(
                placeholders=DocumentGroundingPlaceholders(
                    input=["{{?question}}"],
                    output="{{?context}}"
                ),
                filters=[
                    DocumentGroundingFilter(
                        id="my-vector-repo-id",
                        data_repository_type=DataRepositoryType.VECTOR,
                        search_config=GroundingSearchConfig(max_chunk_count=5)
                    )
                ]
            )
        )
    )
)

service = OrchestrationService(config=config)
response = service.run(placeholder_values={"question": "What is the refund policy?"})

常见错误

错误原因解决方案
No credentials found in any source缺少 AI Core 服务密钥/环境变量设置所有 AICORE_* 环境变量,或创建配置文件配置项
No deployment foundAI Core 中未部署模型在资源组中部署模型,或直接使用 deployment_id
AICORE_RESOURCE_GROUP not set缺少资源组设置 AICORE_RESOURCE_GROUP 环境变量,或向客户端传入 resource_group
ModuleNotFoundError: No module named 'gen_ai_hub'安装了错误的软件包安装 sap-ai-sdk-gen(而非 generative-ai-hub-sdk)
从 generative_ai_hub_sdk 导入失败使用了已弃用的软件包名称软件包已重命名;请从 gen_ai_hub 导入(通过 sap-ai-sdk-gen 安装)
初始化代理客户端时出现 ValidationError凭据不完整确认以下四个必需的环境变量均已设置:AICORE_CLIENT_ID、AICORE_CLIENT_SECRET、AICORE_AUTH_URL、AICORE_BASE_URL

随附资源

参考文档
  1. references/getting-started-auth.md - 安装、身份验证和配置设置
  2. references/native-clients-guide.md - OpenAI、Amazon、Google 和 SAP RPT-1 原生客户端用法
  3. references/orchestration-guide.md - 编排服务:模板化、过滤、脱敏、知识落地、嵌入
  4. references/langchain-guide.md - LangChain 集成:LLM/嵌入初始化、链、结构化输出
  5. references/troubleshooting.md - 常见错误、版本兼容性,以及从 generative-ai-hub-sdk 迁移

文档来源

请使用以下来源更新此技能:

评论

支持 Markdown