Skip to main content

Generative AI using OIC

Calculating read time…

📧 Monday Morning. 847 Unread Emails. Two Hours Before the Board Call.

Meera is a Senior Legal Manager at a large infrastructure company. She manages supplier relationships across 14 countries. Every morning she opens Outlook to find — on average — 134 new emails. Contract dispute threads. Payment escalations. Amendment proposals. Regulatory queries.

Each thread has 12–40 replies. Some date back three months. When someone asks Meera "what is the current status of the GlobalParts dispute?", she has to scroll through 28 emails, across three threads, to piece together an answer.

On Tuesday morning, her CEO calls: "Meera, I'm meeting GlobalParts in 40 minutes. Give me a one-paragraph summary of where we stand on the contract dispute, what they're asking for, and what our position is."

Meera opens the email thread. 31 emails. The oldest is from 6 weeks ago. She starts reading. The CEO's meeting starts in 38 minutes.

Simultaneously, her colleague Rohan — in Procurement — is looking at a 42-page supplier contract that just arrived for renewal approval. He needs a two-page executive summary, key risk flags, and a recommendation for the CFO by 3 PM. It is 11 AM.

Generative AI — specifically Large Language Models (LLMs) accessed through OCI Generative AI — is the technology that reads that 31-email thread and that 42-page contract, and produces a precise, structured summary in under 5 seconds. Combined with OIC Gen 3, this becomes an enterprise-grade pipeline that works automatically, at scale, for every contract and every email thread — integrated directly into Oracle Fusion applications.

💡 What You Will Build in This Article:

Integration 1 — Contract Summarizer:
Receives a supplier contract (text or extracted content), calls OCI Generative AI with a structured prompt, generates a 5-section executive summary with risk flags, stores in Oracle Fusion SCM and sends to stakeholders.

Integration 2 — Email Thread Summarizer:
Receives an email thread (from Oracle CX or raw text), calls OCI Generative AI to produce: one-paragraph summary, key decisions made, open action items, sentiment, next steps. Stores result in Oracle CX Service Request notes.

Full configuration — exact prompt engineering — every OIC step explained — real JSON payloads.

🧠 Section 1: What Is Generative AI — Explained Simply

Imagine you have hired the world's most well-read employee. They have read every book, every legal document, every technical manual, every news article ever written — in every language. They have perfect memory and can write fluently in any style you ask.

When you hand them a 42-page contract and say "give me a two-paragraph summary of the key risks and payment terms", they read it instantly and write exactly what you asked — in your preferred format, in your company's tone, highlighting exactly what matters to your business.

That employee is a Large Language Model (LLM). OCI Generative AI is Oracle's enterprise platform for accessing these models — securely, inside your Oracle Cloud tenancy, without your data ever leaving.

❌ Traditional Integration Approach
Write regex patterns for every contract clause format
Update logic every time a new contract template appears
Extract data but cannot understand meaning or context
Cannot generate human-readable summaries — only extract fields
Complex multi-paragraph clauses require manual reading
✅ OIC + OCI Generative AI Approach
Natural language prompt defines what to extract and summarise
Works on any contract format — no template-specific coding
Understands context, meaning, implications, and tone
Generates structured, human-readable summaries in any format
Adapts automatically to any language, style, or content type
🏛️ The Critical Difference — Extraction vs Generation:

OCI Document Understanding (previous article) = Extraction. It finds and pulls out specific named fields that already exist in the document. It reads what is there.

OCI Generative AI = Generation. It reads, understands, reasons, and creates new content — summaries, analysis, recommendations, explanations. It creates what was not there before.

In a real OIC pipeline, you often use both together: Document Understanding extracts the raw text from a scanned PDF → Generative AI reads that text and produces an intelligent summary. They are complementary, not competing.

☁️ Section 2: OCI Generative AI — Oracle's Enterprise LLM Platform

OCI Generative AI is Oracle's managed service for Large Language Models. It is not a single model — it is a platform hosting multiple frontier models, accessible via a unified REST API, with all data processing happening inside your OCI tenancy.

🦾
Cohere Command R+
Best for: Complex reasoning, long documents, structured output generation, tool use. Ideal for contract summarization with 128K context window. Recommended for enterprise Oracle use cases.
🦙
Meta Llama 3.1 70B
Best for: General text tasks, email summarization, classification, policy Q&A. Strong multilingual capability. Good balance of speed and quality for high-volume use cases.
🏎️
Cohere Command R
Best for: Faster, lower-cost tasks. Short document summaries, quick classification, simple extraction from structured text. Sub-second response on typical email threads.
🎯
BYOM (Custom)
Bring Your Own Model. Fine-tune on your company's documents — your contract language, your email style, your industry terminology. Maximum accuracy for domain-specific tasks.

🔌 OCI Generative AI — Chat Completions API (What OIC Calls)

POST https://inference.generativeai.{region}.oci.oraclecloud.com/20231130/actions/chat
Content-Type: application/json
Authorization: Signature {OCI_Signature_V1}

📋 Request Body Structure:

{
  "compartmentId": "ocid1.compartment.oc1..{your_compartment}",
  "servingMode": {
    "servingType": "ON_DEMAND",
    "modelId": "cohere.command-r-plus"
  },
  "chatRequest": {
    "apiFormat": "COHERE",
    "preambleOverride": "You are an expert Oracle legal and procurement analyst...",
    "message": "Summarise the following contract in 5 structured sections...",
    "maxTokens": 1500,
    "temperature": 0.1,
    "documents": []
  }
}

📋 Response Structure:

{
  "chatResponse": {
    "apiFormat": "COHERE",
    "text": "**CONTRACT SUMMARY**\n\n**1. PARTIES & PURPOSE**\n...",
    "finishReason": "COMPLETE",
    "usage": {
      "inputTokenCount": 4821,
      "outputTokenCount": 847
    }
  }
}
💡 Key parameters to understand:
temperature (0.0–1.0): How creative vs precise. For factual summaries use 0.1–0.2 (focused). For creative writing use 0.7–0.9.
maxTokens: Maximum length of the generated response. 1 token ≈ 0.75 words. 1500 tokens ≈ 1,125 words — enough for a detailed contract summary.
preambleOverride: The system prompt — defines the AI's persona, expertise, and output rules. This is your most powerful configuration knob.

✍️ Section 3: Prompt Engineering — The Most Important Skill in GenAI Integration

In OCI Vision, the quality of your result depends on the image quality and your XPath mappings. In OCI Generative AI, the quality of your result depends almost entirely on the quality of your prompt — the instruction you give the LLM.

A bad prompt gives you a vague, inconsistent summary that cannot be reliably parsed by OIC. A great prompt gives you a structured, predictable output that OIC can map directly into Oracle Fusion fields.

❌ Bad Prompt — What NOT to Write
"Summarise this contract."
Problems: No structure defined. Response length unpredictable. Cannot reliably parse the output in OIC. Every response will be formatted differently. No risk flags requested. No JSON output.
✅ Good Prompt — Structured and Parseable
"You are an Oracle procurement analyst. Analyse the contract text below and respond ONLY in valid JSON with these exact keys: contractTitle, parties, contractValue, paymentTerms, expirationDate, autoRenewal, penaltyClauses, riskFlags[], executiveSummary (max 150 words), recommendedAction. Never add any text outside the JSON."
Benefits: Predictable JSON structure. OIC can map each key to Fusion fields. Always same format. Risk flags are actionable. Executive summary has bounded length.

📐 The 5 Prompt Engineering Rules for Enterprise OIC Integration

Rule 1 — Always request JSON output (not markdown, not prose)
Add to every prompt: "Respond ONLY in valid JSON. Do not include any text, explanation, or markdown outside the JSON object." This makes OIC parsing straightforward — use a single variable assignment to store the response, then extract JSON fields with XPath.
Rule 2 — Define the exact JSON schema in the prompt
List every key you need: "Return JSON with keys: summary, riskLevel, paymentTerms, expirationDate, actionItems[]". The LLM will populate exactly those keys. If you do not define the schema, you get a different structure every time — impossible to parse reliably in OIC.
Rule 3 — Give the AI a clear persona in the system prompt (preamble)
"You are a senior Oracle Fusion procurement expert with 15 years of experience reviewing supplier contracts. You focus on financial risk, compliance obligations, and operational impacts." A persona dramatically improves relevance and accuracy of the output for your specific domain.
Rule 4 — Bound all free-text fields with word/character limits
"executiveSummary: maximum 100 words". Without limits, the LLM may write 800 words for a summary. This wastes tokens (costs money), overflows Fusion text fields, and makes the output inconsistent. Every free-text field in your JSON schema must have an explicit length constraint.
Rule 5 — Set temperature to 0.1 for factual extraction, never above 0.3
High temperature means more creativity and randomness. For contract summarization and email analysis — you want precision, not creativity. Temperature 0.1 means the LLM always picks the most accurate, factually consistent response. Temperature 0.8 might "creatively" add facts that were not in the document. Never use high temperature for business document processing.

📋 Section 4: Use Case 1 — Contract Summarization (Full Build)

We build the complete Contract Summarizer integration. Rohan from Procurement submits a supplier contract — OIC calls OCI Generative AI — gets a structured 5-section summary — loads it into Oracle Fusion SCM and emails the CFO a formatted summary. All in under 10 seconds.

🏗️ Contract Summarizer — Complete OIC Gen 3 Flow

Step 1 — REST Trigger: Receive: contractId, contractText (full contract as string), supplierNumber, businessUnit, requestedBy, summaryAudience (CFO / Legal / Procurement).
⬇️
Step 2 — Pre-Processing Assign: Validate contractText not empty. Calculate token estimate (string-length ÷ 4). If estimated tokens > 90,000 → truncate to first 85,000 chars (contract header and key clauses). Set audience-specific prompt variant. Set compartmentId from OIC Properties.
⬇️
Step 3 — Build GenAI Prompt Assign: Construct the full prompt string: preamble (system role) + structured JSON instruction + contract text. This is the most important step — the quality of the summary depends entirely on this prompt.
⬇️
Step 4 — OCI Generative AI Invoke (REST Invoke): POST to OCI GenAI chat endpoint. Model: cohere.command-r-plus. Temperature: 0.1. MaxTokens: 1500. Receive JSON-structured summary in chatResponse.text.
⬇️
Step 5 — Parse GenAI Response Assign: Extract chatResponse.text. Strip any accidental markdown fences (```json). Store as parseable JSON string. Extract individual fields: contractTitle, executiveSummary, riskLevel, riskFlags[], paymentTerms, expirationDate, recommendedAction.
⬇️
Step 6 — Switch: Route by Risk Level
🔴 HIGH RISK → Alert Legal + CFO immediately via Teams
🟡 MEDIUM → Create review task in Fusion, notify Procurement
🟢 LOW → Auto-load to Fusion Procurement contract record
⬇️
Step 7 — Oracle Fusion SCM Contract Update + Notification: POST summary fields to Oracle Fusion Procurement contract record. Send formatted HTML email summary to requestedBy. Return structured response to caller.

📌 Step 1: Create the Integration

Name:CONTRACT_GENAI_SUMMARIZER
Style:App Driven Orchestration
Description:Receives supplier contract text, calls OCI Generative AI for structured summarization, routes by risk level, updates Oracle Fusion Procurement and sends notifications.

📌 Step 2: Configure the REST Trigger

🔌 REST Trigger Settings

Relative URI:/contract/summarize
Method:POST

📋 Request JSON Sample:

{
  "contractId": "CONTRACT-2024-00847",
  "supplierNumber": "SUPP-00234",
  "businessUnit": "IN_CORP",
  "requestedBy": "rohan.mehta@company.com",
  "summaryAudience": "CFO",
  "contractText": "MASTER SUPPLY AGREEMENT\n\nThis Agreement is entered into as of January 15, 2024..."
}

📋 Response JSON Sample:

{
  "status": "SUCCESS",
  "contractId": "CONTRACT-2024-00847",
  "riskLevel": "MEDIUM",
  "executiveSummary": "This 12-month supply agreement with GlobalParts for ₹45L includes auto-renewal with 90-day notice, a 15% early termination penalty, and a 7.5% annual price escalation cap. Payment terms are Net 30. Key risk: escalation cap exceeds company policy of 5%.",
  "riskFlags": ["Price escalation 7.5% exceeds 5% policy", "15% termination penalty is above standard"],
  "recommendedAction": "Negotiate escalation cap to 5%. Seek legal review of termination clause before signing.",
  "fusionContractUpdated": true,
  "processingTimeMs": 4821,
  "tokensUsed": 5668
}

📌 Step 3: Create the OCI Generative AI REST Connection

Why: OCI Generative AI uses OCI Signature Version 1 — the same authentication pattern as OCI Vision, Language, and Document Understanding. If you have built any previous OCI AI connection in OIC, this follows identical steps.

🔌 OCI Generative AI REST Connection

OIC Console → Connections → Create → Adapter: REST
Connection Name:OCI_GENAI_CONN
Base URL:https://inference.generativeai.ap-mumbai-1.oci.oraclecloud.com
Security Policy:OCI Signature Version 1
Tenancy OCID:ocid1.tenancy.oc1..{your_tenancy}
User OCID:ocid1.user.oc1..{oic_service_user}
Private Key:Upload RSA private key (.pem). Same key as other OCI AI connections if already created.
✅ Required IAM Policy: Allow group OICIntegrationGroup to use generative-ai-family in compartment {YourCompartment}

📌 Step 4: Build the Contract Summarization Prompt (Assign Activity)

Why this is the most important step: The prompt is the instruction set for the AI. Every word matters. A precisely engineered prompt gives you a consistent, parseable JSON output every single time. We build the prompt dynamically using OIC's concat() function, inserting the actual contract text and audience-specific instructions.

⚙️ Assign Activity — "buildContractSummarizationPrompt"

Set two variables that map into the OCI GenAI request body:

Variable: systemPreamble
"You are a senior Oracle Fusion procurement and legal analyst with 15 years of experience reviewing enterprise supplier contracts. You specialise in identifying financial risks, compliance obligations, and operational exposure. You always provide structured, objective analysis based strictly on the contract text provided. You never add information not present in the contract."
Variable: userMessage (the full prompt)
XPath/concat expression in OIC:
concat(
  "Analyse the following supplier contract and respond ONLY in valid JSON with exactly these keys. ",
  "Do not include any text, explanation, or markdown outside the JSON. ",
  "The summary is for audience: ", $triggerRequest.summaryAudience, ". ",
  "Adjust technical depth accordingly. ",
  "\n\nRequired JSON structure:\n",
  "{ ",
  "'contractTitle': 'string - full contract title', ",
  "'parties': { 'buyer': 'string', 'supplier': 'string' }, ",
  "'contractValue': 'string - amount and currency', ",
  "'currency': 'string - ISO currency code', ",
  "'effectiveDate': 'string - YYYY-MM-DD', ",
  "'expirationDate': 'string - YYYY-MM-DD', ",
  "'paymentTerms': 'string - max 50 words', ",
  "'autoRenewal': 'YES or NO', ",
  "'autoRenewalNoticeDays': 'number or null', ",
  "'penaltyClause': 'string - max 50 words or null', ",
  "'priceEscalationCap': 'number as percentage or null', ",
  "'riskLevel': 'HIGH, MEDIUM, or LOW', ",
  "'riskFlags': ['array of strings - each flag max 20 words'], ",
  "'executiveSummary': 'string - maximum 120 words - written for ", $triggerRequest.summaryAudience, "', ",
  "'keyObligations': ['array of strings - top 5 obligations max'], ",
  "'recommendedAction': 'string - max 50 words' ",
  "}\n\n",
  "CONTRACT TEXT:\n",
  $processedContractText
)

📌 Step 5: OCI Generative AI REST Invoke

🧠 REST Invoke — OCI GenAI Chat Completion

Endpoint Name:summarizeContractLLM
Relative URI:/20231130/actions/chat
Method:POST
Timeout (seconds):120 — large contracts can take 30–60 seconds for the LLM to process

📋 Request JSON Sample (paste in wizard — defines the schema OIC will map into):

{
  "compartmentId": "ocid1.compartment.oc1..sample",
  "servingMode": {
    "servingType": "ON_DEMAND",
    "modelId": "cohere.command-r-plus"
  },
  "chatRequest": {
    "apiFormat": "COHERE",
    "preambleOverride": "You are a senior Oracle procurement analyst.",
    "message": "Summarise this contract in JSON format.",
    "maxTokens": 1500,
    "temperature": 0.1,
    "frequencyPenalty": 0,
    "presencePenalty": 0
  }
}

📋 Response JSON Sample (paste in wizard):

{
  "chatResponse": {
    "apiFormat": "COHERE",
    "text": "{\"contractTitle\": \"Master Supply Agreement\", \"riskLevel\": \"MEDIUM\"}",
    "finishReason": "COMPLETE",
    "usage": {
      "inputTokenCount": 4821,
      "outputTokenCount": 847
    }
  }
}

📌 Step 6: Map Request to OCI GenAI (Data Mapper)

🗺️ Data Mapper — Source Variables → OCI GenAI Request Body

$compartmentId
→
compartmentId From OIC Properties — never hardcode
"ON_DEMAND"
→
servingMode/servingType
"cohere.command-r-plus"
→
servingMode/modelId Read from OIC Property for easy model switching
"COHERE"
→
chatRequest/apiFormat Use "GENERIC" for Llama models
$systemPreamble
→
chatRequest/preambleOverride The system prompt / persona
$userMessage
→
chatRequest/message The full prompt with contract text embedded
1500
→
chatRequest/maxTokens ~1,125 words max output
0.1
→
chatRequest/temperature Low = precise and factual. Never use >0.3 for document analysis.

📌 Step 7: Parse the GenAI Response (Assign Activity)

Why this step is critical: The OCI GenAI response puts everything into chatResponse.text as a raw string. Even though we asked for JSON output, it arrives as a string. We must extract individual fields from this string using XPath. We also must handle the case where the LLM wraps its response in markdown code fences (```json ... ```) — which some models do despite being told not to.

⚙️ Assign Activity — "parseGenAIResponse"

Variable: rawGenAIText
$genAIResponse.chatResponse.text
The full JSON string returned by the LLM
Variable: cleanedJSON (strip markdown fences if present)
if(starts-with(normalize-space($rawGenAIText), '```'), substring-before(substring-after($rawGenAIText, '```json'), '```'), $rawGenAIText)
Removes ```json ... ``` wrapping if the LLM added it despite instructions
Variable: inputTokenCount
$genAIResponse.chatResponse.usage.inputTokenCount
Variable: outputTokenCount
$genAIResponse.chatResponse.usage.outputTokenCount
Variable: finishReason (validate completion)
$genAIResponse.chatResponse.finishReason
Must be "COMPLETE". If "MAX_TOKENS" → the response was truncated. Increase maxTokens or reduce contract text length.
💡 Parsing JSON fields from the cleanedJSON string in OIC:
Use OIC's JavaScript or XPath string functions to extract specific JSON field values. The most reliable approach is to use the OIC Parse Stage with JSON schema: in the integration canvas, add a JavaScript action that parses $cleanedJSON and maps each JSON property to a separate OIC variable. This gives you clean, individually addressable variables for each field the LLM returned.

📌 Step 8: Update Oracle Fusion Procurement Contract + Send Notification

🏛️ Oracle Fusion SCM Procurement — Update Contract with AI Summary

PATCH /fscmRestApi/resources/11.13.18.05/purchaseContracts/{contractId}

{
  "DFF_AISummary_c": $extractedExecutiveSummary,
  "DFF_AIRiskLevel_c": $extractedRiskLevel,
  "DFF_AIRiskFlags_c": $extractedRiskFlagsAsString,
  "DFF_AIRecommendedAction_c": $extractedRecommendedAction,
  "DFF_AISummarizedOn_c": fn:current-dateTime(),
  "DFF_AITokensUsed_c": number($inputTokenCount) + number($outputTokenCount)
}

📧 Section 5: Use Case 2 — Email Thread Summarization (Full Build)

Now we build the Email Thread Summarizer. This is Meera's solution — the one that gives the CEO a complete briefing on the GlobalParts dispute in 5 seconds instead of 38 minutes of scrolling.

📌 The Email Summarization Prompt — Engineered for Oracle CX Integration

⚙️ Email Thread Summarization — System Preamble + User Message

Variable: emailSystemPreamble
"You are an expert Oracle CX Service specialist and business communication analyst. You specialise in reading enterprise email threads and extracting the essential information for senior executives who need to act quickly. You are objective, concise, and always structure your output in the exact JSON format requested. You never invent information not present in the emails."
Variable: emailUserMessage (built dynamically in OIC)
concat(
  "Analyse the email thread below and respond ONLY in valid JSON. ",
  "No text outside the JSON. No markdown fences. ",
  "\n\nRequired JSON structure:\n",
  "{ ",
  "'subject': 'string - the main topic of this thread', ",
  "'participants': ['array of names and roles mentioned'], ",
  "'dateRange': { 'from': 'YYYY-MM-DD', 'to': 'YYYY-MM-DD' }, ",
  "'oneParaSummary': 'string - 80 words max - what is this thread about and where does it stand', ",
  "'currentStatus': 'OPEN, RESOLVED, ESCALATED, or PENDING_ACTION', ",
  "'keyDecisionsMade': ['array - decisions agreed in this thread, max 5'], ",
  "'openActionItems': [{'action': 'string', 'owner': 'string', 'dueDate': 'YYYY-MM-DD or null'}], ",
  "'ourPosition': 'string - what is our company's stated position, max 50 words', ",
  "'theirPosition': 'string - what is the other party's stated position, max 50 words', ",
  "'sentiment': 'POSITIVE, NEUTRAL, TENSE, or HOSTILE', ",
  "'urgencyLevel': 'HIGH, MEDIUM, or LOW', ",
  "'recommendedNextStep': 'string - what should happen next, max 50 words', ",
  "'suggestedResponseDraft': 'string - a suggested reply email in 100 words, professional tone' ",
  "}\n\n",
  "EMAIL THREAD (chronological, oldest first):\n",
  $processedEmailThread
)

⚙️ EMAIL_THREAD_SUMMARIZER — OIC Integration Flow

Trigger — REST POST /email/summarize: Receive: serviceRequestId, emailThreadText (all emails concatenated), threadSubject, requestedBy, urgencyOverride (optional).
⬇️
Assign — "preprocessEmailThread": Validate emailThreadText not empty. Truncate if > 80,000 chars (keep most recent emails). Build systemPreamble and userMessage prompt strings. Set compartmentId, modelId.
⬇️
REST Invoke — OCI GenAI (model: cohere.command-r — faster for emails): maxTokens: 1000. temperature: 0.15. apiFormat: COHERE. Receive structured JSON summary in chatResponse.text.
⬇️
Assign — "parseEmailSummary": Extract: oneParaSummary, currentStatus, keyDecisionsMade, openActionItems, ourPosition, theirPosition, sentiment, urgencyLevel, recommendedNextStep, suggestedResponseDraft.
⬇️
Switch — Route by urgencyLevel + sentiment:
🔴 HIGH + HOSTILE → Escalate to Manager via Teams. Create P1 SR in Oracle CX.
🟡 MEDIUM + TENSE → Update CX SR notes. Send summary to owner.
🟢 LOW/NEUTRAL → Update CX SR notes. No escalation.
⬇️
Invoke — Oracle CX Service REST API: Update SR Notes: PATCH /crmRestApi/resources/latest/serviceRequests/{serviceRequestId}/notes. Add note: AI-generated thread summary + key decisions + open actions + suggested response draft.
⬇️
REST Response: Return structured JSON with all extracted fields + CX SR update confirmation + urgencyLevel + sentiment + suggestedResponseDraft.

📝 What Gets Written to Oracle CX SR Notes

🤖 AI THREAD SUMMARY — Generated by OIC GenAI Summarizer | 2024-09-16 09:41 AM

📋 Summary: GlobalParts is disputing Invoice INV-2024-08472 citing a 3-day delivery delay and minor packaging damage on 12 units. They are requesting a 10% credit (₹14,800) against the invoice. Our position is that delivery SLA was met per contract Clause 8.2 (48h window excludes bank holidays) and that packaging damage was within the 2% acceptable tolerance threshold.

📊 Current Status: ESCALATED | Sentiment: TENSE | Urgency: HIGH

✅ Key Decisions Made:
1. We agreed to commission an independent packaging inspection report
2. Payment of undisputed amount (₹1,33,200) to proceed by Oct 1st
3. Disputed portion (₹14,800) held pending resolution

⚡ Open Action Items:
• Procurement to provide inspection report — Owner: Rohan Mehta — Due: Sep 20
• Legal to review Clause 8.2 applicability — Owner: Meera Joshi — Due: Sep 18
• Finance to release partial payment — Owner: Priya Kumar — Due: Oct 1

💬 Suggested Response Draft:
"Dear GlobalParts team, thank you for your email. We acknowledge your concerns regarding Invoice INV-2024-08472. As discussed, we are commissioning the packaging inspection report by September 20th and will release the undisputed amount of ₹1,33,200 by October 1st. We look forward to resolving this matter amicably."

🎯 Section 6: Real World Results — Before and After

❌ Contract Summarization — Before
Rohan reads 42-page contract manually: 3–4 hours
Risk clauses identified: depends on Rohan's experience
CFO summary document: 1 hour to write after reading
Consistent format across 847 contracts: impossible
Missed clauses: common (tired eyes, long documents)
Total time per contract: 4–5 hours minimum
✅ Contract Summarization — After OIC + GenAI
Contract submitted to REST endpoint: 5 seconds to full summary
Risk clauses: every page analysed, nothing missed
CFO summary: auto-generated in consistent format, sent automatically
847 contracts: processed overnight in 4 hours
Consistency: 100% — same format, same depth every time
Rohan reviews exceptions only: 2 hours for 847 contracts

💰 Section 7: Token Management — Controlling Costs in Production

OCI Generative AI charges per token. One token is approximately 0.75 words. A 42-page contract has roughly 12,000 words = 16,000 tokens as input. Understanding token management is not optional in enterprise GenAI — it is the difference between a cost-effective integration and an invoice shock.

💰 Token Budget Planning — Contract Summarizer

System Preamble (fixed per call)
~200 tokens
Prompt instructions (JSON schema)
~350 tokens
Contract text (42 pages)
~16,000 tokens
LLM Output (summary)
~800 tokens
💡 Cost Optimisation Strategies:
1. Chunk large contracts: Split a 100-page contract into 3 sections, summarise each, then summarise the summaries. Total tokens: lower than one massive call.
2. Pre-extract with Document Understanding first: Run OCI Document Understanding to extract structured fields, send only key clause text to GenAI (not the full 100-page PDF). Reduces input tokens by 70%.
3. Cache summaries: Store the summary in ATP/Object Storage. If the same contract is requested again within 24h, serve the cached version — zero token cost.

🚫 Common Mistakes

🔴
Not Validating finishReason — Accepting Truncated Summaries

If the LLM reaches maxTokens before finishing, finishReason returns "MAX_TOKENS" instead of "COMPLETE". The summary will be cut off mid-sentence, often mid-JSON — making it unparseable. Always check $genAIResponse.chatResponse.finishReason = 'COMPLETE' in an Assign. If it is MAX_TOKENS, either increase maxTokens or reduce the input contract length.

🔴
Using High Temperature for Business Document Analysis

Setting temperature to 0.7 or above for contract summarization will cause the LLM to "creatively interpret" clauses — sometimes adding penalty percentages that were not in the contract, or inventing dates. For all factual document analysis in enterprise OIC integrations, temperature must be 0.1. The only exception is if you specifically want creative content generation (marketing copy, training scenarios).

🔴
Sending the Entire Unprocessed Email Thread Without Cleaning

Raw email threads contain: email headers (X-Received, DKIM signatures, MIME boundaries), HTML tags from rich-text emails, base64-encoded inline images, email footers with legal disclaimers (100+ words each). All of this consumes tokens without adding information. In OIC's pre-processing Assign, strip HTML tags, remove standard footers (detect and truncate at "CONFIDENTIALITY NOTICE"), and keep only From/Date/Body for each email in the thread.

🔴
Treating GenAI Output as Ground Truth Without Human Review Gate

LLMs can confidently state incorrect summaries — particularly with complex legal language, ambiguous clause references, or poorly scanned documents. Never auto-approve a contract or send a CEO briefing based solely on GenAI output without flagging it as AI-generated. Always include "This summary was generated by AI and should be reviewed before high-stakes decisions" in the Oracle CX note and email outputs.


✅ Best Practices

✅ Store Prompts in OCI Object Storage or OIC Properties — Not Hardcoded in Flow

Prompt engineering is an ongoing process. As you discover better phrasings, you want to update prompts without redeploying the OIC integration. Store your preamble and user message templates in OCI Object Storage or as OIC Properties. The OIC Assign reads the template at runtime, substitutes dynamic values (contract text, audience), and sends the final prompt. This makes prompt iteration a configuration change, not a deployment.

✅ Combine Document Understanding + Generative AI for Maximum Accuracy

The optimal pipeline for scanned contracts: OCI Document Understanding extracts structured key-value fields (InvoiceId, dates, amounts) with high precision. OCI Generative AI then receives only the clause text (not the full raw scan) and generates the narrative summary and risk analysis. Document Understanding handles structured field extraction better than GenAI. GenAI handles narrative generation better than DU. Use each for what it does best.

✅ Implement a Feedback Loop to Oracle Fusion for Continuous Improvement

After each GenAI summary, let the human reviewer rate it: Accurate / Partially Accurate / Inaccurate. Store this rating with the contract ID and summary in ATP. After 100 ratings, analyse patterns: which contract types get low ratings? Which sections are consistently inaccurate? Use this data to refine your prompt engineering. This transforms your OIC integration into a self-improving system.

✅ Use Audience-Specific Prompts for Different Stakeholders

A contract summary for the CFO should focus on financial risk and cash flow impact. For Legal — clause enforceability and liability exposure. For Procurement — supplier obligations and SLA compliance. Build 3–4 prompt variants in OIC and select the right one based on the summaryAudience field in the trigger request. Same contract, different summaries, all from one integration — maximum stakeholder value.


🎓 Interview Questions — Senior OIC + GenAI Developer Level

❓ "How does OIC connect to OCI Generative AI? What authentication method is used?"

OIC connects to OCI Generative AI using the REST Adapter with OCI Signature Version 1 authentication. You configure a REST connection with: the OCI tenancy OCID, user OCID, RSA private key, and key fingerprint — the same pattern used for all OCI AI services (Vision, Language, Document Understanding). The base URL points to the OCI Generative AI inference endpoint for your region. In the REST Invoke activity, the relative URI is /20231130/actions/chat for chat completions. The connection handles signing each request with the RSA key, which OCI IAM validates before routing to the GenAI service.

❓ "What is the role of prompt engineering in OIC GenAI integrations? How do you ensure consistent, parseable output?"

Prompt engineering is the single biggest quality determinant in a GenAI OIC integration — more than model selection or configuration. For enterprise OIC integrations, three rules are non-negotiable: (1) Always request JSON output with an explicit schema defined in the prompt — this makes OIC parsing deterministic. (2) Set temperature to 0.1 for factual document analysis — this ensures the LLM picks the most accurate response rather than a creative one. (3) Define the exact JSON keys required, with length bounds on free-text fields. In OIC, prompts are built dynamically in Assign Activities using concat() functions — the contract text is injected into a template, the audience type can modify the instruction, and the JSON schema is always the same. Prompts stored in OCI Object Storage or OIC Properties enable updates without redeployment.

❓ "How do you handle a 100-page contract that exceeds the LLM's context window?"

Three strategies, often combined: (1) Pre-extraction first — use OCI Document Understanding to extract key clause text only. A 100-page contract might have 80 pages of boilerplate and 20 pages of critical clauses. Document Understanding identifies the clauses; only those 20 pages go to the LLM. (2) Chunking — split the contract into logical sections (Parties, Financial Terms, Termination, Obligations, Governing Law), summarise each section independently, then send all five section summaries to GenAI for a final combined summary. Total token cost is typically 40% lower than processing the full document. (3) Hierarchical summarization — summarise pages 1–20, then pages 21–40, etc., then summarise all summaries. Each approach is configured using OIC parallel-for-each and sequential Assign activities — no custom code needed.

❓ "What OIC error handling should you implement for a GenAI integration in production?"

Four mandatory fault handlers: (1) OCI GenAI timeout/unavailability — Scope with Fault Handler. On transient error (HTTP 429/503): retry 3 times with 5s delays. On persistent failure: log to ATP exception table, send alert, return graceful error response. Never let the caller receive an unhandled OIC error. (2) finishReason = MAX_TOKENS — detected in an If/Else after the invoke. Response is truncated JSON — do not attempt to parse it. Log the issue, return a PARTIAL status with instruction to retry with shorter contract text. (3) JSON parse failure — the LLM occasionally produces malformed JSON despite strict prompting. Wrap JSON parsing in a try-catch equivalent. On failure: return rawText to caller and flag for manual processing. (4) Context window exceeded — check input token estimate (string-length ÷ 4) before calling the LLM. If above 95K tokens, reject with clear error: "Document too long for single call — please use chunked processing endpoint."


🎉 Final Summary — What You Built and What It Means

🧠 OCI Generative AI: Oracle's enterprise LLM platform — Cohere Command R+, Meta Llama 3.1, and custom models — all running inside your OCI tenancy. Your contract and email data never leaves Oracle Cloud.
🔌 OIC Connection: REST Adapter with OCI Signature Version 1. Same auth pattern as every other OCI AI service. Configure once, reuse across GenAI, Vision, Language, and Document Understanding.
✍️ Prompt Engineering: The most critical skill. JSON output format. Strict schema definition. Temperature 0.1. Explicit word limits. Audience-specific variants. Stored in OCI Object Storage for zero-redeployment updates.
📋 Contract Summarizer: 42-page contract → 5-second structured JSON summary → risk-level routing → Oracle Fusion Procurement update → CFO email. What took 4 hours now takes 5 seconds.
📧 Email Thread Summarizer: 31-email dispute thread → one-paragraph summary → key decisions + open actions + suggested reply draft → Oracle CX SR note update. CEO briefing ready in 5 seconds, not 38 minutes.
💰 Token Management: Pre-extract with Document Understanding to reduce input tokens by 70%. Cache summaries in ATP. Chunk large documents. Monitor finishReason for truncation. Control costs at the architecture level, not as an afterthought.
🔄 Combined Pipeline: OCI Document Understanding extracts structured fields (what is there). OCI Generative AI generates narrative summaries and analysis (creating what was not there). Together they form a complete enterprise document intelligence pipeline inside OIC Gen 3.
🌱 The Shift That Generative AI Makes in Enterprise Integration:

Every integration you have ever built transforms data from one format to another — a purchase order becomes a payment instruction, a HR event becomes an account provisioning request. The data changes shape but the human content inside it — the meaning, the risk, the intent — was always invisible to the integration.

Generative AI changes this fundamentally. For the first time, your OIC integration can understand what a document says, not just what fields it contains. It can assess risk. It can recommend action. It can write a reply. It can brief your CEO.

You are not just building integrations anymore. You are building intelligence.


Read Everything. Understand Anything. Integrate with Intelligence. 🧠 ⚙️

Comments