惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
N
News and Events Feed by Topic
D
DataBreaches.Net
MongoDB | Blog
MongoDB | Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Engineering at Meta
Engineering at Meta
T
Tailwind CSS Blog
博客园_首页
Microsoft Azure Blog
Microsoft Azure Blog
Y
Y Combinator Blog
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
月光博客
月光博客
A
About on SuperTechFans
I
InfoQ
S
Securelist
Last Week in AI
Last Week in AI
S
Schneier on Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
Hacker News: Ask HN
Hacker News: Ask HN
Schneier on Security
Schneier on Security
Know Your Adversary
Know Your Adversary
腾讯CDC
大猫的无限游戏
大猫的无限游戏
S
Security @ Cisco Blogs
博客园 - 三生石上(FineUI控件)
Simon Willison's Weblog
Simon Willison's Weblog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Tor Project blog
美团技术团队
aimingoo的专栏
aimingoo的专栏
G
Google Developers Blog
罗磊的独立博客
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
S
Secure Thoughts
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Latest news
Latest news
Recent Announcements
Recent Announcements
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
LINUX DO - 热门话题
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
A practical SAP agent in Azure AI Foundry: OData in, governed answer out
Der Sascha · 2026-05-14 · via DEV Community

Most enterprise agent demos cheat at the exact point where things get interesting.

They show a nice chat window. They connect it to a toy API. The agent calls a function, gets a clean JSON response, and everyone nods. Then you try the same pattern against a real SAP system and suddenly the demo has to deal with authorization, OData filters, weird field names, data minimization, audit logs, and the uncomfortable fact that "ask the model to query SAP" is not an architecture.

This post is the version I would actually start with.

The scenario is intentionally boring: a support or operations user asks why a customer order is blocked. The agent should look up a small, approved slice of SAP data, summarize the situation, and suggest the next action. No direct database access. No model-generated OData. No magic prompt that says "be secure" and hopes for the best.

The shape of the solution

I would split the system into four parts:

  1. Azure AI Foundry hosts the agent and handles the conversation.
  2. The agent gets one narrow tool, for example get_order_status.
  3. A backend service owns the SAP integration and calls an approved OData endpoint.
  4. Identity, logging, and policy live outside the prompt.

The agent is allowed to ask a question. The tool is allowed to fetch a specific business object. The SAP layer is allowed to enforce the ugly but necessary rules.

That separation matters. If the model can invent arbitrary OData queries, it can also invent expensive, broad, or unauthorized queries. If the backend only exposes a small function with typed parameters, the blast radius is much smaller.

Example architecture

A minimal production-ish flow looks like this:

User
  -> Teams / web app / Copilot extension
  -> Azure AI Foundry agent
  -> function tool: get_order_status(order_id)
  -> integration API
  -> SAP OData endpoint / SAP BTP destination / API Management
  -> sanitized JSON back to the agent
  -> short answer + next action

Enter fullscreen mode Exit fullscreen mode

I like putting Azure API Management or a small integration API between Foundry and SAP. It gives you one place for throttling, logging, allow lists, correlation IDs, and request validation. You can also swap the SAP backend later without teaching the agent a new trick.

The SAP side: keep it boring

Here is a deliberately small Python client for an SAP OData endpoint. The important part is not the HTTP library. The important part is that the caller cannot pass arbitrary filters.

# sap_client.py
import os
import requests
from dataclasses import dataclass


@dataclass(frozen=True)
class OrderStatus:
    order_id: str
    customer_name: str
    lifecycle_status: str
    delivery_block: str | None
    credit_block: str | None
    net_value: float
    currency: str


class SapClient:
    def __init__(self) -> None:
        self.base_url = os.environ["SAP_ODATA_BASE_URL"].rstrip("/")
        self.username = os.environ["SAP_TECH_USER"]
        self.password = os.environ["SAP_TECH_PASSWORD"]

    def get_order_status(self, order_id: str) -> OrderStatus:
        if not order_id.isdigit() or len(order_id) > 12:
            raise ValueError("order_id must be a numeric SAP sales order id")

        url = f"{self.base_url}/sap/opu/odata/sap/API_SALES_ORDER_SRV/A_SalesOrder('{order_id}')"
        params = {
            "$select": ",".join([
                "SalesOrder",
                "SoldToPartyName",
                "OverallSDProcessStatus",
                "DeliveryBlockReason",
                "CreditBlockReason",
                "TotalNetAmount",
                "TransactionCurrency",
            ])
        }

        response = requests.get(
            url,
            params=params,
            auth=(self.username, self.password),
            headers={"Accept": "application/json"},
            timeout=10,
        )
        response.raise_for_status()

        data = response.json()["d"]
        return OrderStatus(
            order_id=data["SalesOrder"],
            customer_name=data.get("SoldToPartyName", ""),
            lifecycle_status=data.get("OverallSDProcessStatus", "Unknown"),
            delivery_block=data.get("DeliveryBlockReason") or None,
            credit_block=data.get("CreditBlockReason") or None,
            net_value=float(data.get("TotalNetAmount", 0)),
            currency=data.get("TransactionCurrency", ""),
        )

Enter fullscreen mode Exit fullscreen mode

A real implementation would probably use OAuth, principal propagation, SAP BTP destinations, or an API Management policy instead of a technical user. Fine. The same rule still applies: the agent should not build the SAP query. Your integration layer should.

The tool boundary

Now wrap the SAP client in a tiny tool function. This is also the place where I would remove fields the user should not see.

# tools.py
from sap_client import SapClient

sap = SapClient()


def get_order_status(order_id: str) -> dict:
    """Return a sanitized status summary for one SAP sales order."""
    status = sap.get_order_status(order_id)

    blocks = []
    if status.delivery_block:
        blocks.append({"type": "delivery", "reason": status.delivery_block})
    if status.credit_block:
        blocks.append({"type": "credit", "reason": status.credit_block})

    return {
        "order_id": status.order_id,
        "customer_name": status.customer_name,
        "lifecycle_status": status.lifecycle_status,
        "blocks": blocks,
        "net_value": status.net_value,
        "currency": status.currency,
    }

Enter fullscreen mode Exit fullscreen mode

Notice what is missing: pricing conditions, margin, bank details, free text notes, internal partner data, and anything else that tends to leak into "just give the AI access" projects.

The model gets the minimum amount of data needed to answer the business question.

Registering the tool in Azure AI Foundry

The current Azure AI Foundry agent pattern is straightforward: define a function tool, create an agent version, send a user prompt, execute the requested function call in your app, and submit the tool output back to the model.

The sketch below follows that shape. It is not meant to be pasted blindly into production, but it shows the moving parts.

# foundry_agent.py
import json
import os

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import FunctionTool, PromptAgentDefinition, Tool
from azure.identity import DefaultAzureCredential
from openai.types.responses.response_input_param import (
    FunctionCallOutput,
    ResponseInputParam,
)

from tools import get_order_status

project = AIProjectClient(
    endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential(),
)

openai = project.get_openai_client()
conversation = openai.conversations.create()

get_order_status_tool = FunctionTool(
    name="get_order_status",
    description="Get the sanitized status of one SAP sales order by numeric order id.",
    parameters={
        "type": "object",
        "properties": {
            "order_id": {
                "type": "string",
                "description": "Numeric SAP sales order id, for example 4711000420",
            }
        },
        "required": ["order_id"],
        "additionalProperties": False,
    },
    strict=True,
)

tools: list[Tool] = [get_order_status_tool]

agent = project.agents.create_version(
    agent_name="sap-order-status-agent",
    definition=PromptAgentDefinition(
        model="gpt-4.1-mini",
        instructions=(
            "You help operations users understand SAP sales order status. "
            "Use the provided tool when an order id is present. "
            "Do not ask for or expose sensitive personal, payroll, banking, or margin data. "
            "Answer briefly. If a block exists, explain the likely owner and next action."
        ),
        tools=tools,
    ),
)

response = openai.responses.create(
    input="Why is sales order 4711000420 blocked?",
    conversation=conversation.id,
    extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)

tool_outputs: ResponseInputParam = []

for item in response.output:
    if item.type == "function_call" and item.name == "get_order_status":
        args = json.loads(item.arguments)
        result = get_order_status(**args)
        tool_outputs.append(
            FunctionCallOutput(
                type="function_call_output",
                call_id=item.call_id,
                output=json.dumps(result),
            )
        )

final_response = openai.responses.create(
    input=tool_outputs,
    conversation=conversation.id,
    extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)

print(final_response.output_text)

Enter fullscreen mode Exit fullscreen mode

A possible answer might be:

Sales order 4711000420 is blocked because it has a credit block.
The order value is 18,420 EUR for Contoso Retail GmbH.
Next action: ask credit management to review the customer exposure before release.

Enter fullscreen mode Exit fullscreen mode

That is the right level of boring. The agent did not browse SAP. It did not decide which table to query. It called one approved capability.

Add correlation IDs before you add more tools

Before I would add a second or third SAP tool, I would add tracing.

Every request should carry a correlation ID from the UI to Foundry, from Foundry to the integration API, and from the integration API to SAP or API Management logs.

# api.py
from fastapi import FastAPI, Header, HTTPException
from tools import get_order_status

app = FastAPI()


@app.get("/orders/{order_id}/status")
def order_status(order_id: str, x_correlation_id: str | None = Header(default=None)):
    if not x_correlation_id:
        raise HTTPException(status_code=400, detail="Missing X-Correlation-ID")

    result = get_order_status(order_id)

    # In production, log this as structured telemetry.
    # Never log secrets or full SAP payloads.
    print({
        "correlation_id": x_correlation_id,
        "tool": "get_order_status",
        "order_id": order_id,
        "block_count": len(result["blocks"]),
    })

    return result

Enter fullscreen mode Exit fullscreen mode

This is the part that gets skipped in demos and then hurts later. When a user says "the agent told me the wrong thing," you need to reconstruct what it saw, which tool it called, what SAP returned, and which policy version was active.

Without that, you are debugging vibes.

Where the avatar fits

If you are building a Casandra-style avatar on top of this, I would keep the avatar layer dumb.

The avatar can make the interaction feel nicer. It can speak, explain, ask follow-up questions, and show the answer in a more human way. But it should not own the SAP permissions, the OData query, or the policy decisions.

A clean split looks like this:

Avatar / UI:
  - captures the user request
  - shows status and confidence
  - asks for missing order id
  - renders the final answer

Foundry agent:
  - decides whether a tool call is needed
  - turns tool output into an explanation
  - follows response policy

Integration backend:
  - validates input
  - calls SAP
  - trims data
  - logs access
  - enforces authorization

Enter fullscreen mode Exit fullscreen mode

That makes the avatar replaceable. Today it is a web avatar. Tomorrow it might be Teams, Copilot, a mobile app, or a voice interface. The SAP contract stays the same.

The policies I would enforce early

I would not wait for an enterprise governance board to invent a 40-page document. Start with five rules in code:

  • Only approved tools can access SAP.
  • Tools must have typed schemas and additionalProperties: false.
  • The model never receives raw SAP payloads.
  • Every tool call gets a user id, tenant/context id, and correlation id.
  • Tool output is logged as metadata, not as full business data.

Those five rules already avoid a lot of trouble.

A small test that catches a big mistake

Here is the kind of test I would add before showing the agent to anyone outside the team:

# test_tools.py
import pytest
from tools import get_order_status


def test_rejects_non_numeric_order_ids():
    with pytest.raises(ValueError):
        get_order_status("4711; $filter=NetValue gt 0")


def test_tool_does_not_return_internal_fields(monkeypatch):
    class FakeSap:
        def get_order_status(self, order_id):
            return type("OrderStatus", (), {
                "order_id": order_id,
                "customer_name": "Contoso Retail GmbH",
                "lifecycle_status": "Blocked",
                "delivery_block": None,
                "credit_block": "Credit exposure exceeded",
                "net_value": 18420.0,
                "currency": "EUR",
                "margin": 0.42,
                "internal_note": "Do not expose this",
            })()

    import tools
    monkeypatch.setattr(tools, "sap", FakeSap())

    result = get_order_status("4711000420")

    assert "margin" not in result
    assert "internal_note" not in result
    assert result["blocks"][0]["type"] == "credit"

Enter fullscreen mode Exit fullscreen mode

A test like this is not glamorous. Good. Glamour is usually where agent projects start lying to themselves.

My take

For SAP integration, Azure AI Foundry becomes interesting when you stop treating it as a chatbot builder and start treating it as an orchestration layer with strict tool contracts.

The model should explain. Your backend should decide what data exists, who can see it, and how it is fetched.

That is less flashy than "natural language over SAP," but it is much closer to something I would trust in a real environment.


Originally published at https://blog.bajonczak.com/a-practical-sap-agent-in-azure-ai-foundry-odata-in-governed-answer-out/.