Technology Blog Posts by SAP
cancel
Showing results for 
Search instead for 
Did you mean: 
Hrb24
Product and Topic Expert
Product and Topic Expert
26,943

 

The Vision: Talk to your SAP system

Do you use still SAP transactions? Talk with your SAP system! AI can do the same things like you but faster and smarter!

What the agent does:

  • Connect to your live SAP GUI session via COM
  • Navigate through SAP transactions
  • Export data and do analysis on it

🛠️ What We Built: The SAP GUI Scripting AI Agent

This Python application combines cutting-edge AI frameworks with battle-tested SAP automation:

Tech Stack:
├── 🖥️ pywin32 (COM automation for SAP GUI)
├── 📊 openpyxl (Excel generation)
├── 📚 sap_scripting.py (reusable SAP GUI API sap_gui_scripting_api.pdf )
└── 📝 CLAUDE.md (living project documentation)

Core Capabilities Demonstrated

Capability Description

Live SAP GUI ConnectionROT-based COM access to running sessions
Intelligent NavigationTransaction execution, screen exploration, button discovery
Complex Grid ParsingTree controls, ALV grids, splitter shells, dynamic content
Error AnalysisMessage classification, severity scoring, root cause mapping
Excel AutomationStructured remediation plans with SAP transaction references
Conversational InterfaceNatural language → structured SAP operations

📊The Real-World Use Case: DMLT Posting Engine Error Analysis

Context: Migration project has 14,000+ posting simulation errors

Top 3 Critical Errors (from 10 total message classes)

# Message Count Severity Solution

1NR 751 - Number range interval missing9999+🔴HIGHFBN1/SNRO → Maintain number ranges in target
2CNV_PE 451 - TRule error2,328🔴HIGHCNV_PE_CUSTOM → Read Customizing + Regenerate TRules
3CNV_OT_CX 000 - Generic exception1,746🔴HIGHST22/SM21 → Check dumps/system log for root cause

Complete Error Analysis Generated

Message Count Severity Root Cause SAP Transaction

NR 7519999+HIGHNumber range gapFBN1/SNRO
CNV_PE 4512,328HIGHTRule customizationCNV_PE_CUSTOM
CNV_OT_CX 0001,746HIGHSystem exceptionST22/SM21
F5A 00286MEDIUMVendor deletion flagXK02/FK02
CNV_PE 58954MEDIUMWL2MOD exit errorDebug ABAP exit
CNV_PE 20551MEDIUMReference doc missingPost ref docs first
F5 35117MEDIUMAccount blockedFS00/FK02
F5A 00314MEDIUMG/L deletion flagFS00
F5 02610LOWMissing bank detailsFK02
/SLO/PECON 1025LOWWHT data missingFK02

🏗️ Architecture: How the Agent Works

┌─────────────────────────────────────────────────────────────────┐
│                    User: Natural Language Request               │
└─────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────┐
│  1. COM Connection → session.Info → System validation           │
│  2. /SLO/PECON → Error Monitor (ERR_OV) → F8 Execute           │
│  3. Tree Control parsing → MSGNO/MSGCNT_RCV/MSGTEXT extraction │
│  4. LLM Reasoning → Severity classification + solution mapping  │
│  5. openpyxl → Structured Excel with 2 sheets                   │
└─────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────┐
│              Output: PE_Error_Analysis_ZFI_SDT.xlsx             │
└─────────────────────────────────────────────────────────────────┘

SAP Connection Pattern (ROT-based COM)

import win32com.client

# Connect to RUNNING SAP session (never launch from script)
SapGuiAuto = win32com.client.GetObject("SAPGUI")
application = SapGuiAuto.GetScriptingEngine
connection = application.Children(0)   # first connection
session = connection.Children(0)       # first session

# Validate connection
print(f"System: {session.Info.SystemName}")
print(f"Client: {session.Info.Client}")
print(f"User: {session.Info.User}")

💰Why This Matters

Traditional Approach AI Agent Approach

Manual Error Monitor → Export → Excel → Manual analysis → 4+ hours"Check errors and create Excel"Done in 2 minutes
Static SQL queries → Miss dynamic tree dataLive GUI parsing → Always current
Generic error listsSeverity-ranked remediation with exact transactions
Consultant dependencySelf-service analysis for any team member

 


💬The Conversation That Built This

Here's the actual conversation flow with Claude Code that produced this solution:

User: "List SAP connections"
Agent: → Found 2 connections

User: "Test System"
Agent: → Connected to system

User: "Open /SLO/PECON"
Agent: → Transaction opened, PECON Start screen displayed

User: "Go into Error Monitor, check messages, create Excel with solutions"
Agent: → Clicked ERR_OV → F8 Execute → Parsed tree (16 nodes)
      → Generated PE_Error_Analysis.xlsx with 10 errors + solutions

Total time: ~2 minutes. Zero manual SAP navigation.


Prerequisites (Production-Ready)

  • Windows OS + SAP GUI for Windows
  • Scripting enabled (Alt+F12 → Options → Scripting)
  • RZ11: sapgui/user_scripting = TRUE
  • Open SAP session before agent execution
  • Python 3.11+ with virtual environment

📁Project Structure

sap_gui_scripting_ai/
├── 📚 sap_scripting.py            # SAP GUI Scripting Framework Generic Python wrapper#├── 📝 CLAUDE.md                   # Living documentation (auto-updated)
├── 📊 PE_Error_Analysis.xlsx      # Generated output
└── 📁 posting_engine_knowledge/   # SAP docs + extracted knowledge
    ├── PECON_User_Guide_v2.1.pdf
    ├── PECON_FAQ_v1.5.pdf
    └── PE_Enablement_2025_10.pdf

 


FAQs

Q: Does this replace SAP GUI scripting consultants? A: It augments them. The agent handles 80% of repetitive analysis; consultants focus on exceptions.

Q: Is this safe for Production SAP? A: Read-only analysis mode. No postings, no data changes. Uses your existing session permissions.

Q: What SAP systems are supported? A: Any SAP GUI system with scripting enabled — ECC, S/4HANA, any client. Multi-system aware.

Q: Can it handle custom Z-transactions? A: Yes! Recursive screen exploration + visual debugging discovers any SAP screen pattern.

Q: What LLM powers the agent? A: Currently using Claude (Anthropic) via LangChain, but architecture supports OpenAI, Azure, or local models.


📣What's Coming in Part 1?

  • 🎥Live demo video (agent solving NR 751 in real-time)
  • 🛠️ Step-by-step setup (5 minutes to first execution)
  • 🔧Advanced patterns (Outlook integration, multi-session handling)
  • 📈Scaling to production (error handling, logging, monitoring)
  • 💻Full source code walkthrough

👍Like this post if you want Part 1 next week!


Share your SAP challenges in the comments below — which analysis blocks you most often?

8 Comments
Hrb24
Product and Topic Expert
Product and Topic Expert

I asked Claude Code:  "what is your opinion about the library? Can you create dynamically new scripts or steps to fulfill a lot of different actions in SAP GUI?"

-----------------------------------------------------------------------------------------
Good question. Let me give you an honest, technical assessment.

What the library does well

Navigation and field interaction  start_transaction, set_field, send_vkey, press_button cover probably 80% of what any SAP script needs to do. These are generic enough to work across any transaction.

Grid reading  grid_read_all with find_grid is the most valuable piece. ALV grids appear everywhere in SAP reporting, so this one function unlocks hundreds of transactions.

Screen exploration  explore_screen is a genuine capability multiplier. It lets you discover field IDs on unknown screens without manual inspection.

Helper patterns  run_transaction_report is a good abstraction. One function call can drive FBL1N, MB52, VA05, ME2M and many others with just different parameters.


Honest limitations

1. Dynamic script generation — partially yes, but with a catch

The library gives Claude (or any LLM) enough primitives to compose new scripts. If you describe a task in plain language, I can write a script using these building blocks. But there's a problem: field IDs are system-specific. The path wnd[0]/usr/ctxtFIELD_NAME can differ between SAP releases, customizations, and screen variants. I can write the logic, but I can't guarantee the IDs without seeing your specific system.

2. find_grid is brittle

It only tries 5 hardcoded paths. Many transactions use custom container names. If none of the 5 match, it returns None silently. A real dynamic approach would need recursive tree traversal.

3. No scroll/pagination support

grid_read_all reads only what's currently visible or loaded. For large result sets, SAP paginates the grid. Without scroll logic, you silently get partial data — this is a significant gap.

4. Table controls vs. GridView

table_read_cell exists but is basic. Many classic SAP transactions (MM03, XK03, FB03) use dynpro table controls, not ALV grids. These need different traversal logic.

5. No recording/discovery mode

SAP's own Script Recorder generates IDs automatically by watching your clicks. The library has explore_screen but no equivalent of "watch me do this once, then repeat it." That would be the real dynamic capability.


Can I create new scripts dynamically from this?

Yes, for a large class of problems:

  • Any report transaction with a selection screen + ALV grid output → I can write the script
  • Any transaction where you can describe the fields and steps → I can compose it from the primitives

No, reliably, for:

  • Complex multi-screen workflows (purchasing, goods receipt, FI posting) without first running explore_screen to discover actual IDs
  • Transactions with non-standard grid containers
  • Anything requiring pagination of large datasets

What would make it truly dynamic

The one addition that would change the game is a recursive screen walker that returns the full element tree of any screen. With that, Claude could:

  1. You navigate to a screen manually
  2. Call explore_screen_deep()
  3. Claude reads the tree, understands what's there, writes the targeted script

That would make the "describe what you want → get a working script" loop much more reliable. Right now explore_screen only goes 2 levels deep, which often misses elements inside nested containers.


Bottom line: The library is a solid, usable foundation. It can dynamically generate scripts for reporting/extraction tasks well. For complex transactional workflows, it needs either screen-specific knowledge upfront, or a deeper exploration capability to discover that knowledge at runtime.

nayan_kokare
Explorer

Hi Hrb24,

Can you please share the git hub link and when can i get the next Part, eager to try this out?

Hrb24
Product and Topic Expert
Product and Topic Expert

Hi @nayan_kokare

you can try by yourself.

  1. Install Claude Code for Windows.
  2. Install python - by the way, Claude code can take over that part also
  3. let Claude code generate a sap script method library based on sap_gui_scripting_api_761.pdf 
  4. Enable Scripting (Alt+F12 → Options → Scripting)
  5. check RZ11 setting of your SAP system: sapgui/user_scripting = TRUE

Then log in into SAP system and try some prompts in Claude Code. You can start with "list my sap connection"

Necronomicon
Participant

Amazing. Can't wait for Part 1

Kiran_Kapasi
Explorer

Hi @Hrb24 ,
Can we use Claude for developing new apps in an on‑premise system while complying with Indian data privacy rules?

Hrb24
Product and Topic Expert
Product and Topic Expert

@Kiran_Kapasi you can ask claude: 

What about Zero Data Retention (ZDR)?

Zero Data Retention is available for Enterprise accounts and must be enabled per organization by your account team. Claude This means prompts and responses are not stored at all after processing.

kosei
Discoverer

@Hrb24 

Hello, Thank you for your wonderful explanation.

Have you already shared the blog of setup in PART1 for AI agent with SAP?
I really want to know how to do and try this out.

 

RajuSubba
Participant
0 Likes

Waiting for Part 1 Blog