<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sanjay Raina on Medium]]></title>
        <description><![CDATA[Stories by Sanjay Raina on Medium]]></description>
        <link>https://medium.com/@sanjayraina?source=rss-53fea6a84fa1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yc_b9RoLxrP3FTHaqDYMpg.jpeg</url>
            <title>Stories by Sanjay Raina on Medium</title>
            <link>https://medium.com/@sanjayraina?source=rss-53fea6a84fa1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:18:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanjayraina/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Agentic AI Is Rewriting the Business Operating Model]]></title>
            <link>https://medium.com/@sanjayraina/agentic-ai-is-rewriting-the-business-operating-model-8e2a49ade782?source=rss-53fea6a84fa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e2a49ade782</guid>
            <dc:creator><![CDATA[Sanjay Raina]]></dc:creator>
            <pubDate>Sun, 10 May 2026 18:43:49 GMT</pubDate>
            <atom:updated>2026-05-10T18:43:49.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yylMnxf1PH7E6mnF4Nbstg.png" /></figure><p>Every era of business has been defined by a dominant managerial question. The industrial era asked how to scale production. The information age asked how to digitise and coordinate the enterprise. The emerging AI era asks something more fundamental: <strong>How should work itself be designed when intelligence can be embedded, distributed, and increasingly delegated?</strong></p><p>That question, posed by Harvard Business School professor Dr. Karim Lakhani in Microsoft’s 2026 Work Trend Index Annual Report, is not rhetorical. It is the single most urgent strategic challenge facing business leaders today. And the answer demands not an upgrade to the organisation — but a rearchitecture of it.</p><blockquote><em>“The most consequential change underway is not simply the adoption of new tools. It is the emergence of a new operating model.”<br></em> — Dr. Karim Lakhani, Harvard Business School, Microsoft 2026 Work Trend Index</blockquote><h3>The Burning Platform: Why the Old Model Cannot Hold</h3><p>For decades, the operating model of the modern organisation has been built on the same architecture: hierarchical org charts, departmental silos, process handoffs between human specialists, and IT systems that exist to record and report on the work those humans do. It is a structure designed for a world where the only scalable form of intelligence was human intelligence — and where intelligence was expensive, scarce, and slow.</p><p>That world has ended. But most organisations are still running its operating model.</p><blockquote><strong>80% of C-suite executives are already running pilots on agentic AI — yet a similar share report seeing no material impact on earnings.</strong> (Microsoft Work Trend Index 2026)</blockquote><p>Microsoft’s 2026 Work Trend Index, which analysed trillions of productivity signals and surveyed 20,000 AI users across ten countries, lays out the paradox in stark terms: employees are ready to reinvent how they work, but the system around them — metrics, incentives, and norms — continues to reinforce the old way. The report calls this the <strong>Transformation Paradox</strong>. 65% of AI users fear falling behind if they don’t adapt quickly, yet 45% say it feels safer to focus on current goals than to redesign work with AI.</p><p>McKinsey’s December 2025 research adds a sharper edge: agentic AI is expected to drive a <strong>20–30% compression in legacy service lines</strong> as agents take on execution tasks that once required entire teams of human specialists. Enterprises believe as much as 15–30% of current knowledge roles’ work could be taken on by agents over the next three years.</p><h3>The Automation Trap: Why Replicating Human Teams Isn’t Enough</h3><p>The first instinct of most organisations encountering agentic AI has been entirely rational: take the teams and workflows that already exist, and replace the slower, more expensive human components with AI agents.</p><p>This was, in fact, the initial direction taken by Fuschia Systems when building its agentic AI platform. The approach showed genuinely promising results — tasks completed faster, costs dropped, capacity scaled. Early adopters were impressed.</p><p>But the model had a fundamental ceiling.</p><blockquote><em>“AI agents were trying to work like humans — only faster and cheaper. True leverage can only be achieved by reorganising work itself. AI agents need to organise themselves differently.”<br></em> — Fuschia Systems, reflecting on the evolution of the platform</blockquote><p>The insight that emerged was this: <strong>automation of the old model is not transformation</strong>. When AI agents are forced to conform to organisational structures built for human cognitive constraints — single-threaded attention, handoff meetings, limited working memory, fixed working hours — they inherit all of those constraints without the compensating benefits of human judgment, empathy, and contextual wisdom.</p><p>A human sales team needs handoffs because one person cannot hold the full context of every customer relationship simultaneously. An AI agent system has no such limitation. A human finance department has separate teams for AP, AR, FP&amp;A, and reporting because cognitive specialisation is the only practical way to manage complexity at human scale. An agentic system can hold all of that context in parallel, routing work dynamically based on state and outcome — not org chart position.</p><blockquote><strong>10–25% EBITDA gains</strong> for tech-forward enterprises who moved beyond the pilot phase — but most organisations remain stuck in experimentation mode precisely because they automated old workflows rather than redesigning them. (Bain &amp; Company, Technology Report 2025)</blockquote><h3>Rearchitecting Work: What the New Operating Model Demands</h3><p>The emerging consensus from Microsoft, McKinsey, Bain, and the California Management Review points to five interconnected shifts that define a genuinely new operating model.</p><h4>1. From Org Charts to Work Charts</h4><p>McKinsey argues that traditional hierarchical organisation charts must give way to <strong>agentic networks</strong>: flat, context-rich structures where work is organised around the exchange of tasks and outcomes rather than the assignment of roles. When intelligence is abundant and context can be shared instantly across an agent network, the entire rationale for hierarchical delegation — managing information scarcity and human cognitive limits — disappears.</p><h4>2. From Execution to Intent</h4><p>Microsoft’s Work Trend Index identifies the most critical reallocation of human effort: the shift from execution to intent. As AI agents take on the doing — analysis, synthesis, drafting, processing — human value concentrates in <strong>setting clear intent, defining quality standards, and owning outcomes</strong>. 49% of all AI-assisted interactions already support cognitive work. The most effective workers will be those who redefine their value around what only humans can do: judgment, taste, ethical accountability, and the design of work systems themselves.</p><h4>3. From Siloed Functions to Outcome-Oriented Workflows</h4><p>McKinsey identifies the most transformative emerging value proposition as the <strong>End-to-End Workflow Disruptor</strong> — going beyond deploying individual agents to redesigning entire customised workflows with deep domain expertise. When an AI agent can pull data from ERP, analyse it in a financial model, and trigger an HR action within a single workflow, the organisational boundary between Finance, HR, and Operations ceases to be a structural necessity. It becomes a choice.</p><h4>4. From Static Processes to Learning Systems</h4><p>Microsoft identifies the most profound shift as the emergence of the organisation as a <strong>Learning System</strong>. As agents execute work at scale, they generate continuous signals: what worked, what failed, where quality drifted. Frontier Firms capture these signals and encode them into shared routines, building what Microsoft calls <strong>Owned Intelligence</strong> — institutional know-how that compounds over time, is unique to the firm, and is extraordinarily hard to replicate. Active agents in the Microsoft 365 ecosystem grew 15× year over year.</p><blockquote><strong>$400 billion</strong> — upper estimate of the annual value pool from transforming core business functions through joint human-agent operating models, particularly in knowledge roles. Over 70% of this opportunity spans financial services, retail, high tech, healthcare, and manufacturing. (McKinsey, 2025)</blockquote><h4>5. From Periodic to Embedded Governance</h4><p>As agents operate continuously across functions, governance cannot remain a periodic, paper-heavy exercise. The California Management Review’s March 2026 analysis proposes that AI agents have transitioned from tools to actors — systems that independently perceive, decide, and act. Governance must become real-time, data-driven, and embedded, with humans holding final accountability.</p><h3>The Fuschia Framework: Four Pillars of an Agentic Operating Model</h3><ul><li><strong>Work Architecture</strong> — Organise around outcomes and tasks, not roles and departments. Replace org charts with dynamic workflow graphs. Let context flow freely across agent networks.</li><li><strong>Human–Agent Interface</strong> — Define where judgment, intent, and accountability sit with humans. Design clear escalation paths, human-in-the-loop checkpoints, and quality review frameworks.</li><li><strong>Owned Intelligence</strong> — Capture what agents learn. Build feedback loops that encode successful patterns into shared routines. Turn agent outputs into institutional knowledge that compounds.</li><li><strong>Embedded Governance</strong> — Monitor agent behaviour in real time. Assign permissions, identities, and policy constraints to agents as managed entities. Make trust a structural property of the system.</li></ul><h3>Where Fuschia Fits: Designing for the New Operating Model</h3><p>Fuschia Systems was built to make this new operating model practically achievable — for businesses of any size, not just large enterprises with armies of AI engineers. The platform was designed around a core insight: the bottleneck to agentic transformation is not the availability of AI models. It is <strong>orchestration</strong> — coordinating the right agent, at the right time, with the right information, in the right relationship to human oversight and to every other agent in the workflow.</p><h3>Context Engineering at the Core</h3><p>One of Fuschia’s most distinctive capabilities is <strong>context engineering</strong> — systematically ensuring every agent has the information it needs to make good decisions: clear instructions, access to company data and customer histories, memory of past interactions, and the ability to invoke tools and integrate with existing systems. This is the foundational requirement for moving from the old model (agents replicating human tasks) to the new model (agents organised differently around what they are actually capable of).</p><h3>Orchestration for Scale</h3><p>The Fuschia platform coordinates agent collaboration across entire multi-agent workflows — managing handoff logic between specialised agents, ensuring generalist agents escalate to specialists when needed, and surfacing decisions for human review when complexity or risk exceeds defined thresholds. Real-time visual monitoring provides the transparency that embedded governance demands: showing active agents, their decisions, the state of each task, and precisely when human input is required.</p><h3>Memory as Institutional Learning</h3><p>Fuschia’s memory system captures patterns across workflows over time — enabling agents to generate deeper insights and continuously improve automation performance. Every interaction feeds back into the system’s understanding of what good looks like for that business, that workflow, and those customers. This is the mechanism that turns Fuschia from a workflow tool into what Microsoft calls a Learning System.</p><h3>The Leadership Imperative</h3><p>None of this happens by accident. The Microsoft research is unambiguous: organisational factors — culture, manager support, talent practices — account for more than twice the reported AI impact of individual factors like mindset and behaviour (67% vs. 32%). The biggest barrier to capturing the value of agentic AI is not the technology. It is leadership.</p><p>The Transformation Paradox is fundamentally a leadership problem. When only 13% of workers say they are rewarded for reinvention of work with AI even when results aren’t immediately met, the system is actively selecting against the very behaviours needed to build a new operating model. The metrics, incentives, and norms of the industrial-era org chart continue to reinforce old ways of working — even as individuals race to adopt new tools.</p><p>The organisations pulling ahead — what Microsoft calls Frontier Firms — have made a deliberate choice to redesign the system, not just the tools. Their leaders use AI themselves, set quality standards for AI-assisted work, create psychological safety around experimentation, and reward reinvention regardless of short-term outcome. In organisations with this kind of leadership, employees report a <strong>17-point lift in AI value</strong>, a <strong>22-point lift in critical thinking</strong>, and a <strong>30-point lift in trust in agentic AI</strong>.</p><blockquote><em>“The firms that build a new operating model today won’t just move faster in the short term. They’ll build something more durable — an organisation that learns faster than its competitors, compounds its own intelligence, and gets harder to catch with every cycle.”<br></em> — Microsoft 2026 Work Trend Index Annual Report</blockquote><h3>The Architecture of the Next Era</h3><p>The industrial era was defined by the design of scale. The information age by the design of coordination. The agentic AI era will be defined by the design of <strong>judgment, learning, and coordinated action across humans and machines</strong>.</p><p>The businesses that win will not be the ones that accumulate the most AI tools. They will be the ones that build operating models capable of turning local gains into institutional advantage — organisations in which every agent action teaches the system something, and every human decision focuses on what only humans can do.</p><p>The architecture of that organisation exists today. The question is simply whether leaders are willing to do the work to build it. Platforms like Fuschia exist precisely to make that work tractable — starting with a single process, proving value, and scaling into a fundamentally different kind of enterprise. Not one that runs like a human team, only faster. One that runs in ways human teams never could.</p><p><strong>Learn more at </strong><a href="https://fuchsiasystems.ai/"><strong>fuchsiasystems.ai</strong></a></p><h3>Sources</h3><ul><li>Microsoft 2026 Work Trend Index Annual Report — “Agents, human agency, and the opportunity for every organization” (May 2026)</li><li>McKinsey &amp; Company — “Reimagining the value proposition of tech services for agentic AI” (December 2025)</li><li>McKinsey &amp; Company — “The agentic organization: A new operating model for AI” (September 2025)</li><li>Bain &amp; Company — “State of the Art of Agentic AI Transformation”, Technology Report 2025</li><li>California Management Review — “Governing the Agentic Enterprise” (March 2026)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e2a49ade782" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fuchsia: Reimagining Business Process Automation in the Agentic AI Era]]></title>
            <link>https://medium.com/@sanjayraina/fuchsia-reimagining-business-process-automation-in-the-agentic-ai-era-4c4b136e715c?source=rss-53fea6a84fa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c4b136e715c</guid>
            <category><![CDATA[process-automation]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <dc:creator><![CDATA[Sanjay Raina]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 17:40:49 GMT</pubDate>
            <atom:updated>2026-01-07T17:40:49.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*el8yECaklZ1sP4J7" /></figure><p>Business process automation has evolved through distinct technological phases: mainframe-era batch processing in the 1960s-70s, integrated enterprise software in the 1980s, workflow orchestration tools in the 1990s, and Robotic Process Automation (RPA) in the 2000s. Despite these advances, the fundamental architecture of enterprise automation has remained largely unchanged-database backends, rule-based workflow engines, and per-seat licensing models designed for human operators.</p><p>Today’s automation platforms share common limitations:</p><ul><li><strong>Rule-based logic</strong>: Workflows rely on predefined conditional statements that cannot adapt to unforeseen scenarios</li><li><strong>Brittle integrations</strong>: Point-to-point connections that break when underlying systems change</li><li><strong>Limited context</strong>: No persistent memory of past executions or ability to learn from outcomes</li><li><strong>Human-centric design</strong>: Built around the assumption that humans will perform the actual work</li></ul><p>The emergence of large language models and agentic AI systems presents an opportunity to fundamentally rethink enterprise automation. Rather than building tools for human workers, we can now construct platforms where AI agents are the primary executors. This paradigm shift enables autonomous agents to reason about tasks, collaborate with each other, accumulate knowledge over time, and adapt their behaviour based on outcomes.</p><h3>The Fuchsia Automation Platform</h3><p>Fuchsia implements an agent-first automation architecture inspired by Andrej Karpathy’s “LLM Operating System” concept. Instead of orchestrating human tasks, the platform orchestrates autonomous AI agents that execute business processes end-to-end. The system combines multi-agent collaboration, persistent knowledge graphs, and continuous learning mechanisms to create an automation layer that adapts and improves over time.</p><h4>Architecture Overview</h4><p>The platform architecture consists of five integrated layers, as illustrated in Figure 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*NpZvdDqkEhBCrHm3hoc5TQ.png" /><figcaption>Figure 1: The Fuchsia architecture centres on an LLM-driven agentic workflow engine, with supporting layers for context management, external integrations, and user interaction</figcaption></figure><p><strong>1. Omnichannel Conversational Interface</strong></p><p>The user interaction layer supports multiple input modalities-native chat UI, email, API calls, and webhook triggers. All interactions are normalised into a unified request format and routed to the workflow engine. This abstraction allows the same workflow to process requests regardless of origin, eliminating the need for channel-specific logic.</p><p><strong>2. LLM Interface Layer</strong></p><p>Fuchsia maintains provider-agnostic LLM connectivity, supporting OpenAI, Anthropic, Google, and other model providers through a unified interface. Prompt construction follows a modular, declarative approach where prompt components are assembled programmatically based on task requirements, agent capabilities, and available context. This architecture enables prompt optimisation without modifying workflow logic.</p><p><strong>3. Agentic Workflow Engine</strong></p><p>The workflow engine executes business processes as directed acyclic graphs (DAGs) where each node represents a task executed by an AI agent. Unlike traditional workflow engines that route tasks to human queues, Fuchsia’s engine:</p><ul><li><strong>Assigns tasks to agent teams</strong>: Each workflow execution is paired with an agent organisation that collaboratively completes the tasks</li><li><strong>Injects dynamic context</strong>: Task execution incorporates real-time data from knowledge graphs, vector stores, and external systems</li><li><strong>Supports multiple reasoning modes</strong>: Agents can execute tasks using direct execution, chain-of-thought reasoning, or ReAct (Reasoning + Acting) patterns</li><li><strong>Enables agent collaboration</strong>: Tasks can be delegated between agents based on specialisation and current workload</li><li><strong>Facilitates human escalation</strong>: Complex decisions automatically route to human reviewers based on confidence thresholds</li></ul><p><strong>4. Context Management System</strong></p><p>Context management operates across three subsystems:</p><p><strong>Graph Database (Neo4j)</strong>: Stores episodic memory of workflow executions, entity relationships, and accumulated domain knowledge. The graph structure enables multi-hop reasoning queries like “Find all customers who experienced issue X and were resolved by approach Y within the last quarter.”</p><p><strong>Vector Database</strong>: Maintains embeddings of documents, historical conversations, and task outcomes for semantic retrieval. Used primarily for identifying similar past situations when agents encounter new scenarios.</p><p><strong>Prompt Optimisation Framework</strong>: Implements DSPy-based continuous improvement where task prompts are evaluated against metrics and iteratively refined. Training examples, evaluation metrics, and optimisation algorithms (GEPA, MIPRO v2) work together to improve task completion quality over time.</p><p><strong>5. External Integration Layer</strong></p><p>Agents access external systems through two mechanisms:</p><p><strong>Model Context Protocol </strong>(MCP) Servers that provide standardised interfaces to external services like email, HR systems, and databases. MCP servers expose tools that agents can invoke during task execution.</p><p><strong>REST APIs </strong>that provide direct HTTP integration for systems without MCP support. API responses are parsed and incorporated into agent context for decision-making.</p><h3>User Experience</h3><p>Fuchsia provides a hybrid interface that combines traditional UI navigation with conversational AI and visual workflow design. This multi-modal approach accommodates different user preferences and task types-quick actions via chat, detailed configuration via visual tools, and structured navigation for administrative functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JwmdjyTKy1VBaZ_wvUmEg.png" /><figcaption>Figure 2: The interface integrates a navigation menu, AI chat assistant, and a visual canvas for workflow design and monitoring</figcaption></figure><h4>AI-Assisted Chat Interface</h4><p>The conversational interface functions as a co-pilot for workflow development and optimisation. The system maintains context awareness of the user’s current task-whether designing a workflow, analysing process metrics, or monitoring executions-and provides role-appropriate assistance.</p><p>For example, when a process designer selects the workflow editor, the chat interface can:</p><ul><li>Generate workflow templates from natural language descriptions</li><li>Suggest optimal task sequences based on similar processes</li><li>Identify potential bottlenecks or failure points</li><li>Recommend appropriate agent organisations for the workflow type</li></ul><p>The generated workflows render immediately on the visual canvas, where they can be refined through continued conversation or direct manipulation.</p><h3>Visual Workflow Designer</h3><p>The drag-and-drop interface enables declarative workflow construction without coding. Each workflow consists of task nodes connected by edges representing execution flow. Task nodes are configured with clear specification of objectives, completion criteria and expected outputs. The platform converts the task configuration into appropriate prompts and context for the LLM workflow engine to execute.</p><p>Task configuration also includes continuous prompt/context optimisation. Few-shot examples can be provided to evaluate the output of tasks against using predefined metrics. The continuous refinement and optimisation of the task context produces better outputs over time and results in truly intelligent execution of workflow tasks by AI agents.</p><p>Task execution can also use memory persistence to accumulate knowledge acquired from task outputs and interactions. The ability to capture historical data in a knowledge memory graph provides AI agents with additional insight and reasoning when excuting tasks.</p><p><strong>Memory Integration:</strong></p><p>The workflow designer can also configure the memory capability of workflows:</p><ul><li><strong>Knowledge Graph Storage</strong> : Whether task outcomes should be persisted as entities and relationships</li><li><strong>Retrieval Scope </strong>: Which historical data the agent should consider during execution</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CN5gxixNEq_DwI0TQDjZAQ.png" /><figcaption>Figure 3: The visual designer shows a customer support workflow with multiple task nodes. The chat interface enables interactive workflow development through natural language prompts</figcaption></figure><p>The interface supports both conversational workflow generation (“create a workflow for processing refund requests”) and direct manipulation (dragging task nodes, editing properties, connecting flow edges). This flexibility allows rapid prototyping via chat followed by detailed refinement using visual tools.</p><h3>Workflows</h3><p>Workflows represent the structural definition of business processes. A workflow template specifies the task sequence, data flow, and decision logic that governs process execution. At runtime, the platform instantiates workflow executions-stateful instances tracking progress through the task DAG.</p><h4>Workflow Templates vs Executions</h4><p><strong>Workflow Templates</strong> are reusable process definitions that specify:</p><ul><li>Task nodes and their configuration (objectives, completion criteria, evaluation metrics)</li><li>Edges defining execution order and conditional branching</li><li>Input schema defining what data initiates the workflow</li><li>Output schema defining what data the workflow produces</li></ul><p><strong>Workflow Executions</strong> are runtime instances of workflows that maintain:</p><ul><li>Current execution state (which tasks are in-progress, completed, or blocked)</li><li>Accumulated context data from completed tasks</li><li>Agent assignments for each task</li><li>Execution history and decision audit trail</li></ul><h4>Task Configuration Deep Dive</h4><p>Each task node contains rich metadata that transforms it from a simple execution step into an intelligent, self-optimising unit. Figure 4 illustrates the task configuration interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ane4wEGX4o5H0PlRCvwISg.png" /><figcaption>Figure 4: Task properties panel showing the objective, completion criteria, and evaluation settings. These parameters are compiled into prompts that guide the agent execution of workflows</figcaption></figure><p>Task configuration operates at three levels:</p><p><strong>Execution Layer </strong>(what the agent does):</p><ul><li><strong>Task Objective</strong>: Natural language goal statement specifies what the agent should achieve(“Analyse customer sentiment from support ticket”)</li><li><strong>Completion Criteria</strong>: Specific conditions for successful completion (“Sentiment classification with confidence &gt; 0.85”)</li><li><strong>Input Schema</strong>: Required data format from previous tasks</li><li><strong>Output Schema</strong>: Expected data structure for downstream tasks</li></ul><p><strong>Evaluation Layer</strong> (how we measure success):</p><ul><li><strong>Training Examples</strong>: Few-shot sample demonstrations of correct task completion</li><li><strong>Metrics</strong>: Programmatic functions scoring task outputs to assess task performance (accuracy, completeness, latency)</li><li><strong>Optimisation Settings</strong>: Algorithms (GEPA, MIPRO v2) and hyperparameters for prompt tuning</li></ul><p><strong>Learning Layer </strong>(how the task improves):</p><ul><li><strong>Memory Persistence</strong>: Whether to store task outcomes in the knowledge graph</li><li><strong>Optimisation Schedule</strong>: How frequently to run prompt optimisation</li><li><strong>Optimisation Algorithm</strong>: Which DSPy optimiser to use (MIPRO v2 leveraging instructions and examples , GEPA for natural language self-reflection of prompt itself)</li></ul><h3>Agent Organisations</h3><p>Agent organisations define the AI workforce structure that executes workflows. Like human organisational charts specify reporting relationships and specializations, agent organisations define collaboration patterns, skill distributions, and handoff protocols between AI agents.</p><h4>Agent Architecture</h4><p>Each agent operates as an autonomous execution unit with reasoning capability and the ability to leverage skills.</p><p><strong>Reasoning Strategy</strong> defines the cognitive approach that the agent employs:</p><ul><li><strong>Direct Execution</strong>: Immediate LLM inference without intermediate reasoning steps (lowest latency, suitable for straightforward tasks)</li><li>Chain-of-Thought (CoT): Step-by-step reasoning where the agent articulates its logic before producing outputs (better for complex analysis)</li><li><strong>ReAct</strong>: Iterative reasoning-action cycles where the agent alternates between thinking and tool use (optimal for tasks requiring external data integration)</li></ul><p>Each agent has a <strong>Skill Set</strong> that comprises tools and capabilities available to the agent:</p><ul><li><strong>Native Functions</strong>: Python functions for structured data manipulation, calculations, and business logic</li><li><strong>MCP Servers</strong>: Connections to external services (email, databases, CRM systems) following the Model Context Protocol standard</li><li><strong>Custom Tools</strong>: Organisation-specific integrations defined as callable functions</li></ul><p>Additionally, agents have access to <strong>Knowledge Scope</strong> that includes the information available to the agent It includes:</p><ul><li><strong>Workflow Context</strong>: Data from previous tasks in the current execution</li><li><strong>Episodic Memory</strong>: Historical workflow executions stored in the knowledge graph</li><li><strong>External Knowledge</strong>: Data retrieved via RAG from vector stores or graph traversal</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lqXRgcbOE9JDpHyadf35A.png" /><figcaption>Figure 5: Agent configuration showing reasoning strategy selection and available tools. Each agent’s capabilities are defined by its reasoning mode and skill set</figcaption></figure><h4>Agent Organisation Templates</h4><p>Agent templates are graphs where nodes represent agents and edges represent potential task handoffs. When a workflow execution begins, the system instantiates an agent organisation by assigning specific agent instances to each node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riGNmH_WwWP6VmZQqvoGIw.png" /><figcaption>Figure 6: Pre-configured agent organisation templates. Each template defines a collaboration pattern — sequential processing, parallel execution, or hierarchical delegation</figcaption></figure><p>Agent templates support several common patterns:</p><ul><li><strong>Sequential Processing</strong>: Tasks flow through a series of specialists (triage → analysis → resolution)</li><li><strong>Parallel Execution</strong>: Multiple agents work simultaneously on independent subtasks (data gathering, validation, formatting)</li><li><strong>Hierarchical Delegation</strong>: A coordinator agent distributes work to specialists and aggregates results</li><li><strong>Peer Collaboration</strong>: Agents of equal capability share workload and cross-check their outputs</li></ul><h4>Agent Types and Roles</h4><p>Agents can be configured for specific organisational functions:</p><ul><li><strong>Coordinators</strong> route requests to appropriate specialists, aggregate results from parallel tasks, manage workflow state</li><li><strong>Specialists</strong> execute domain-specific tasks (sentiment analysis, data transformation, compliance checking) with deep expertise in particular areas</li><li><strong>Validators</strong> verify outputs against quality criteria, check for policy violations, ensure data completeness</li><li><strong>Human Liaisons </strong>agents manage human-in-the-loop interactions, format approval requests, process human feedback</li><li><strong>Tool Executors</strong> interface with external systems, handle API calls, manage data transformations between systems</li></ul><h3>Context Engineering in Fuchsia</h3><p>An effective Agentic AI system relies on high quality context data. Fuchsia implements a multi-layered context system that combines episodic memory, semantic retrieval, and structured knowledge to provide agents with relevant information at task execution time.</p><h4>Agentic Memory System</h4><p>The memory architecture uses Neo4j to maintain a persistent knowledge graph representing workflow history, entity relationships, and accumulated domain knowledge. Unlike vector-only approaches that lose relational structure, the graph preserves entity connections and enables reasoning about relationships.</p><p><strong>Episodic Memory Storage</strong> models workflow execution as a subgraph containing:</p><ul><li><strong>Task nodes </strong>with execution metadata (start time, duration, agent assignment, outcome)</li><li><strong>Entity nodes</strong> extracted from inputs and outputs (customers, products, tickets, documents)</li><li><strong>Relationship edges</strong> describing how entities interacted during the process</li><li><strong>Temporal markers</strong> enabling time-based queries</li></ul><p><strong>Entity Extraction and Linking</strong>: As workflows execute, the system extracts named entities from unstructured data and links them to existing graph nodes. For example, processing a support ticket creates nodes for the customer, product, issue category, and resolution approach, then connects them to the ticket entity and the broader knowledge graph.</p><p><strong>Temporal Knowledge Evolution</strong>: The graph tracks how entity attributes change over time. A customer entity accumulates interaction history, preference updates, and issue resolution patterns. Agents query this temporal data to understand context: “What issues has this customer reported in the past six months?”</p><p><strong>Multi-Hop Reasoning Support</strong>: Graph queries can traverse multiple relationship types to answer complex questions:</p><ul><li>“Find customers who experienced billing issues that were resolved via refund”</li><li>“Which products have quality problems that correlate with specific suppliers?”</li><li>“What resolution approaches work best for priority customers with technical issues?”</li></ul><p>These queries inform agent decisions during workflow execution. When an agent encounters a support ticket, it queries the graph for similar historical cases and their outcomes, incorporating that knowledge into its reasoning.</p><h3>GraphRAG: Hybrid Retrieval Architecture</h3><p>Retrieval Augmented Generation is another key feature of Agentic AI systems where LLMs can connect to external, authoritative knowledge bases, allowing them to pull in current and specific information before generating answers, instead of relying solely on their pre-trained data. Fuchsia implements GraphRAG-a retrieval architecture that combines semantic vector search with graph traversal to provide richer context than either approach alone. The retrieval process operates as follows.</p><ol><li><strong>Vector Search</strong> : When an agent needs external knowledge, the system first performs semantic similarity search against embedded documents in the vector store. This identifies text chunks semantically related to the current task.</li><li><strong>Entity Extraction </strong>: The system extracts entities from the retrieved chunks and from the current workflow context.</li><li><strong>Graph Expansion</strong> : Starting from identified entities, the system traverses the knowledge graph to find related entities and relationships. For example, finding a customer entity triggers traversal to related products, past issues, and resolution patterns.</li><li><strong>Context Aggregation</strong> : Both the semantically similar text chunks and the graph-traversed structured data are combined into a unified context that provides both unstructured information and relational structure.</li></ol><p>The Graph-RAG approach has a number of technical advantages:</p><p><strong>Multi-Hop Reasoning</strong>: Graph traversal enables queries that span multiple relationship types. A question like “What products purchased by enterprise customers in Q4 experienced quality issues?” requires traversing customer→purchase→product→issue relationships, which pure vector search cannot represent.</p><p><strong>Explainable Retrieval</strong>: Graph paths provide audit trails showing how information was retrieved. Rather than opaque similarity scores, the system can explain: “This recommendation comes from customer C123’s past issues (relationship: REPORTED) with product P456, resolved via method M789 (relationship: RESOLVED_BY).”</p><p><strong>Domain Structure Preservation</strong>: Entity relationships encode domain semantics that vector embeddings cannot capture. The relationship between “invoice” and “payment” differs from “invoice” and “customer,” and graph structure preserves these distinctions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-C6ROkZTfKW7cz-XtEN3g.png" /><figcaption>Figure 7: A knowledge graph excerpt showing entities (customers, products, support tickets) and their relationships. Graph traversal enables multi-hop queries that combine information across entity types</figcaption></figure><h3>Agent Tools and External Integration</h3><p>Agents extend their capabilities through tools-callable functions that interact with external systems, perform computations, or access data sources. Fuchsia supports tool integration via the Model Context Protocol (MCP) for standardised connections and direct REST API integration for custom systems.</p><p>MCP Servers are standalone processes that expose standardised tool interfaces following the Model Context Protocol specification. Each MCP server provides:</p><ul><li><strong>Tool Definitions</strong>: JSON schemas describing available functions, required parameters, and return types</li><li><strong>Execution Handlers</strong>: Code that processes tool invocations and returns results</li><li><strong>Authentication</strong>: Credential management for secure system access</li></ul><p>Native Python Tools include custom functions defined directly in the platform, useful for:</p><ul><li><strong>Data transformations </strong>(parsing, formatting, validation)</li><li><strong>Business logic calculations </strong>(pricing, scoring, compliance checks)</li><li><strong>Internal system operations</strong> (database queries, cache management)</li></ul><p>The tool invocation flow can be summarised as follows:</p><ol><li>Agent determines a tool is needed based on task requirements</li><li>Agent constructs tool call with appropriate parameters</li><li>System validates parameters against tool schema</li><li>Tool executes and returns structured result</li><li>Agent incorporates result into its reasoning and proceeds</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7c50hCAQSU7o9_kw34pmpQ.png" /><figcaption>Figure 8: MCP server connections to external services. Agents invoke tools through standardised interfaces regardless of the underlying system implementation</figcaption></figure><p>The diagram shows integration with email services and HR management systems. From an agent’s perspective, sending an email or querying employee data requires the same tool invocation pattern-only the tool name and parameters differ.</p><h4>Agent Handoff Protocol</h4><p>Agent handoff enables task delegation between agents with different specialisations. This mirrors human organisational patterns where generalist agents triage work and escalate to specialists when needed.</p><p>Handoffs occur when an agent determines it cannot optimally complete a task due to:</p><ul><li><strong>Missing tools</strong>: The task requires system access the current agent lacks</li><li><strong>Low confidence</strong>: The agent’s reasoning indicates uncertainty about the correct approach</li><li><strong>Explicit routing</strong>: The workflow design specifies handoff conditions (e.g., “escalate refund requests &gt; $500 to manager agent”)</li></ul><p>Agent handoff follows a consistent process where the context is clearly specified and the target agent identified before passing control over. Typically, the process consists of:</p><p><strong>Context Packaging</strong>: The source agent bundles relevant information:</p><ul><li>Task objective and completion criteria</li><li>Work completed so far</li><li>Entities and data extracted</li><li>Reasoning trace explaining why handoff is needed</li></ul><p><strong>Target Selection</strong>: The system identifies candidate agents based on:</p><ul><li>Required tools and skills</li><li>Agent specialisation tags</li><li>Current availability and load</li><li>Historical performance on similar tasks</li></ul><p><strong>Transfer Execution</strong>: Control passes to the target agent with full context preservation</p><p><strong>Result Return</strong>: When the specialist completes the task, results flow back to the originating agent (if workflow structure requires it) or directly to the next workflow task</p><p>This pattern enables progressive specialisation-simple requests are handled by generalist agents, complex cases automatically route to experts.</p><h3>Human-in-the-Loop Integration</h3><p>Not all decisions can or should be fully automated. Fuchsia provides structured human-in-the-loop (HITL) capabilities that enable agents to request human input when needed while maintaining full automation for routine tasks. Human intervention can be invoked in various cases.</p><p><strong>Escalation Triggers</strong>: Automation workflows and tasks are usually triggered by human interaction, where a user is expecting to accomplish a business function or fulfil a request.</p><p><strong>Confidence Thresholds</strong>: During task execution, when an agent’s confidence score for a decision falls below configured thresholds, the task automatically escalates to a human reviewer. For example, a refund decision with 65% confidence might require approval if the threshold is set at 75%.</p><p><strong>Policy Requirements</strong>: Certain task types mandate human oversight regardless of confidence. High-value transactions, contract modifications, or compliance-sensitive operations can be configured to always require human approval.</p><p><strong>Exception Conditions</strong>: Unexpected scenarios that don’t match known patterns trigger escalation. For example, an agent processing invoices that encounters an unusual format or missing required data will pause for human guidance.</p><p>A typical human-in-the-loop workflow operates as follows:</p><ol><li><strong>Escalation Initiation</strong>: Agent determines human input is needed and packages a request containing:</li></ol><ul><li>Context explaining why escalation occurred</li><li>Work completed so far</li><li>Specific decision or input required</li><li>Recommended action (if agent has a suggestion)</li></ul><p>2. <strong>Human Notification</strong>: The system routes the request to appropriate personnel based on:</p><ul><li>Role-based access control (managers, subject matter experts, compliance officers)</li><li>Availability and current workload</li><li>Domain expertise matching the request type</li></ul><p>3. <strong>Human Response</strong>: The reviewer examines the context and provides:</p><ul><li>Decision/approval</li><li>Additional information</li><li>Correction to agent reasoning</li><li>Instructions for proceeding</li></ul><p>4. <strong>Workflow Resumption</strong>: The agent incorporates human input and continues execution</p><p>The technical implementation of HITL capability requires integration with other collaboration and communication tools.</p><p><strong>Real-Time Communication</strong>: WebSocket connections enable bidirectional communication between agents and human users. Escalation requests appear instantly in the user interface without polling delays.</p><p><strong>Mobile Support</strong>: HITL requests can be reviewed and approved via mobile devices, enabling quick response times for time-sensitive decisions.</p><p><strong>Audit Trail</strong>: All human interactions are logged in the knowledge graph with timestamps, decision rationale, and outcome data. This provides compliance documentation and training data for improving agent performance.</p><h3>Prompt Optimisation with DSPy</h3><p>Task execution quality depends heavily on prompt quality. Rather than manually tuning prompts through trial and error, Fuchsia implements automated prompt optimisation using DSPy-a framework that treats prompts as learnable parameters optimised against metrics.</p><p>At task execution time, the optimisation system constructs prompts by assembling:</p><ul><li>Task objective and completion criteria (from workflow template)</li><li>Few-shot examples (if configured)</li><li>Retrieved context (from knowledge graph or vector store)</li><li>Agent capabilities and available tools</li><li>Input data from previous tasks</li></ul><p>These components are compiled into a prompt template that instructs the LLM how to complete the task. As workflows execute, the system collects performance data-task outputs, execution times, success rates, and metric scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFYU-_HlSLIdqv16jjIOYg.png" /><figcaption>Figure 9: The DSPy optimisation interface showing training examples, evaluation metrics, and optimiser configuration. The system iteratively refines prompts to maximise metric scores</figcaption></figure><p><strong>Training Examples</strong>: Process designers provide sample inputs and expected outputs that demonstrate correct task completion. These serve as optimisation targets — the system tunes prompts to reliably produce outputs matching the examples.</p><p><strong>Evaluation Metrics</strong>: Programmatic functions that score task outputs. Metrics can measure:</p><ul><li><strong>Accuracy</strong> (does the output match expected results?)</li><li><strong>Completeness</strong> (are all required fields populated?)</li><li><strong>Consistency</strong> (do similar inputs produce similar outputs?)</li><li><strong>Latency</strong> (how quickly does the task complete?)</li></ul><p><strong>Optimisation Algorithms</strong>: DSPy provides several optimisers:</p><p><strong>MIPRO v2</strong> (Multi-stage Instruction Proposal Optimiser): A sophisticated approach that generates multiple prompt variations, evaluates them against metrics, and selects the best performers. It is designed to optimise both the natural language instructions (prompts) and the few-shot examples used by an LLM program, often using techniques like bootstrapping and Bayesian optimisation.</p><p><strong>GEPA</strong> (Genetic Pareto Prompt Optimiser): Uses an approach called “reflective prompt evolution”. Instead of relying purely on structured feedback and few-shot examples, GEPA enables LLMs to introspect and reflect on their own execution traces and evaluation results in natural language to diagnose errors and propose improvements.</p><p>The system runs optimisation periodically (e.g., weekly) or when performance degrades below thresholds. Over time, prompts become increasingly effective at their specific tasks, similar to how human agents improve with experience.</p><h3>Process Management</h3><p>Beyond workflow orchestration, Fuchsia provides additional process management capabilities that help organisations understand, optimise, and govern their business processes. These modules leverage the same core agentic architecture and context management system.</p><h4>Process Mining</h4><p>Process mining reconstructs actual process execution patterns from event logs, enabling data-driven process understanding and optimisation. Unlike workflow templates that define how processes should work, process mining reveals how they actually work in practice. The core capabilities of the Process Mining subsystem are as folllows.</p><p><strong>Process Discovery</strong>: The system ingests event logs from source systems (ERP, CRM, ITSM tools) containing:</p><ul><li><strong>Case ID</strong> (uniquely identifies a process instance, e.g., order number)</li><li><strong>Activity</strong> (what happened, e.g., “order received,” “payment processed”)</li><li><strong>Timestamp</strong> (when it happened)</li><li><strong>Optional attributes</strong> (who performed it, what data changed)</li></ul><p>From these logs, the system constructs process graphs showing:</p><ul><li>Activity sequences and their frequencies</li><li>Parallel execution paths</li><li>Decision points and branching logic</li><li>Cycle times for each activity</li></ul><p><strong>Conformance Checking</strong>: Compares discovered process models against reference workflows to identify deviations:</p><ul><li>Activities executed out of sequence</li><li>Missing required steps</li><li>Unauthorised shortcuts</li><li>Compliance violations</li></ul><p><strong>Process Enhancement</strong>: Analyses discovered models to identify optimisation opportunities:</p><ul><li>Bottlenecks where work queues up</li><li>Rework loops indicating quality issues</li><li>Resource allocation inefficiencies</li><li>Automation candidates (high-volume, repetitive activities)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoNbd_SLiZUoRwJudXn-lg.png" /><figcaption>Figure 10: Process mining module showing event log configuration, discovered process model, and bottleneck analysis.</figcaption></figure><p>The Process Mining interface enables process analysts to:</p><ul><li>Configure event log connections to source systems</li><li>Visualise discovered process models as flow diagrams</li><li>Identify bottlenecks highlighted by colour-coded activity metrics</li><li>Compare conformance between actual and expected processes</li><li>Export insights for workflow optimisation</li></ul><h3>Value Stream Management</h3><p>Value stream mapping identifies value-adding and non-value-adding activities in end-to-end business processes. Unlike process mining (which analyses what happens), value stream management focuses on cycle time, wait time, and handoff delays to optimise throughput and minimise waste.</p><p>A value stream map visualises:</p><ul><li><strong>Process Steps</strong>: Activities that transform inputs into outputs</li><li><strong>Wait Times</strong>: Delays between activities (queuing, waiting for approval)</li><li><strong>Cycle Times</strong>: How long each activity takes to complete</li><li><strong>Information Flows</strong>: How data and instructions move between steps</li><li><strong>Material Flows</strong>: How physical or digital artifacts progress through the process</li></ul><p><strong>Current State Mapping</strong> documents existing processes with actual metrics:</p><ul><li><strong>Lead time</strong> (total time from request to completion)</li><li><strong>Process time</strong> (actual work time)</li><li><strong>Wait ratio</strong> (wait time / total time, highlighting inefficiency)</li></ul><p><strong>Future State Design </strong>proposes optimised processes that:</p><ul><li>Eliminate non-value-adding steps</li><li>Reduce handoffs and batch processing</li><li>Automate repetitive tasks</li><li>Parallelise independent activities</li></ul><p><strong>Gap Analysis</strong> compares current and future states to prioritise improvements by impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjURAPNnObKTF7kBQFBWbA.png" /><figcaption>Figure 11: Value stream designer showing process steps, cycle times and wait</figcaption></figure><p>The AI-assisted Value Stream Mapping interface enables:</p><ul><li>Natural language description of value streams (“map our order-to-cash process”)</li><li>Automatic calculation of metrics from process data</li><li>Identification of bottleneck steps with high wait ratios</li><li>Generation of future-state recommendations</li></ul><h3>Analytics &amp; Monitoring</h3><p>Fuchsia provides real-time observability into workflow executions and agent behaviour, enabling process managers to monitor performance, diagnose issues, and identify optimisation opportunities.</p><h4>Live Workflow Monitoring</h4><p>The monitoring interface provides visibility into active workflow executions, displaying:</p><p><strong>Workflow State</strong>: Current execution progress showing:</p><ul><li>Which tasks are completed, in-progress, or pending</li><li>Agent assignments for each task</li><li>Execution timeline with task durations</li><li>Data flowing between tasks</li></ul><p><strong>Agent Reasoning Transparency</strong>: For each task, the system exposes:</p><ul><li>Agent’s reasoning trace (chain-of-thought steps)</li><li>Tool invocations and their results</li><li>Confidence scores for decisions</li><li>Handoff rationale (if task was delegated)</li></ul><p><strong>Performance Metrics</strong>:</p><ul><li>Task completion times (vs. historical averages)</li><li>Success/failure rates by task type</li><li>Agent utilisation (how busy each agent is)</li><li>Bottleneck identification (tasks with high wait times)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3a2oHIx0fg6-KtmMEzfL7g.png" /><figcaption>Figure 12: Real-time workflow execution view showing task status, agent assignments, and execution timeline. The selected task displays the agent’s reasoning trace and current progress</figcaption></figure><p>This transparency serves multiple purposes:</p><ul><li>Debugging: Understand why a workflow failed or produced unexpected results</li><li>Optimisation: Identify slow tasks or overloaded agents</li><li>Compliance: Provide audit trails showing decision rationale</li><li>Training: Help process designers understand how agents interpret their instructions</li></ul><h3>Metrics and Reporting</h3><p>Beyond real-time monitoring, the analytics layer aggregates historical execution data to surface trends and patterns:</p><p><strong>Workflow Performance Metrics</strong>:</p><ul><li>Throughput (executions per hour/day)</li><li>Success rate (% of workflows completing without errors)</li><li>Average cycle time (from initiation to completion)</li><li>SLA compliance (% meeting defined time thresholds)</li></ul><p><strong>Agent Performance Analysis</strong>:</p><ul><li>Task completion rates by agent type</li><li>Quality scores (based on evaluation metrics)</li><li>Handoff frequency (how often agents escalate)</li><li>Learning curves (improvement over time via prompt optimisation)</li></ul><p><strong>Operational Insights</strong>:</p><ul><li>Peak load times requiring additional capacity</li><li>Common failure modes and their root causes</li><li>Underutilised agents or skills</li><li>Cost metrics (LLM API costs per workflow type)</li></ul><h3>Core Technology Stack</h3><p>Fuchsia’s architecture is built on modern, scalable technologies selected for performance, reliability, and maintainability.</p><p><strong>Backend Infrastructure</strong>:</p><ul><li><strong>Python FastAPI</strong>: Asynchronous API framework providing sub-200ms response times</li><li><strong>Celery</strong>: Distributed task queue for background processing</li><li><strong>Docker</strong>: Containerisation enabling horizontal scaling and consistent deployments</li></ul><p><strong>Data Layer</strong>:</p><ul><li><strong>Neo4j</strong>: Graph database storing episodic memory, entity relationships, and knowledge graphs</li><li><strong>Vector Store (Pinecone/Weaviate)</strong>: Embedding storage for semantic retrieval</li><li><strong>Redis</strong>: Caching layer for session state and frequently accessed data</li><li><strong>PostgreSQL</strong>: Relational store for structured workflow metadata</li></ul><p><strong>AI/ML Components</strong>:</p><ul><li><strong>Multi-LLM Support</strong>: Adapters for OpenAI, Anthropic, Google, and open-source models</li><li><strong>DSPy</strong>: Prompt optimisation framework with GEPA and MIPRO v2 implementations</li><li><strong>Embedding Models</strong>: Dense retrieval models for document and conversation encoding</li><li><strong>Entity Extraction</strong>: NER models identifying entities in unstructured text</li></ul><p><strong>Frontend Architecture</strong>:</p><ul><li><strong>React + TypeScript</strong>: Component-based UI with type safety</li><li><strong>WebSocket Client</strong>: Real-time bidirectional communication with agents</li><li><strong>React Flow</strong>: Visual workflow designer with drag-and-drop capabilities</li><li><strong>D3.js</strong>: Process visualisation for mining and value stream modules</li></ul><p><strong>Integration Layer</strong>:</p><ul><li><strong>MCP Framework</strong>: Model Context Protocol server implementations</li><li><strong>REST/GraphQL APIs</strong>: Flexible API access patterns</li><li><strong>Webhook Engine</strong>: Event-driven integration with external systems</li><li><strong>OAuth 2.0:</strong> Secure authentication for third-party connections</li></ul><h3>Enterprise-Ready Features</h3><p>Production enterprise deployment requires security, scalability, and integration capabilities beyond core workflow functionality. The Fuchsia platform incorporates security and performance features to provide solutions at enterprise scale.</p><h4>Security and Compliance</h4><p><strong>Authentication and Authorisation</strong>:</p><ul><li><strong>Multi-Factor Authentication</strong>: TOTP-based 2FA for user access</li><li><strong>SSO Integration</strong>: SAML 2.0 and OAuth 2.0 for enterprise identity providers</li><li><strong>Role-Based Access Control</strong> (RBAC): Granular permissions at workflow, agent, and data levels</li><li><strong>JWT Token Management</strong>: Secure, time-limited API access tokens</li></ul><p><strong>Data Protection</strong>:</p><ul><li><strong>Encryption at Rest</strong>: AES-256 encryption for all stored data (database, file storage)</li><li><strong>Encryption in Transit</strong>: TLS 1.3 for all network communication</li><li><strong>Secrets Management</strong>: Integration with HashiCorp Vault for credential storage</li><li><strong>Data Residency</strong>: Configurable geographic data storage locations</li></ul><p><strong>Compliance Capabilities</strong>:</p><ul><li><strong>Audit Logging</strong>: Immutable logs of all workflow executions, agent decisions, and human interactions</li><li><strong>Data Retention Policies</strong>: Automated data lifecycle management for GDPR/CCPA compliance</li><li><strong>Consent Management</strong>: User consent tracking for privacy-sensitive data processing</li><li><strong>Compliance Reporting</strong>: Automated generation of SOC 2, GDPR, and HIPAA compliance reports</li></ul><h4>Scalability and Performance</h4><p><strong>Performance Targets</strong>:</p><ul><li><strong>API latency</strong>: &lt;200ms p99</li><li><strong>Workflow throughput</strong>: 1000+ concurrent executions</li><li><strong>Knowledge graph</strong>: 1M+ nodes with sub-second query times</li><li><strong>Concurrent users</strong>: 1000+ with responsive UI</li></ul><p><strong>Scalability Architecture</strong>:</p><ul><li><strong>Horizontal Scaling</strong>: Stateless API servers enable linear capacity growth</li><li><strong>Database Sharding</strong>: Neo4j and PostgreSQL partitioning for multi-tenant isolation</li><li><strong>Caching Strategy</strong>: Multi-tier caching (L1: in-memory, L2: Redis) for frequently accessed data</li><li><strong>Async Processing</strong>: Background job queues for non-blocking workflow execution</li></ul><p><strong>Multi-Tenancy</strong>:</p><ul><li><strong>Data Isolation</strong>: Per-tenant databases or schema-level isolation</li><li><strong>Resource Quotas:</strong> Configurable limits on workflows, agents, and storage per tenant</li><li><strong>Usage Metering</strong>: Granular tracking for billing and capacity planning</li></ul><h4>Integration Ecosystem</h4><p><strong>Pre-Built Connectors</strong>:</p><ul><li><strong>ServiceNow</strong>: Incident/problem/change management via REST API</li><li><strong>Salesforce</strong>: Lead/opportunity/case automation via SOAP and REST APIs</li><li><strong>SAP</strong>: Financial posting and material management via RFC/BAPI</li><li><strong>Workday</strong>: Employee onboarding/offboarding via Workday Web Services</li><li><strong>Microsoft 365</strong>: Email, calendar, SharePoint document processing via Graph API</li></ul><p><strong>Custom Integration Options</strong>:</p><ul><li><strong>MCP Server Development</strong>: Build custom tools following Model Context Protocol</li><li><strong>REST/GraphQL APIs</strong>: Call Fuchsia workflows from external systems</li><li><strong>Webhooks</strong>: Subscribe to workflow events for real-time notifications</li><li><strong>Database Connectors</strong>: Direct SQL access for data import/export</li></ul><h3>Fuchsia in Practice</h3><p>Understanding a complete request lifecycle illustrates how Fuchsia’s components work together to execute business processes.</p><h4>Request Execution Flow</h4><ol><li><strong>Request Initiation</strong></li></ol><p>A user submits a request through any supported channel (chat UI, email, API call, webhook). The system normalises the input into a structured request object containing:</p><ul><li>Request type (new process vs. continuation of existing execution)</li><li>Requester identity and role</li><li>Request content (unstructured text, structured form data, or attachments)</li><li>Context metadata (channel, timestamp, priority)</li></ul><p>2. <strong>Intent Classification</strong></p><p>The intent classifier determines:</p><ul><li>Whether this is a new workflow or continuation of an existing execution (based on conversation history and entity matching)</li><li>Which workflow template matches the request type</li><li>Which agent organisation should handle the execution</li><li>Initial task in the workflow that should receive the request</li></ul><p>3. <strong>Workflow Instantiation</strong></p><p>For new requests, the system:</p><ul><li>Creates a workflow execution instance from the matched template</li><li>Assigns an agent organisation instance</li><li>Initialises workflow state with request data</li><li>Schedules the first task for execution</li></ul><p>4. <strong>Agent Task Execution</strong></p><p>For each task in the workflow:</p><p>a. The system performs <strong>Context Assembly</strong> and gathers:</p><ul><li>Task objective and completion criteria from template</li><li>Input data from previous tasks</li><li>Retrieved knowledge from graph/vector stores</li><li>Agent’s available tools and reasoning strategy</li></ul><p>b. Based on its configured strategy <strong>Agent Reasoning</strong> is performed:</p><ul><li><strong>Direct</strong>: Single LLM call with full context</li><li><strong>Chain-of-Thought</strong>: Multi-step reasoning with intermediate outputs</li><li><strong>ReAct</strong>: Iterative loop of reasoning, tool use, and observation</li></ul><p>c. <strong>Tool Invocation</strong>: If needed, agent calls external systems via MCP servers or APIs</p><p>d. <strong>Decision Point</strong>: Agent determines:</p><ul><li>Task is complete (output meets completion criteria)</li><li>Handoff needed (delegate to specialist agent)</li><li>Human input required (escalate via HITL)</li><li>Retry needed (transient failure, will reattempt)</li></ul><p>5. <strong>Knowledge Persistence</strong></p><p>Upon task completion:</p><ul><li>Extracted entities are added to the knowledge graph</li><li>Relationships between entities are created</li><li>Task outcome is stored as an episodic memory node</li><li>Evaluation metrics are computed for prompt optimisation</li></ul><p>6. <strong>Workflow Progression</strong></p><p>The engine advances to the next task:</p><ul><li>Workflow state updates (mark current task complete, activate next tasks)</li><li>Data from completed task becomes input to downstream tasks</li><li>Process repeats until all tasks are complete</li></ul><p>7. <strong>Completion and Feedback</strong></p><p>When the workflow finishes:</p><ul><li>User receives results via their original request channel</li><li>Knowledge graph updates with full execution trace</li><li>Analytics aggregate performance metrics</li><li>Prompt optimisation scheduler queues tasks that underperformed</li></ul><h3>Application Domains</h3><p>Fuchsia’s architecture supports diverse business process automation scenarios across organisational functions. Common use cases include the following.</p><p><strong>IT Service Management</strong>:</p><p>Incident management workflows that:</p><ul><li>Classify incoming tickets using entity extraction and historical pattern matching</li><li>Route to appropriate resolver groups based on skills and availability</li><li>Attempt automated resolution via knowledge base lookup and scripted remediation</li><li>Escalate complex cases to human experts with full context</li><li>Learn from resolution patterns to improve future classification and routing</li></ul><p><strong>Customer Service Operations</strong>:</p><p>Support ticket processing that:</p><ul><li>Aggregates customer context from CRM, order history, and past interactions</li><li>Generates contextual responses using knowledge base and policy documents</li><li>Handles routine requests autonomously (password resets, order status, refunds)</li><li>Escalates sensitive issues (billing disputes, complaints) to human agents</li><li>Tracks satisfaction metrics and optimises response quality</li></ul><p><strong>Human Resources</strong>:</p><p>Employee lifecycle processes including:</p><ul><li>Onboarding: Provisioning accounts, equipment, training assignments</li><li>Performance reviews: Scheduling, reminder generation, document collection</li><li>Offboarding: Access revocation, knowledge transfer, exit interviews</li><li>Compliance: Tracking certifications, mandatory training, policy acknowledgments</li></ul><p><strong>Finance and Accounting</strong>:</p><p>Financial operations such as:</p><ul><li>Invoice processing: OCR extraction, validation, approval routing, ERP posting</li><li>Expense reimbursement: Receipt validation, policy compliance checking, payment processing</li><li>Month-end close: Journal entry generation, reconciliation, variance analysis</li><li>Audit preparation: Document collection, trail generation, report compilation</li></ul><p><strong>Sales and Marketing</strong>:</p><p>Revenue operations including:</p><ul><li>Lead qualification: Scoring, enrichment, routing to sales representatives</li><li>Opportunity management: Next-step recommendations, risk assessment, forecast updates</li><li>Contract processing: Generation, approval workflows, signature collection</li><li>Campaign execution: Audience segmentation, content personalization, performance tracking</li></ul><h3>Conclusion</h3><p>Fuchsia represents a fundamental architectural shift in enterprise automation-from human-centric tools to agent-first platforms. Traditional automation systems treat software as task executors controlled by human operators. Fuchsia inverts this model: AI agents are the primary workforce, with humans providing oversight and handling exception cases.</p><p>This paradigm enables capabilities impossible in rule-based systems:</p><p><strong>Adaptive Execution</strong>: Agents reason about tasks contextually rather than following rigid if-then logic, handling variations and exceptions without explicit programming.</p><p><strong>Cumulative Learning</strong>: The knowledge graph accumulates process memory over time. Agents improve through prompt optimisation and access to historical outcomes, similar to human skill development.</p><p><strong>Collaborative Intelligence</strong>: Multi-agent organisations mirror human team structures — specialists, coordinators, validators — with dynamic task handoff based on skills and confidence levels.</p><p><strong>Contextual Awareness</strong>: GraphRAG and episodic memory provide agents with rich context spanning structured data, unstructured documents, and historical patterns, enabling informed decision-making.</p><p><strong>Continuous Optimisation</strong>: DSPy-based prompt optimisation creates a feedback loop where evaluation metrics automatically improve task execution quality without manual intervention.</p><p>The platform’s technical foundation-Neo4j for knowledge persistence, DSPy for optimisation, and MCP for extensibility-provides the infrastructure needed for production deployment at scale.</p><p>As LLM capabilities continue advancing, platforms like Fuchsia will increasingly mediate between human intent and automated execution, transforming how organisations design and operate business processes.</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/fuchsia-reimagining-business-process-automation-agentic-ai-i3j8e/?trackingId=0krJkrQmQRSiFTbcoZCLvg%3D%3D"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c4b136e715c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain + ServiceNow = Intelligent Process Orchestration]]></title>
            <link>https://medium.com/@sanjayraina/langchain-servicenow-intelligent-process-orchestration-45c280826847?source=rss-53fea6a84fa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/45c280826847</guid>
            <dc:creator><![CDATA[Sanjay Raina]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 18:35:41 GMT</pubDate>
            <atom:updated>2024-11-24T18:35:41.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHfOQeA2QprXkQZLDQWHJg.jpeg" /></figure><p>Large Language Models (LLMs) and Generative AI are among the most transformative technologies in recent times. These systems leverage deep learning algorithms to understand, generate, and interact with human language in ways that were unimaginable just a decade ago. From chatbots to creative tools, their applications are reshaping industries and pushing the boundaries of artificial intelligence.</p><p>In this article, we describe how the power of LLMs can be combined with workflow automation tools to build a new breed of cognitive process automation capabilities, enabling the automation of activities that previously relied on specialist human expertise and reasoning ability.</p><p>We will build a sample integration between LangChain and ServiceNow. LangChain is a versatile framework for developing LLM applications, and ServiceNow is a de facto standard process automation tool found in most enterprises, large and small.</p><h3>LangChain: The Swiss army knife for building LLM solutions</h3><p>Large language models are impressive in generating human-like text and understanding complex language patterns. LLMs can search, translate, summarize, and respond to questions and generate new content, including text, images, music, and software code.</p><p>However, on their own, they have some limitations and need additional capabilities when solving real-world problems in a business context. These limitations include:</p><ul><li><strong>Gaps in knowledge</strong>: even though the scale of training data used by LLMs is vast, there are gaps. The training data used generally has an end date and is limited to data in the public domain. So, when asked about topics beyond the cutoff date or data that is private to an organisation, the LLM tends to hallucinate.</li><li><strong>Token constraints</strong>: there is a limit on the amount of input tokens when LLMs process a query. E.g., the limit for GPT3.5 is 4,096 and for GPT4 it is 32,768 tokens. So, asking questions longer than the token limit is likely to return an error.</li><li><strong>Inability to follow rules and actions</strong>: while LLMs are great at predicting the next word in a sentence, they lack any inherent logical reasoning capability and cannot perform actions such as searching and complex calculations.</li><li><strong>Lack of memory</strong>: LLMs struggle with tasks that require retaining information over a long period or making connections between different pieces of information. Without a memory component, these models struggle to provide accurate responses to questions that require context or previous knowledge.</li><li><strong>Inability to process structured data</strong>: LLMs are great at processing unstructured text but can struggle with structured, tabular data.</li></ul><p>Enter LangChain, a flexible framework for building LLM-based applications. It simplifies the process of connecting LLMs like OpenAI’s GPT models with external data sources, tools, and APIs to build powerful, context-aware applications, overcoming the limitations described above.</p><p>There are many excellent resources available that describe the LangChain framework and its features, including the <a href="https://python.langchain.com/docs/concepts/">LangChain documentatio</a>n. Here, we summarise its key capabilities.</p><ul><li><strong>Model I/O</strong>: the core building block of LLM applications. LangChain enables you to integrate with a variety of models, including <em>Chat Models that </em>use chat messages as input/output rather than plain text. With <em>Prompt Management</em> one can develop sophisticated prompts to elicit specific outputs from language models. <em>Output parsers</em> enable the generated output to be presented in various formats.</li><li><strong>Chain composition</strong>: enables linking of tasks and primitive functions into pre-defined, reusable compositions that serve as building blocks for application development. Chains allow powerful constructs to be built using pipelines of form such as:<br>Chain = Prompt() | LLM() | OutputParser()</li><li><strong>Memory Management</strong>: allows LLMs to retain context over extended interactions, enabling multi-step conversations and workflows, essential for building context-aware applications.</li><li><strong>Retrieval</strong>: Enables access to and interaction with untrained data to augment the knowledge available to LLMs. This includes utilities to load documents from various sources and to split the text data. It also includes embedding capabilities to convert, store, and index vector representations of text data.</li><li><strong>Tools and Agents</strong>: enable integration with external APIs and services, including databases and SaaS systems. Agents use LLMs to determine actions to take to complete a task.</li></ul><h3>Retrieval Augmented Generation</h3><p>Retrieval Augmented Generation (RAG) refers to the process of incorporating additional data as context into a prompt to the LLM. This enables LLMs to go beyond the limitations of training data and respond to queries relating to topics that are not in the public domain or beyond the training cutoff date.</p><p>As shown below, a RAG system has two main sub-systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*y2WsFsyAPyMtTaw93TCaIg.jpeg" /></figure><p>First, it ingests data and stores it in a vector store. Due to the limitation in the length of tokens that can be processed by LLMs, the documents need to be split into smaller chunks. The text chunks are then transformed into vector embeddings and stored in a vector database. Embeddings are essentially vector representations of the meaning of words in context. This process is known as indexing.</p><p>The second sub-system then uses the stored vector data as lookup to match against the user query. This lookup of matching data is what is referred to as “retrieval” in RAG, and it provides extra context in the prompt to the LLM. The combination of matched document data and the query used as context enables the LLM to generate the final answer. The “augmented generation” part of RAG corresponds to the ability of LLMs to combine retrieved data as context with pre-trained data to return a response to the user.</p><h3>AI Agents</h3><p>Agents are used to enable language models to perform a series of actions. Unlike chains, in which a predetermined sequence of actions is performed, Agents allow LLMs to be used as reasoning engines. An Agent can be thought of as a chain that uses the LLM to decide which actions to take next.</p><p>As shown below, Agents rely on a runtime capability called Agent Executor. This is what executes the actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*SqlWHvoM5AsshXvRnvvw4Q.jpeg" /></figure><p>The agent framework also relies on a collection of Tools, that behave like functions, accomplishing tasks as directed. Langchain provides a wide range of tools, performing a variety of functions, including web scraping and code generation.</p><h3>ServiceNow RAG and Agent using LangChain</h3><p>ServiceNow is a premier platform for digital workflow automation, asset management, incident tracking, and customer service management. Organizations rely on it for automating business processes and streamlining operational activities.</p><p>Key capabilities of ServiceNow include:</p><ul><li><strong>Process Workflows</strong>: define end-to-end workflows across departments, from HR to IT, using visual tools and templates.</li><li><strong>Incident and Task Management</strong>: track and resolve incidents efficiently, prioritising tasks based on urgency and resource availability.</li><li><strong>Integration Hub</strong>: connect with numerous third-party systems, including CRM, ERP, and cloud solutions, enabling a unified data environment.</li><li><strong>AI and Analytics</strong>: incorporate AI and machine learning capabilities into automation capabilities.</li></ul><p>ServiceNow, like many companies, is investing heavily in augmenting its product lineup by leveraging Generative AI and LLMs. In the future, this may result in new capable features in the product. However, our interest here is to use ServiceNow just as an external data source and system of action for LLMs. We will use LangChain to integrate with ServiceNow and build:</p><ul><li>A RAG system to enable us to chat with ServiceNow knowledge base.</li><li>A ServiceNow Tool and its use in an Agent to orchestrate workflow actions with the help of LLM and incident data.</li></ul><p>Let’s start.</p><h4>Prerequisites</h4><p>The code used in the examples below is available on Github here: <a href="https://github.com/sanjayraina/langchain-servicenow">LangChain ServiceNow repository</a>.</p><p>You will need.</p><ul><li><strong>A Python environment</strong>. I prefer using Jupyter Notebooks as I like the responsive way of experimenting with and building code fragments. Make sure to install Langchain and other dependent modules as required.<br>pip install langchain</li><li><strong>OpenAI LLM</strong>: Get an OpenAI key by registering with the <a href="https://platform.openai.com/">OpenAI developer platform</a>.<br><strong><em>Disclaimer</em></strong>: <em>Please bear in mind that you may incur charges when calling the APIs, depending on the models chosen and usage.</em></li><li><strong>ServiceNow</strong>: Get a ServiceNow personal developer instance by registering with the <a href="https://developer.servicenow.com/">ServiceNow developer portal</a>. You will need to create a user that the API can use to read and write table data.</li><li><strong>Environment variables</strong>: Create a .env file and add the OpenAI API key and the ServiceNow instance values as environment variables. The contents of the file should look like this:</li></ul><pre>OPENAI_API_KEY=sk-*****<br>SERVICENOW_INSTANCE_URL=https://dev*****.service-now.com<br>SERVICENOW_INSTANCE_USERNAME=******<br>SERVICENOW_INSTANCE_PASSWORD=******</pre><h4>ServiceNow RAG</h4><p>The first step in building a RAG is to have a document loader. There are a number of loaders available for Langchain as described on this page: <a href="https://python.langchain.com/docs/integrations/document_loaders/">Document Loaders</a>. There isn’t one available for ServiceNow, but creating one should be easy. Just follow the instructions on this page: <a href="https://python.langchain.com/docs/how_to/document_loader_custom/">How to create a custom Document Loader</a>.</p><p>The document loader contains a lazy_loader function that calls the ServiceNow table API as follows:</p><pre>headers = {&quot;Content-Type&quot;: &quot;application/json&quot;, &quot;Accept&quot;: &quot;application/json&quot;}<br>url = self.instance_url + \<br>    &quot;/api/now/table/&quot; + self.table + &quot;?sysparm_limit=10&amp;sysparm_query=&quot; + \<br>    self.query + &quot;&amp;sysparm_fields=&quot; + self.fields<br>response = requests.get(url, auth=(self.instance_username,<br>                                self.instance_password), headers=headers)<br>data = response.json()</pre><p>And then yields the queried data as a series of Document objects.</p><pre>pattern = re.compile(&#39;&lt;.*?&gt;&#39;)<br>for rec in data[&#39;result&#39;]:<br>    doc = &quot;\n&quot;<br>    for fld in fldarr:<br>        doc +=  fld + &quot;:&quot; + rec[fld] + &quot;\n&quot;<br>    content = re.sub(pattern, &#39;&#39;, doc)<br>     yield Document(page_content=content,<br>         metadata={&quot;line_number&quot;: line_number, &quot;source&quot;: self.instance_url},<br>     )</pre><p>Once the document loader is created, we can build the main RAG script.</p><p>We start with loading the environment variables and importing the required modules.</p><pre>from dotenv import load_dotenv<br>load_dotenv()  # take environment variables from .env<br>from langchain_openai import OpenAIEmbeddings<br>from servicenow import ServiceNowLoader<br>from langchain.vectorstores import FAISS</pre><p>We then load the ServiceNow &quot;documents&quot; using the document loader we just created. In this case we are loading a subset of the knowledge base articles.</p><pre>table = &quot;kb_knowledge&quot;<br>query = &quot;short_descriptionLIKEsmartcool&quot;<br>fields = &quot;short_description,text&quot;<br>loader = ServiceNowLoader(table, query, fields)<br>docs = loader.lazy_load()<br>for doc in docs:<br>    docarr.append(doc)</pre><p>Next, we create Embeddings from the loaded document and store them in the vector store.</p><pre>embeddings = OpenAIEmbeddings()<br>vectorstore = FAISS.from_documents(docarr, embeddings)</pre><p>We then create the Retriever.</p><pre>retriever = vectorstore.as_retriever()</pre><p>Next, we create a chain to incorporate the retrieved context in the Chat.</p><pre>from langchain.chains import ConversationalRetrievalChain<br>from langchain_openai import ChatOpenAI<br><br>qa_chain = ConversationalRetrievalChain.from_llm(<br>    ChatOpenAI(),<br>    vectorstore.as_retriever(search_kwargs={&#39;k&#39;: 3}),<br>    return_source_documents=True<br>)</pre><p>Finally, we test the RAG by asking a question, using the right prompt.</p><pre>query = &quot;You are a customer service agent. Draft an email to a customer on how to use the SmartView Camera.&quot;<br>result = qa_chain({&#39;question&#39;: query, &#39;chat_history&#39;: chat_history})<br>print(&#39;Answer: &#39; + result[&#39;answer&#39;] + &#39;\n&#39;)</pre><p>The RAG should respond with something as follows:</p><pre>Answer: <br>Subject: Guide on Using the SmartView Camera Feature in Your SmartCool Refrigerator<br><br>Dear Valued Customer,<br><br>I hope this email finds you well. We appreciate your interest in utilizing the SmartView camera feature in your SmartCool refrigerator. Here is a step-by-step guide to help you effectively use this feature:<br><br>1. Touch View Inside on the SmartCool fridge display screen.<br>2. You can ...<br>---<br>5. To access the Shopping List, touch the MENU button on the display screen and then select Go to Shopping List.<br><br>By following these steps, you will be able to make the most out of the SmartView camera feature in your SmartCool refrigerator.<br><br>If you encounter any difficulties or have any further questions, please do not hesitate to reach out to us. Our customer service team is here to assist you with any queries you may have.<br><br>Thank you for choosing our SmartCool refrigerator. We hope this guide enhances your experience with our product.<br><br>Best regards,<br><br>[Your Name]<br>[Customer Service Representative]<br>[Company Name]</pre><p>So, what happened? The RAG used the chat query to retrieve a set of matching documents (text) from the vector store and then used the matched text as context along with the query in the prompt to the LLM to generate the response that we see above.</p><h4>ServiceNow AI Agent</h4><p>In the previous RAG example, notice that the chain is static. It uses the external knowledge base as a reference and always follows the same path, albeit coming up with creative answers. Imagine if we had multiple data sources and complex workflows and we wanted the LLM to traverse the right path in the workflow depending on the query and the external data available. That’s exactly what an Agent in LangChain can do.</p><p>Let us now build a reasoning agent that is able to use LLM to decide what actions to take next without adhering to a predetermined chain. As with RAG, there are a lot of Tools already available in LangChain but none for ServiceNow, so we’ll create one based on the instructions on this page: <a href="https://python.langchain.com/docs/how_to/custom_tools/">How to create Tools</a>.</p><p>You can find a sample ServiceNow Tool in servicenow_api_wrapper.py in the Github repository.</p><p>The Tool defines two functions: get_incidents() and create_incident().</p><p>The get_incidents() function uses the ServiceNow GET API call to return a list of incidents.</p><pre>def get_incidents(self, query: str) -&gt; str:<br>    headers = {&quot;Content-Type&quot;: &quot;application/JSON&quot;,<br>                   &quot;Accept&quot;: &quot;application/json&quot;}<br>    url = self.url + &quot;/api/now/table/incident?sysparm_limit=&quot; + \<br>            str(self.limit) + &quot;&amp;sysparm_query=&quot; + sysparm_query + \<br>                &quot;&amp;sysparm_fields=&quot; + self.fields<br>    response = requests.get(url, auth=(self.username, self.password), headers=headers)</pre><p>The create_incident() function uses a POST request to create an incident using the parameters.</p><pre>def create_incident(self, query: str) -&gt; str:<br>    url = self.url + &quot;/api/now/table/incident&quot;<br>    headers = {&quot;Content-Type&quot;: &quot;application/json&quot;,<br>                   &quot;Accept&quot;: &quot;application/json&quot;}<br>    response = requests.post(self.url, auth=(self.username, self.password), headers=headers, data=query)<br>    return response</pre><p>Once we are done with the Tool, we can create the Agent (see test_agent.ipynb). As usual, we need to load the relevant modules and source the environment variables first, including the OpenAI API key.</p><pre>import os<br>from dotenv import load_dotenv<br>from langchain_openai import ChatOpenAI<br>from langchain import hub<br>from langchain.agents import AgentExecutor, create_openai_functions_agent<br>from langchain.tools import Tool<br>load_dotenv()</pre><p>It is important to define prompts that guide the LLM in choosing the right tool. Here is an example prompt telling the Agent how to use the tool to get Incident records.</p><pre>SERVICENOW_GET_RECORDS_PROMPT = &quot;&quot;&quot;<br>    This tool is a wrapper around the ServiceNow table API, useful when you need to search for records in ServiceNow.<br>    Records can be of type Incident, Change Requests or Service Requests.<br>    The input to the tool is a query string that filters results based on attribute value.<br>    For example, to find all the Incident records with Priority value of 1, you would <br>    pass the following string: priority=1<br>    &quot;&quot;&quot;<br>SERVICENOW_INC_CREATE_PROMPT =</pre><p>We need to define the tools next. In addition to the ServiceNow tool we just built, we also load a built-in tool for web-scraping, the DuckGoGoSearch Tool.</p><pre>from snow_api_wrapper import ServiceNowAPIWrapper<br>from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper</pre><pre>servicenow = ServiceNowAPIWrapper()<br>duckduck_search = DuckDuckGoSearchAPIWrapper()</pre><p>Next, create the toolkit, which is simply a list of tools. Notice how we are using the predefined prompts as the description of the tools to help the LLM.</p><pre>tools = [<br>    Tool.from_function(<br>        name = &quot;ServiceNow_Get&quot;,<br>        func=servicenow.get_incidents,<br>        description=SERVICENOW_GET_RECORDS_PROMPT<br>    ),<br>    Tool(<br>        name = &quot;Search_DuckDuckGo&quot;,<br>        func=duckduck_search.run,<br>        description=&quot;useful for when you need to answer questions about current events. You should ask targeted questions&quot;<br>    )<br>]</pre><p>Next, let’s create the Agent Executor, using the LLM, agent and standard prompt as input.</p><pre>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;, temperature=0)<br>prompt = hub.pull(&quot;hwchase17/openai-functions-agent&quot;)<br>agent = create_openai_functions_agent(llm, tools, prompt)<br>agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)</pre><p>OK, that’s the agent done. Let’s ask it a question.</p><pre>response = agent_executor.invoke({&quot;input&quot;:&quot;You are a technical support analyst. Retrieve a list of ServiceNow incidents of priority 1 and for each incident, use its description to find a solution on the web.&quot;})</pre><p>The Agent responds as follows. It determines the most appropriate tool is ServiceNow_Get and lists out the incidents.</p><pre>&gt; Entering new AgentExecutor chain...<br>Invoking: `ServiceNow_Get` with `priority=1`<br>number: INC0000060<br>short_description: Unable to connect to email<br>description: I am unable to connect to the email server. It appears to be down.<br>number: INC0009002<br>short_description: My computer is not detecting the headphone device<br>---Truncated---</pre><p>It then uses the Search agent to search for solutions on the web.</p><pre>Invoking: `Search_DuckDuckGo` with `solution for unable to connect to email server`<br><br>In Control Panel, search for and open the Mail icon. On the Mail Setup - Outlook window, click Email Accounts. On the Account Settings window, ....<br><br>Invoking: `Search_DuckDuckGo` with `solution for computer not detecting headphone device`<br>---Truncated---</pre><p>Finally, it summarises the solutions in a nicely readable list:</p><pre>1. **Incident: Unable to connect to email**<br>   - **Solution:** To fix the issue of being unable to connect to the email server, you can try the following steps:<br>     - Check the Incoming mail server and Outgoing mail server settings.<br>     - Change the view type to Large icons and click on Mail (Microsoft Outlook).<br>     - Add an Email Account Again.<br>     - Use encryption method as SSL/TLS.<br>2. **Incident: My computer is not detecting the headphone device**<br>   - **Solution:** To resolve the issue of the computer not detecting the headphone device, you can try the following:<br>     - Check if the headset mic is disabled in Windows 10.<br>     - Remove and re-add the headphones.<br>     - Run a troubleshooter.<br>     - Manually set Headphones as the default device.<br>---Truncated---</pre><p>Now let us try a different prompt to create an incident.</p><pre>response = agent_executor.invoke({&quot;input&quot;:&quot;You are a technical support analyst and a customer has just called about a faulty laptop. Create a ServiceNow incident for this issue.&quot;})</pre><p>And here is the response. As before, the agent determines that the most appropriate Tool for this query is ServiceNow_Create.</p><pre>&gt; Entering new AgentExecutor chain...<br><br>Invoking: `ServiceNow_Create` with `{&quot;short_description&quot;: &quot;Faulty laptop issue&quot;, &quot;description&quot;: &quot;Customer reported an issue with a faulty laptop. Please investigate and resolve.&quot;}`<br><br>&lt;Response [200]&gt;I have successfully created a ServiceNow incident for the faulty laptop issue.</pre><p>The agent called the tool with appropriate field values for short_description and description.</p><p>And here’s the incident as created in ServiceNow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGcoGg9IDSvq-Q3Z5MNFUw.jpeg" /></figure><h4>A better UX with Streamlit</h4><p>The way we have tested queries so far, from within the code itself is not a great user experience. Let’s fix that by using another of my favorite tools — Streamlit. It’s a great tool for creating interactive web applications with just a few lines of Python code. We will use it to create a simple yet engaging chat interface.</p><p>I won’t reproduce any of the code here, as we will reuse what has already been described in the previous sections. Just make sure you have the appropriate modules installed and loaded.</p><pre>pip inslall streamlit</pre><p>The code for this app is available in st_app.py.</p><p>We have added the following additional features to this app.</p><ul><li>Display retrieved incidents in a table using the AgGrid module allows us to display the retrieved incidents in a table.</li><li>Ability to plot graphs using the plotly package.</li><li>Analyse retrieved data and perform actions using the Pandas Dataframe tool.</li></ul><p>Let us see this in action. You can launch the chatbot app as follows:</p><pre>streamlit run st_app.py</pre><p>The app will launch in a browser tab and should look something like below. The sidebar on the left allows you to choose a few options, and the main canvas contains the chat interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQadQPZsA04rv4LMi41ZQw.jpeg" /></figure><p>Let us try out a few questions. We’ll try the RAG use case first, leave the other options unchanged, and type the following question in the chat input:</p><p>You are a customer service agent. Draft an email to a customer on how to use the SmartView Camera.</p><p>You should see the bot respond with something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ieGq_Ww0OOYmtJYa6hSy-w.jpeg" /></figure><p>As before, the app first retrieves the matching documents from the ServiceNow knowledge base and passes this on to the LLM as context to generate the email.</p><p>Next, let us try the Agent from the left sidebar. Leave the other options unchanged for now. Choose the “Action” radio button option for the type of chat. You should see a list of incidents retrieved from ServiceNow. Note that there is no LLM or LangChain used yet in this case. It simply calls the ServiceNow REST API and displays the results using AG Grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Echk-DR81-zo-oZj2ALF9A.jpeg" /></figure><p>Selecting a row from the table will display the chat interaction container below the table, where you can ask a question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2FsywYNeEelgIBqegWIfg.jpeg" /></figure><p>We are asking the agent to use the incident as the context and search for a solution on the web. The agent response should look something like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hvk4cqXNAv4HIsjOw9793A.jpeg" /></figure><p>Observe how the agent used the incident details and passed them to the Search tool. You can see the input and output of the search tool in the collapsed container. The completed response shows the resolution as above.</p><p>Finally, let us try the ability of the agent to use another tool to analyse the data in the table and plot a graph. It will use the Pandas dataframe tool and the Plotly package to plot.</p><p>Select the Analyze radio button option from the left sidebar. Enter your query as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1o4IS9UVdXYm6EkMTqGcA.jpeg" /></figure><p>The agent will get into action, this time generating plotly code to draw the graph as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkN0GC7bb2plg4sYMY3_Eg.jpeg" /></figure><p>You can see the code that the agent generated if you expand the containers above the graph. Pretty neat, eh!</p><p>Using this interface, one can experiment further with the code and different prompts.</p><h3>Wrap up</h3><p>We’ve only scratched the surface in this article, but one can imagine the incredible potential and possibilities of using LLM technologies for business process automation. This is an active area of development, and new framework capabilities are emerging on a regular basis, opening new avenues and approaches for developing intelligent automation applications.</p><p>One such example is LangGraph, an orchestration framework built on top of LangChain that incorporates a persistence layer to enable human-in-the-loop interactions. LangGraph Studio adds low-code, visual ability to develop complex agentic applications much more easily than before. Visualising agent graphs helps application developers understand the complex data interactions in agentic applications.</p><p>We live in interesting times indeed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45c280826847" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accelerating the Adoption of CSDM]]></title>
            <link>https://medium.com/@sanjayraina/accelerating-the-adoption-of-csdm-f978640a293d?source=rss-53fea6a84fa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f978640a293d</guid>
            <category><![CDATA[cmdb]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[itsm]]></category>
            <category><![CDATA[servicenow]]></category>
            <dc:creator><![CDATA[Sanjay Raina]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 14:39:19 GMT</pubDate>
            <atom:updated>2024-03-19T14:39:19.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0mE9e78ahimyU72KbaWiA.jpeg" /></figure><p>ServiceNow Common Service Data Model (CSDM) is a standard framework and prescriptive guidance for modelling and managing business services and service-related data in the CMDB. It provides common nomenclature and structure for defining, organising, and exchanging data, ensuring consistency and accuracy throughout the service management lifecycle.</p><p>ServiceNow recommends a staged approach to implementing CSDM, using the Crawl, Walk, Run methodology. This helps breakdown the complexity of a large-scale technology change into stages of increasing complexity. However, there is a problem with this approach — it often takes considerable time and effort before any tangible benefits of CSDM are realised by the business. Early stages of such implementations, though important, do not have enough functionality to deliver significant value.</p><p>This article describes a more agile approach — one where greater value can be achieved earlier on a smaller scale with limited scope, i.e. a minimum value product. Once the benefits are proven, adoption and roll-out at larger scale can be achieved by replicating iteratively.</p><h3>ServiceNow CSDM and the staged deployment approach</h3><p>The Common Service Data Model (CSDM) is a standardised and extensible framework designed to facilitate sharing and integration of service-related data across diverse IT service management (ITSM) platforms. It extends the CMDB and integrates with foundation and infrastructure data to provide an extensive data architecture for service management, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L74OMSf4-RYRjJjywdzEgQ.png" /><figcaption>Courtesy and © ServiceNow</figcaption></figure><h4>CSDM Domains</h4><p>The CSDM framework is characterised by a set of domains and services. Each of the domains contains different types of services and other entities linked together to model different business functions and capabilities.</p><ul><li><strong>Foundation domain</strong> contains the base, referential data such as locations, companies, users and groups.</li><li><strong>Sell/Consume domain</strong> represents the business portfolio of (customer oriented) business services and service offerings.</li><li><strong>Manage Technical Services domain</strong> contains the technology components and service provider related information (support model) , including application services, technical services and service offerings.</li><li><strong>Design domain</strong> contains elements for design and planning, including business capabilities, business applications and information objects.</li><li><strong>Build domain</strong> contains data entities relating to DevOps and the build process.</li></ul><p>The Sell/Consume and Manage Technical Services domains contain a set of services and service offerings to model the services and map these to the infrastructure and application Configuration Items.</p><ul><li><strong>Business Service</strong> supports a business capability and is typically underpinned by one or more application services.</li><li><strong>Application Service</strong> is the logical representations of a deployed system or application stack and it covers all components of an application or service.</li><li><strong>Technical Service</strong> is a technical capability that underpins one or more application services.</li></ul><h3>Crawl, Walk, Run deployment approach</h3><p>ServiceNow recomends a staged approach for implementing CSDM. It involves starting with basic, foundational steps (Foundation, Crawl), gradually building upon them (Walk), and ultimately reaching a state of advanced proficiency and optimisation (Fly). These stages are shown below along with a description of each stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*pb4mw7chh4qvA0qXsrQUsg.png" /></figure><ul><li><strong>Foundation</strong>: Accurate foundational referential data that is referenced throughout the model. Examples include: Companies, Locations, Users and Groups.</li><li><strong>Crawl</strong>: Creation of Business Applications and Application Services and a minimum requirement for Incident, Problem and Change. Enables the foundation for application and technology portfolio management.</li><li><strong>Walk</strong>: Creation of the Technical Services and Technical Service Offerings. Enables the meta data related to support and management of CIs.</li><li><strong>Run</strong>: Creation of Business Services and Service Offerings in the sell/consume domain. Enables impact assessment for ITSM.</li><li><strong>Fly</strong>: Creation of Business Capabilities, Request Catalog Items and Information Objects. Enables the foundation for application and service portfolio management.</li></ul><p>The staged-based methodology clearly has benefits. Breaking down the implementation process into smaller, manageable phases allows teams to make steady progress without feeling overwhelmed. Starting with simple steps ensures that everyone can participate and understand the changes, laying a solid foundation for more complex activities later on.</p><p>By starting with basic steps in the early stages, organisations can identify and mitigate risks early in the process. This proactive approach helps prevent potential issues from escalating as the implementation progresses to more advanced stages.</p><p>However, there are a few problems with this approach.</p><ul><li><strong>Prolonged implementation</strong>: early stages can take substantial amount of time and effort, without delivering significant business value. The Foundation stage can be quite complex due to lack of good quality data sources to populate the referential data. Similarly, in the Crawl stage the sheer volume of products and services managed by an organisation can be a significant challenge.</li><li><strong>Lack of business value in early stages</strong>: Even when significant progress is made in early stages, it does not translate into tangible business benefits. Notable improvements are only realised when business services and service offerings are implemented (Run phase). This leads to disillusionment from the business stakeholders due to perceived lack of progress.</li><li><strong>Difficulty in transitioning from stages:</strong> Transitioning from one phase to the next is still a challenge. It takes considerable effort and planning to start each new stage.</li><li><strong>Lack of flexibility and feedback</strong>: The stage based approach has a whiff of waterfall about it — big upfront effort in planning and development of early stages without early feedback of outcomes from stakeholders. Stakeholder requirements may change during the course of the project or certain features such as application/service portfolio management may not be required.</li></ul><h3>Towards a more agile approach</h3><p>In order to address the above issues, a more pragmatic and flexible approach is needed — where outcomes of positive business benefits are achieved early and where continuous feedback from stakeholders can guide a successful implementation instead of “boiling the ocean”.</p><p>Adopting an agile approach to CSDM implementation has a number of advantages:</p><ul><li><strong>Reduced initial complexity</strong> by building and minimum viable product (MVP) implementation first. This helps demonstrate the full capabilities of CSDM without getting bogged down by enterprise-wide constraints and challenges.</li><li><strong>Early benefits realisation</strong> on a smaller scale, giving comfort to stakeholders and the project sponsor.</li><li><strong>Easier path to scale</strong> &amp; replicate. Once the implementation has been proven at small scale for a single product or business area, it can be used as a blueprint for expansion enterprise wide.</li><li><strong>Testing, refinement and course-correction</strong> is easier. CSDM can have significant impact on existing system and processes and requirements may be refined over time.</li><li><strong>Continuous involvement of stakeholders</strong> and delegation of activities. CSDM can also have impact on ways of working, so keeping the affected teams involved and engaged helps the implementation.</li></ul><p>So how does one go about it.</p><h4><strong>Start small with an MVP</strong></h4><p>Recall the layer-cake depiction of the staged approach show above and think of the MVP solution as a thin vertical slice of the cake, as shown below. It incorporates the required elements of the Foundation, Crawl, Walk and Run stages to deliver the solution for a single product or a narrow business area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*RIokwcHuY4pYUB2ci-YqiQ.png" /></figure><p>Such a solution would include all the foundation data, the application, business and technical services pertaining to that single product or business area rather than considering all of the applications and infrastructure.</p><h4>Identify key business value drivers</h4><p>It is important to quantify business benefits using metrics that the stakeholders and business leaders can easily relate to. Unless the outcomes of the CSDM implementation are clear and measurable, it becomes difficult to justify the associated investment and impact. Common metrics relate to volume and resolution time of issues. In particular, CSDM helps improve Incident, Problem and Change Management processes.</p><ul><li>Service impact modelling is a key value driver that helps determine the root cause and impact of an issue on customers and related services.</li><li>Technical services and service offerings help improve resolution by identifying the support and maintenance metadata associate with provision of services.</li></ul><h4>Create a blueprint</h4><p>There are two reasons why a blueprint can be useful. First, as a medium of collaboration with stakeholders — CSDM introduces many new concepts and has broad impact on teams and processes. A blueprint creates common awareness and understanding of how CSDM will be utilised across an organisation. It also helps stakeholders articulate their requirements better in a clear manner.</p><p>Secondly, it serves as a reference template for replicating the MVP implementation across a wide range of enterprise applications and services. It is much easier to apply the blueprint to new products and services rather than starting from scratch. All the feedback and knowledge gained from previous iterations can be incrementally applied and adapted to other products and services.</p><h4>Build standard templates and visual aids</h4><p>A picture is worth a thousand words as the saying goes. CSDM models are conventionally drawn in a standard colour coded manner. It can be useful to adopt the Diagram as Code (DaC) approach to create CSDM diagrams in a consistent and quick manner. The figure below shows an example using the PlantUML drawing tool. Further details of how to use DaC for CSDM can be found in a separate article <a href="https://medium.com/@sanjayraina/using-diagram-as-code-for-csdm-implementation-4c2d93181b44">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCK16erMTUiZZ9o-tGgrug.png" /></figure><h4>Orchestrate deployment via low-code tools</h4><p>ServiceNow platform has a number of low-code and no-code utilities that can help with the adoption of CSDM. One such capability is the Process Automation Designer (PAD). It can be used to orchestrate processes where CSDM deployment is a key aspect of the process. The figure below shows an onboarding process defined in PAD where CSDM implementation is part of the process that includes CMDB and ITOM setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkMUGDuZMJvDUg3OUEUPeA.png" /></figure><p>The process workflow in the example above serves as guided setup and contains a set of activities or tasks that can be automated or assigned to a particular team for fulfilment. Resolvers in assigned teams are further guided by the Playbook Experience workspace showing them their assigned task in context of the overall onboarding process.</p><p>For more information on these tools, refer to ServiceNow documentation:</p><ul><li><a href="https://www.servicenow.com/uk/products/process-automation-designer.html">Process Automation Designer</a></li><li><a href="https://docs.servicenow.com/bundle/washingtondc-build-workflows/page/administer/process-automation-designer/concept/process-automation-designer-landing-page.html">Playbook Experience</a></li></ul><h4>Finally, don’t forget roles and responsibilities</h4><p>One must not underestimate organisational implications of a CSDM project. The guidance here is to engage all stakeholders early on, not just to inform but to seek their active participation and delegation of activities.</p><p>In particular, product owners and service owners should spearhead the adoption by communicating the new ways of working and the benefits of CSDM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f978640a293d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Diagram as Code for CSDM Implementation]]></title>
            <link>https://medium.com/@sanjayraina/using-diagram-as-code-for-csdm-implementation-4c2d93181b44?source=rss-53fea6a84fa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c2d93181b44</guid>
            <dc:creator><![CDATA[Sanjay Raina]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 16:35:29 GMT</pubDate>
            <atom:updated>2024-03-15T16:50:09.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mr1-LWV5u1nXs7ABaoCKg.jpeg" /></figure><p>ServiceNow Common Service Data Model (CSDM) is a standard framework and prescriptive guidance for modelling and managing business services and service-related data in the CMDB. As with enterprise architecture frameworks, CSDM uses standard notation and nomenclature to depict business service model components.</p><p>Consistent schematic representation of business service models helps stakeholders visualise and communicate various aspects during design, implementation and operation. Documenting a large number of CSDM models can be a challenge for organisations with large number of IT project and services.</p><p>This article describes how Diagram as Code can be leveraged to manage the creation and maintenance of CSDM diagrams.</p><h3>Drawing CSDM models</h3><p>A CSDM model for a solution is depicted using colour coded domains enclosing blocks representing services and other configuration data items as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQfuSfBNPHnFuvhC3iVUyQ.png" /></figure><ul><li><strong>Foundation</strong> domain is shaded grey and contains all the core referential data entities (non-CIs). It includes common data elements such as Company, Location, Group and User, as well as Products and Contracts.</li><li><strong>Design</strong> domain is coloured blue and contains elements for design and planning, including Business Capability, Business Application and Information Object.</li><li><strong>Build</strong> domain is coloured red/pink and contains data entities relating to DevOps and the build process.</li><li><strong>Manage Technical Services</strong> domain is coloured amber/orange and represent the provider view of technology deployed to run a business. It includes Application Services, Technical Services as well as the Configuration Items (of various types).</li><li><strong>Sell/Consume</strong> domain is coloured green and represents business portfolio and services that are consumed by customers. It includes Business Services, Portfolios and Service Offerings.</li></ul><p>ServiceNow provides plenty of guidance to help implement CSDM including a set or example available <a href="https://nowlearning.servicenow.com/nowcreate/en/pages/assets?id=nc_asset&amp;asset_id=dfd5c0ae871255d0f2f443f7dabb359b">here</a>. One such example is shown below. It shows the component items in the Design, Sell/Consume and Manage Technical Services domains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVG3c4hLNjTFfBY5afgeKg.png" /></figure><h3>Diagram as Code &amp; PlantUML</h3><p>Diagram as Code (DaC) is a concept that promotes the idea of creating visual representations of an architecture or code artefacts using actual code. This approach aligns with the principles of infrastructure as code (IaC) and configuration as code (CaC), bringing the benefits of version control, collaboration, and automation to the realm of diagrams.</p><p>By treating diagrams as code, developers and analysts can leverage their existing skills in coding and version control systems to manage and maintain visual representations of software architecture. This ensures that diagrams stay up-to-date, consistent, and can be seamlessly integrated into the development workflow.</p><p>The benefits of using DaC for CSDM include:</p><ul><li><strong>Consistency</strong>: Code-based diagrams foster consistency while producing and sharing CSDM artefacts.</li><li><strong>Automation</strong>: Automated generation of diagrams ensures efficiency and reduces the manual effort required to maintain documentation.</li><li><strong>Collaboration</strong>: Stakeholders can collaborate on diagrams just like they do with code, fostering teamwork and knowledge sharing.</li><li><strong>Readability</strong>: Simple, intuitive syntax makes it easy for both technical and non-technical stakeholders to understand and contribute to the documentation.</li></ul><p><a href="https://plantuml.com/">PlantUML</a> is one example of a DaC tool. Other options include <a href="https://mermaid.js.org/">Mermaid</a> and <a href="https://github.com/mingrammer/diagrams">Diagrams</a>. There are a number of ways to get started with PlantUML, as outlined in this <a href="https://plantuml.com/starting">Quick Start Guide</a>. The easiest way is to use the online tool <a href="https://www.planttext.com/">here</a>.</p><p>I prefer to use PlantUML via the VS Code IDE extension. It allows easy rendering and preview of the diagram as you write the code in VS Code editor.</p><p>PlantUML contains a repertoire of diagram types, as specified by the <em>@start&lt;type&gt;</em> and <em>@end&lt;type&gt;</em> tags in your code. In addition to the generic UML type, there are MindMap, Gantt Chart and other types. A PlantUML diagram file contains a set of directives that create nodes and relations. Common code can be written once in a separate “library” and then reused by including in projects.</p><p>More details about PlantUML can be found in the following guides:</p><ul><li><a href="https://plantuml.com/guide">PDF guide</a></li><li><a href="https://crashedmind.github.io/PlantUMLHitchhikersGuide/">HitchHikers Guide to PlantUML</a></li><li><a href="https://www.augmentedmind.de/2021/01/31/plantuml-advanced-features/">AugmentedMind Tutorial</a></li></ul><h3>Creating CSDM diagrams with PlantUML</h3><p>We will first start with the common boiler-plate code that we will be including in all CSDM diagrams. This creates the consistent layout and colour coding required for the CSDM standard. It also helps keep the main code representing the model clear and concise.</p><p>The common include file is available here: <a href="https://github.com/sanjayraina/csdm-puml/blob/d5c941d75acfacde0e78f9d76909b30545e7b33c/CSDM.puml">CSDM.puml</a></p><p>It includes code for the legend:</p><pre>legend top right<br>        &lt;b&gt;Legend&lt;/b&gt;<br>        &lt;#FFFFFF,#FFFFFF&gt;|  &lt;#24C2Ce&gt; BC | Business Capability|<br>        | &lt;#24C2Ce&gt; BA  | Business Application|<br>        | &lt;#009156&gt; BS  | Business Service|<br>        | &lt;#009156&gt; BSO | Business Service Offering|<br>        | &lt;#FCA822&gt; TS | Technical Service |<br>        | &lt;#FCA822&gt; TSO | Technical Service Offering|<br>        | &lt;#FCA822&gt; AS | Application Service |<br>        | &lt;#FCA822&gt; CI | Configuration Item |<br>        |  | &lt;b&gt;Not all components shown for brevity&lt;/b&gt;|<br>    endlegend</pre><p>The above code renders the legend as follows and places it at the top right in the drawing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*Uw_mOkf2-KcqmzsZl0o1Ng.png" /></figure><p>The include file also contains decoration of different cards representing entities in different domains. The fragment below shows definition of the Business Capability and its corresponding rendering.</p><pre>&#39; Define Business Capability<br>!unquoted procedure $BusinessCapability($name)<br>     #24C2Ce;line:black;line.bold;text:Black [<br>         BC<br>         ----<br>         $name<br>     ]<br>!endprocedure</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*dYaRoY64cfOs-94JaMPBLA.png" /></figure><p>The include file is added to the main diagram with the !include directive as shown below. The fragment also shows the package directive creating a collection of cards representing entities within the Design domain.</p><pre>@startuml<br>!include ../CSDM.puml<br>title O365 Platform<br>&#39; Design Domain<br>&#39;<br>package &quot;Design&quot; {<br>    top to bottom direction<br>    card ba_o365 $BusinessApplication(&quot;O365 E5&quot;)<br>    card ba_ad $BusinessApplication(&quot;Active Directory&quot;)<br>    card ba_teams $BusinessApplication(&quot;MS Teams&quot;)<br>    card ba_sp_online $BusinessApplication(&quot;Sharepoint Online&quot;)<br>    card ba_exchange $BusinessApplication(&quot;MS Exchange&quot;)<br>}</pre><p>Other domains can be similarly created. Relationships are created using arrow notation as shown below.</p><pre>&#39; Relationships<br>ba_o365-d-&gt;ba_teams<br>ba_o365-d-&gt;ba_sp_online<br>ba_o365-d-&gt;ba_exchange<br>sp_comms--&gt;bs_email<br>sp_comms--&gt;bs_direct_mesg</pre><p>The complete code for the above diagram is available here: <a href="https://github.com/sanjayraina/csdm-puml/blob/d5c941d75acfacde0e78f9d76909b30545e7b33c/Examples/O365Platform.puml">O365Platform.puml</a> and rendered as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GJF4K_N6EBxQrsye0Iysg.png" /></figure><p>PlantUML diagram code of other examples can be found in this Github <a href="https://github.com/sanjayraina/csdm-puml.git">repository</a> and includes the following:</p><ul><li><a href="https://github.com/sanjayraina/csdm-puml/blob/d5c941d75acfacde0e78f9d76909b30545e7b33c/Examples/ClientCompueHW.puml">Client Computer Hardware</a></li><li><a href="https://github.com/sanjayraina/csdm-puml/blob/d5c941d75acfacde0e78f9d76909b30545e7b33c/Examples/ConferenceRoom.puml">Conference Room</a></li><li><a href="https://github.com/sanjayraina/csdm-puml/blob/d5c941d75acfacde0e78f9d76909b30545e7b33c/Examples/Microservices.puml">Microservice</a></li><li><a href="https://github.com/sanjayraina/csdm-puml/blob/d5c941d75acfacde0e78f9d76909b30545e7b33c/Examples/MSDynamics.puml">MSDynamics</a></li><li><a href="https://github.com/sanjayraina/csdm-puml/blob/d5c941d75acfacde0e78f9d76909b30545e7b33c/Examples/SaaSwOnPrem.puml">SaaS Software on prem</a></li><li><a href="https://github.com/sanjayraina/csdm-puml/blob/d5c941d75acfacde0e78f9d76909b30545e7b33c/Examples/SAPFinancials.puml">SAP Financials</a></li><li><a href="https://github.com/sanjayraina/csdm-puml/blob/d5c941d75acfacde0e78f9d76909b30545e7b33c/Examples/SharedTechService.puml">Shared Technical Service</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c2d93181b44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add VR magic to ServiceNow with Amazon Sumerian]]></title>
            <link>https://medium.com/@sanjayraina/add-vr-magic-to-servicenow-with-amazon-sumerian-61232c68fd77?source=rss-53fea6a84fa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/61232c68fd77</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[servicenow]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sanjay Raina]]></dc:creator>
            <pubDate>Sun, 13 Sep 2020 18:49:39 GMT</pubDate>
            <atom:updated>2023-01-30T20:35:09.473Z</atom:updated>
            <content:encoded><![CDATA[<h3>Add VR Chatbot to ServiceNow with Amazon Sumerian</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHaowgc8RY8yKbqRNn6LIw.jpeg" /></figure><p>About a year ago I <a href="https://chatbotslife.com/a-chatbot-for-servicenow-using-amazon-connect-lex-and-lambda-cb7ed7f090b4?source=friends_link&amp;sk=f8216fe0fe89e32ff09d48fc7d72dda3">blogged</a> about how Amazon Connect and other AWS services can be integrated with ServiceNow to build intelligent voice user interfaces for the Service Desk. Since then ServiceNow has recognised the potential of Amazon Connect and recently released an official integration between Amazon Connect and ServiceNow as part of its Cloud Call Center offering, as reported <a href="https://www.zdnet.com/article/servicenow-integrates-with-amazon-connect-eyes-cloud-call-center-market-amid-remote-works-new-normal/">here</a>. Enterprises are now able to replace their legacy call center solutions with omni-channel Chatbots and conversational user interfaces, to build powerful customer service solutions.</p><p>Another technology that is likely to have a disruptive impact in this space is Virtual Reality. Although Virtual Reality (VR) and Augmented Reality (AR) technologies have been around for a while, their use and development has been somewhat of a niche area. We are now beginning to see mainstream adoption of VR/AR in both consumer and enterprise space. There are a couple of reasons behind this.</p><ul><li>Improved hardware availability: new generation headsets from pioneers such as Oculus and rumoured, imminent arrival of Smart eyewear devices from the likes of Apple and Nimo.</li><li>Better application development environments: availability of web-based, low-code development environments such as Amazon Sumerian, making it easier to develop 3D AR/VR applications.</li></ul><p>In this article we explore the use case of a Virtual Reality service agent, assisting a customer with a support query. We will build a VR support agent using Amazon Sumerian and then use Amazon Lex and AWS Lambda (similar to my previous blog article) to interact with ServiceNow. In addition to Sumerian, we will utilise Amazon Amplify to develop the browser app as well as backend AWS services. A few words about these two services:</p><ul><li><strong>Amazon Sumerian </strong>is a new service offering from Amazon that includes a low-code platform enabling augmented and virtual reality applications to be built without requiring any specialist graphics skills or expensive hardware. Sumerian integrates with other AWS and external cloud services to enable immersive and interactive customer experience applications to be built.</li><li><strong>Amazon Amplify</strong>: is a development framework for creating full-stack applications including front-end UI/UX using React, Angular and iOS, as well as backend services for data storage and authentication.</li></ul><blockquote><strong>Note</strong>: this solution has not been tried on any AR/VR headsets. We will confine ourselves to a WebGL capable browser.</blockquote><p>The solution described here enacts a scenario where a VR agent acts as a service desk agent and initiates a dialog with the end user. The user request is forwarded to Amazon Lex to be interpreted, to determine the intent, and then forwarded on to ServiceNow through a Lambda function to retrieve information or trigger a workflow in ServiceNow. Here is a high level conceptual view of the solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dnsvhFLfjcXpzXPiyJKzJQ.png" /><figcaption>Conceptual view</figcaption></figure><h3>Prerequisites</h3><h4>AWS account</h4><p>This will be needed to run the various Amazon and AWS services. Make sure to choose a region that has all the services (outlined below) available. If you do not have an AWS account, you can register for a free-tier account at <a href="https://aws.amazon.com/free.">https://aws.amazon.com/free</a>. <strong><em>CAUTION</em></strong><em>: You may incur charges, based on your usage. Please consult the details about the usage and pricing of Amazon services.</em></p><h4>ServiceNow developer instance</h4><p>You can sign up for a developer instance at <a href="https://developer.servicenow.com/">https://developer.servicenow.com</a>. You will receive a personal sandbox environment of the form devNNNNN.service-now.com.</p><h3>Implementation overview</h3><p>Our solution will consist of a number of components built using different cloud services.</p><ul><li>Base <strong>Sumerian</strong> Scene: a room with a Sumerian Host acting as virtual service agent</li><li><strong>ServiceNow</strong>: we’ll create a user with <em>ITIL</em> role that can retrieve a list of Incidents via a REST call</li><li><strong>AWS Lambda</strong> function: a serverless function that make a POST call to ServiceNow</li><li><strong>Amazon Lex</strong> bot: to drive the conversational element of the VR-agent in the scene</li><li><strong>AWS Amplify</strong>: to build a React app to present the scene to the user and set up of the backend AWS services</li><li><strong>Sumerian </strong>Host: add the conversation/dialog workflow and Lex bot to the Sumerian Host</li><li><strong>ServiceNow</strong> Portal: create a Portal widget to launch the Sumerian scene.</li></ul><p>Let’s get started.</p><h3>Let’s create a scene… a Sumerian scene</h3><p>If you are new to Amazon Sumerian, there are some excellent tutorials and beginners resources available online. I recommend the following:</p><ul><li><a href="https://docs.sumerian.amazonaws.com/tutorials/create/intermediate/amplify-react-2/">Getting Started with Amazon Sumerian, AWS Amplify, and the React Component</a></li><li><a href="https://medium.com/@dabit3/building-ar-vr-experiences-with-react-amazon-sumerian-aws-amplify-789976db1689">Building AR &amp; VR Experiences with React, Amazon Sumerian &amp; AWS Amplify</a></li></ul><p>To start with, log into the AWS Management console and choose the Sumerian service. You are taken to the Sumerian dashboard. From here, creating a new scene will launch the editor where you’ll see the blank canvas. We’ll start by adding some ambience to the scene and creating a room for the VR agent.</p><h4>Create a room</h4><ul><li>From the Sumerian dashboard create a new scene and give it a name, e.g. VR-agent.</li><li>Using <em>Create Entity</em> at the top, choose a 3D Primitive to create a box.</li><li>In the <em>Inspector</em> panel on the right, expand the <em>Material</em> component, choose the <em>Culling</em> property of the entity and set the <em>Cull Face</em><strong><em> </em></strong>to Front. This allows us to see and render the inside of the box.</li><li>Expand the <em>Transform</em> component to set the dimensions of the room. I chose values as: <em>Scale: X=5, Y=5, Z=5 </em>and <em>Translation: X=0, Y=0.5, Z=0</em></li><li>Choose a colour of the room using the <em>Material</em> component. I chose blue-grey from the palette.</li><li>Add a <em>Point Light</em> entity, using <em>Create Entity</em>. I chose the Transform values as: <em>Scale: X=1, Y=1, Z=1</em> and <em>Translation: X=0, y=4, Z=0</em></li><li>Add another <em>Box</em> entity to create a counter with Transform values: <em>Scale: X=0.5</em>, Y=1, Z=2 and <em>Translation: X=0, Y=-1.5, Z=-1.5</em></li><li>Add a flat screen TV: click on Import Assets at the top of the editor and look for <em>Television Hanging</em>. Double click to add this to your Assets. Drag and drop this entity from Assets onto the scene. Adjust the Transform as: <em>Scale: X=0.6, Y=0.6, Z=0.6, Rotation: X=0, Y=90, Z=0</em> and <em>Translation: X=-0.24, Y=0.2, Z=-0.4</em></li><li>Add the company logo: add another Box entity with Transform as: <em>Scale: X=1.6, Y=0.4, Z=0.05, Rotation: X=0, Y=90, Z=0</em> and <em>Translation: X=-2.5, Y=1, Z=1</em>. Add a logo image as material texture.</li></ul><p>If you wish you can change or add more furniture to the room.With the room prepared, let us drop our agent into it — a <em>Host</em> in Sumerian parlance.</p><h4>Add the Host</h4><p>Hosts can be imported into the scene using Import Assets above the canvas. There are various options available. We have chosen Maya for our project.</p><ul><li>Click on the <em>Import Assets </em>button above the canvas and choose <em>Maya</em>. This will add the host as an asset pack.</li><li>From the <em>Assets</em> panel on the left, find the host entity and drag it to the scene. Adjust the Transform as: <em>Scale: X=1, Y=1, Z=1, Rotation: X=0, Y=90, Z=0 </em>and <em>Translation: X=0, Y=-2, Z=1.5</em></li><li>The Host normally stares blankly into space, but we will make it look at the default camera using the <em>Point of Interest </em>property. You’ll find this under the Host component on the right. Set it to <em>Look at Entity</em></li></ul><p>The scene should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_MlBlxHP7hMdY5GfVY6zgA.png" /></figure><p>You can now test the scene within the editor by clicking on the Play button at the bottom of the canvas. Notice that when you rotate the scene, host Maya’s eyes will follow you.</p><p>We can now P<em>ublish</em> the scene from the upper-right corner, and then choose <em>Host privately</em>. This will generate a JSON config file that will be required in the next section. Download this file, giving it a shorter name if required, e.g. sumerian_exports_VR-agent.json.</p><p>With the basic scene in place, we can add some interactivity. However, before we do that, we need to set up the backend AWS and ServiceNow services for the agent to perform actions. We will come back to the Sumerian Scene a bit later on.</p><h3>Create ServiceNow user to run REST calls</h3><p>As with my previous article, our agent will be performing simple actions of creating and retrieving Incident tickets in ServiceNow. We will be using REST calls to query the ServiceNow instance, so there is not much configuration on the ServiceNow side, other that creating a user that can run API calls and have read and write access to the relevant tables (e.g. with an ITIL role). At this stage it’s a good idea to validate that the REST calls to the instance run with the chosen user are working. You can do this with Postman or a similar tool.</p><h3>Build the AWS Lambda function</h3><p>The Lambda function is needed to initiate the GET and POST calls to ServiceNow to retrieve and create tickets. From the AWS console, locate the Lambda service and click on <em>Create function</em>.</p><ul><li>Choose <em>Author from scratch </em>and<em> </em>give it a name. We will call it <em>sumerian-bot-servicenow.</em></li><li>Choose runtime as Node.js 12.x and then <em>Create function.</em></li><li>The code of the function is available on Github <a href="https://github.com/sanjayraina/sumerian-bot-servicenow">here</a>. Copy this Function code into <em>index.js </em>in the Lambda console<em>.</em></li></ul><p>The code implements a handler that gets invoked when the Lambda function is called. The event parameter gets passed in from the Lex service and it contains the intent and slots. There are two types of intents: <em>GetTickets</em> and <em>LogTicket</em>, that call the corresponding functions:</p><ul><li><em>getTickets()</em> sets up a GET request to ServiceNow as shown below.</li></ul><pre>var snowInstance = process.env.SERVICENOW_HOST;var options = {<br>      hostname: snowInstance,<br>      port: 443,<br>      path: &#39;/api/now/table/&#39; + recType + &#39;?sysparm_query=ORDERBYDESCsys_updated_on&amp;sysparm_limit=&#39;+count,<br>      method: &#39;get&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        Accept: &#39;application/json&#39;,<br>        Authorization: &#39;Basic &#39; + Buffer.from(process.env.SERVICENOW_USERNAME + &quot;:&quot; + process.env.SERVICENOW_PASSWORD).toString(&#39;base64&#39;),<br>      }<br>  };</pre><ul><li><em>logTickets() </em>sets up a POST request to ServiceNow as shown below.</li></ul><pre>var options = {<br>        host: process.env.SERVICENOW_HOST,<br>        port: &#39;443&#39;,<br>        path: &#39;/api/now/table/&#39; + recType,<br>        method: &#39;POST&#39;,<br>        headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;Accept&#39;: &#39;application/json&#39;,<br>            &#39;Authorization&#39;: &#39;Basic &#39; + Buffer.from(process.env.SERVICENOW_USERNAME + &quot;:&quot; + process.env.SERVICENOW_PASSWORD).toString(&#39;base64&#39;),<br>            &#39;Content-Length&#39;: Buffer.byteLength(postData)<br>        }<br>    };</pre><ul><li>Next we create the following Environment variables with appropriate values:</li></ul><pre>SERVICENOW_HOST        &lt;FQDN of your developer ServiceNow instance&gt;<br>SERVICENOW_USERNAME<br>SERVICENOW_PASSWORD</pre><ul><li>Save the Lambda function</li></ul><p>That’s the Lambda function done. Let’s move on to create the Lex bot.</p><h3>Build Lex bot</h3><p>The Lex bot manages the conversation between the user and our VR agent. Head over to the Lex service landing page from the AWS console.</p><ul><li>Choose <em>Create</em> and the <em>(Create Your Own) Custom bot </em>and give it a name, e.g. <em>SumerianServiceNow</em>.</li><li>Set the output voice to None for now, as the voice output is handled by Sumerian</li><li>Set the session timeout to 5 minutes, leave the IAM role to the default chosen and set the COPPA field to No.</li><li>With the above settings, hit the Create button to open up the Lex editor</li><li>To start with let us create an Intent. We shall call it <em>Get_Tickets</em> and fill in some details next</li><li><em>Sample utterances </em>are used to invoke the intent. We’ll add just one for now — “What are the top tickets”</li><li>Ignore<em> Lambda initialization and validation</em>.</li><li>Before we continue with <em>Slots</em>, we’ll create a new slot type. From the left menu, click on the <em>+</em> sign, next to <em>Slot types</em>. In the dialog box enter a name for the slot type, and a sample value. We’ll create a slot type: <em>Ticket_Type</em> with values as <em>incident</em>. We will use built in slot type <em>AMAZON.NUMBER</em> for the <em>ticketCount</em> slot.</li><li><em>Slots</em> are used to pass data to the bot. We’ll define two slots using the two slot types defined above, with prompts: “<em>What is the type of ticket?</em>” and “<em>How many tickets?</em>” respectively.</li><li><em>Confirmation prompt </em>is used to ask the user to confirm the response. We shall leave it out for this example.</li><li>Fulfilment is used to call the Lambda function that we defined earlier. Choose the Lambda function <em>sumerian-bot-servicenow. </em>You will be prompted to give the Lex bot permission to invoke the Lambda function.</li><li>The editor should now look something like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cNh47ktQxPbmrGHaWNEMA.png" /><figcaption>Get_Tickets Intent</figcaption></figure><ul><li>Use the same procedure as above to create another Intent called LogTicket and it should look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vm6H3HtHa7YdvXJg6wrE3g.png" /><figcaption>Log_Ticket Intent</figcaption></figure><p>You can now build the Lex bot and once done, you will get a confirmation message at the top. Once the build completes, you can test the bot via text interface, using the <em>Test bot </em>window on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*L87UghScjkNp4OmJw1Oaig.png" /><figcaption>Test your bot</figcaption></figure><p>OK, that’s the Lex bot done as well. We’ll now create the web app and configure additional AWS services.</p><h3>Create the app and backend services with Amplify</h3><p>We will use the browser to present and interact with the Sumerian Scene. The web app and associated backend services will be built using AWS Amplify.</p><h4>Create the React app</h4><p>The React web app will be configured using the Amplify CLI. We will add authentication (Amazon Cognito) and AR/XR backend services to it.</p><ul><li>Install and configure the Amplify CLI, as explained <a href="https://docs.amplify.aws/start/getting-started/installation/q/integration/react">here</a>.</li><li>Start by creating a project:</li></ul><p>$ npx create-react-app sumerian-servicenow-app</p><ul><li>Change to the React project folder, and then install the aws-amplify and aws-amplify-react libraries, and initialise the project:</li></ul><pre>$ cd sumerian-servicenow-app<br>$ yarn add aws-amplify aws-amplify-react --save<br>$ amplify init</pre><ul><li>In response provide suitable options as follows. This will create some resources in AWS.</li></ul><pre>? <strong>Enter a name for the project</strong> sumerian-servicenow<br>? <strong>Enter a name for the environment</strong> dev<br>? <strong>Choose your default editor:</strong> Atom Editor<br>? <strong>Choose the type of app that you&#39;re building</strong> javascript<br>Please tell us about your project<br>? <strong>What javascript framework are you using</strong> react<br>? <strong>Source Directory Path: </strong> src<br>? <strong>Distribution Directory Path:</strong> build<br>? <strong>Build Command: </strong> npm run-script build<br>? <strong>Start Command:</strong> npm run-script start<br>Using default provider  awscloudformation<br>? <strong>Do you want to use an AWS profile?</strong> Yes<br>? <strong>Please choose the profile you want to use</strong> amplify-user</pre><ul><li>Add authentication backend, choosing options as follows:</li></ul><pre>$ amplify add auth</pre><pre><strong>Do you want to use the default authentication and security configuration?</strong> Default configuration<br><strong>How do you want users to be able to sign in?</strong> Username<br><strong>Do you want to configure advanced settings?</strong> No, I am done.</pre><ul><li>Add AR/XR backend, choosing options as follows, specifying the sumerian_exports_ VRagent.json file we saved when we configured the base Sumerian Scene above.</li></ul><pre>$ amplify add xr</pre><pre>? <strong>Provide a name for the scene:</strong> VRagent<br>? <strong>Enter the path to the downloaded JSON configuration file for VRagent:</strong> /tmp/sumerian_exports_VRagent.json<br>? <strong>Would you like to allow unauthenticated users access to the Sumerian project for this scene?</strong> No</pre><ul><li>Add authentication and XR to the React app. Change src/App.js as follows</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a350fed819900cc2eb9d49c199953cd2/href">https://medium.com/media/a350fed819900cc2eb9d49c199953cd2/href</a></iframe><h4>Deploy backend services</h4><p>Now build and deploy the backend resources in AWS.</p><pre>$ amplify push</pre><p>This will take some time, so have a break! When you come back, check whether Amplify has successfully deployed the services and then continue with the Sumerian scene.</p><h3>Continue with Sumerian scene</h3><p>Head back to the Sumerian console.</p><ul><li>From the previous (Amplify) step, open the src/aws-exports.js file and copy the value of attribute <em>aws-cognito_identity_pool_id </em>and paste this into the <em>AWS Configuration </em>component in the Inspector panel.</li><li>Republish the Scene from top-right</li><li>You should now be able to launch the Sumerian Scene web app locally from a web browser.</li></ul><pre>$ yarn start</pre><ul><li>The React app will present a Login UI. Click on Create an account.</li><li>Log in with the account just created and you should be presented with the familiar Sumerian Scene we created earlier.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vzfvb6MfpP4yHxnM6RClmg.png" /><figcaption>Scene in local browser</figcaption></figure><p>You should be able to move the scene around but not do much else. We will now add interactivity features and weave all the stuff we’ve built so far into the Scene.</p><h4>Add an initial greeting</h4><p>We want our scene to start with host Maya introducing herself with a greeting, and prompting the user for their request. We’ll do this by adding a speech component to the Host. Back to the Sumerian console.</p><ul><li>Select the Maya Host entity and expand the Speech component in the Inspector panel. Choose a voice option, e.g. Amy.</li><li>Under the Speech files drop-down in the Speech component, click on the + sign to add new speech. This will open the speech text editor.</li><li>Type the introductory greeting in the text editor and save.</li></ul><h4>Add gestures and animation</h4><p>To make our host more life-like we will add animation and gesture capability.</p><ul><li>Adjust the Animate Using Speech set of properties under the Host component as follows:<br><em>- Lip Sync: ticked<br>- Gestures: ticked<br>- Gesture Hold: 10<br>- Min Gesture Period: 0.1</em></li><li>Gesture tags can be added to text in speech files to make the host gesture while speaking. This can be tricky to get right and takes a bit of practice. Fortunately, Sumerian has the ability to auto generate gestures.</li><li>Under the <em>Gesture Map</em> drop down, choose the default <em>Gesture Map</em>. This will enable the auto gesture generation icon, next to the Intro speech file.</li><li>Click on the Auto-generate gesture marks icon. If you review/edit the Intro speech file again, you will see your text interspersed with gesture tags.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0TpgKBw10yh3yOvm0KSSg.png" /><figcaption>Gesture tags</figcaption></figure><h4>Connect with Lex Bot</h4><p>After the initial greeting, we want our host to engage in a conversation with the user. This is achieved by configuring the Dialogue component in the Host entity, to point to the Lex Bot we created earlier.</p><ul><li>From the Host entity open the Dialogue Component. You may need to add the component (using <em>+ Add component</em> a the bottom)</li><li>Enter the Name and Alias of the Dialog component to correspond to the Lex Bot</li></ul><h4>Add State Machine</h4><p>With all the building blocks of the Host configured, we need to knit these together in a workflow. This is done through the <em>State Machine</em> component, by adding a <em>Behaviour</em>. Behaviours are collections of States and Transitions that guide changes in entities, driven by user interaction. This enables a Host to respond to requests and commands in a conversation with the user. State Machine has its own low-code editor interface to build behaviours in a graphical manner.</p><ul><li>Open the State Machine component (you may need to add this) and add a new Behaviour. Give it a name, e.g. <em>Agent Behaviour</em>.</li><li>The State Machine editor will open below the Scene canvas showing the Behaviour with an initial state.</li><li>Change the name of the initial state to AWS SDK and then add the action AWS SDK Ready.</li><li>Click on <em>+ Add State</em> at the top-left of the State Machine editor to add a new state. This state waits for 5 seconds, so add the Wait action and specify 5 seconds. Rename the state to <em>Initial Wait</em>. Add a state transition from the initial (AWS SDK) state to this state by clicking and holding on the initial state and then dragging to the current (Wait) state. This will result in a blue arrow from one state to another.</li><li>Following the above procedure create a new state to wait until the user taps the Host (with a mouse click). The action to add is <em>Click/Tap on Entity</em>. As before, add the state transition from the Wait State to the On Tap state.</li><li>Add the next State to play the introductory greeting. Use the <em>Start Speech</em> action and choose the Intro Speech file created earlier. Leave the <em>Use Lex Response</em> box unchecked. Add the state transition from previous state.</li><li>Add another <em>Click/Tap on Entity </em>state. This will trigger the recording of the user response. Add the state transition from previous state.</li><li>Add another state to start recording, using the action <em>Start Microphone Recording. </em>Add the state transition from previous state. Add another <em>Click/Tap on Entity </em>state.</li><li>Add the next state to end recording, using the action <em>Stop Microphone Recording. </em>Add the state transition from previous state.</li><li>The next state will hand over the recorded user response to the Lex Bot for processing. We will use the action <em>Send Audio Input to Dialogue Bot</em>. Add the state transition from previous state.</li><li>Add the last state to play the response back from the Lex Bot. Add a state action of type <em>Start Speech</em>. In this case do not choose a speech file and instead check the <em>Use Lex Response</em> box. Add state transition from <em>On Response Ready</em> in the previous state to the current state.</li><li>Finally add a state transition from the above <em>Replay Response</em> state to the <em>Wait for Tap</em> state. This will enable the VR agent to go around the loop of recording another input from user and getting a response back from the Lex Bot. The complete State Machine Behaviour should look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ibw2iNj7rdIqe13eBE5yoQ.png" /><figcaption>State machine behaviour</figcaption></figure><h4>IAM Policies</h4><p>We need to give the Sumerian role (created by Amplify) permissions to Polly and Lex services on AWS.</p><ul><li>Identify the Sumerian authenticated role from the Cognito identity pool. E.g. <em>amplify-sumerian-servicenow-dev-xxxxx-authRole</em></li><li>Go to IAM console and locate this role and attach the policies: <em>AmazonPollyReadOnlyAccess</em> and <em>AmazonLexRunBotsOnly</em></li></ul><h4>Host the React App</h4><p>So far we have been testing the Sumerian web app locally with yarn start. In order to run the app from anywhere, we will need to host it. With Amplify we can host our app on S3 (Dev environment) or S3 with CloudFront (Prod environment).</p><ul><li>Add hosting, choosing the PROD environment option:</li></ul><pre>$ amplify add hosting<br>Scanning for plugins...<br>Plugin scan successful<br>? <strong>Select the environment setup:</strong> PROD (S3 with CloudFront using HTTPS)<br>? <strong>hosting bucket name</strong> sumerian-servicenow-20200123456789-hostingbucket</pre><ul><li>Publish the app</li></ul><pre>$ amplify publish</pre><p>When the above command finishes, you will be provided with a CloudFront URL of your app. Open this URL in a browser and you should see the login panel as before. Once logged in, the Sumerian app will load. Make a note of this URL.</p><h3>Create a widget to launch VR-agent from ServiceNow Portal</h3><p>This step is not strictly necessary, but as a finishing touch we will create a widget to launch the VR agent from a ServiceNow portal.</p><h4>Create the Portal Widget</h4><p>The purpose of the widget is to launch the Sumerian Scene when the corresponding link is clicked. The code for our widget is shown below and consist of HTML, CSS and the Client Script. Note that it contains the number of other links that we use for other demos. You only need the Sumerian link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Z1Ycsy05dpbbVZExuY_iA.png" /><figcaption>ServiceNow Widget</figcaption></figure><h4>Add widget to Portal Page</h4><p>You can add the above widget to any page in the ServiceNow Portal. We have added it to our landing page as shown below. When we click on the VR Agent as highlighted, the Sumerian Scene launches in a new dialog window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfdbIrZNswbu8lMnznRT2g.png" /><figcaption>VR Agent launched from ServiceNow Portal</figcaption></figure><p>That’s it! Our VR Agent is ready for action!</p><h3>Take it for a spin</h3><p>Here’s a video showing a demo interaction with the VR Agent.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP6ZIR93u0vU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DP6ZIR93u0vU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FP6ZIR93u0vU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f233e33498b5fccd49a8bbf2982210b/href">https://medium.com/media/7f233e33498b5fccd49a8bbf2982210b/href</a></iframe><h3>Delete resources</h3><p>Don’t forget to clean up once you’re done and don’t want to incur any charges unnecessarily.</p><pre>$ amplify delete</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61232c68fd77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A ChatBot for ServiceNow using Amazon Connect, Lex and Lambda]]></title>
            <link>https://blog.chatbotslife.com/a-chatbot-for-servicenow-using-amazon-connect-lex-and-lambda-cb7ed7f090b4?source=rss-53fea6a84fa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb7ed7f090b4</guid>
            <category><![CDATA[servicenow]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Sanjay Raina]]></dc:creator>
            <pubDate>Sun, 21 Jul 2019 18:09:34 GMT</pubDate>
            <atom:updated>2019-12-17T18:26:40.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*oJ0WlLAdMtwxaImm0Wmniw.png" /></figure><p>AWS and ServiceNow are two great platforms for building compelling services and solutions in the cloud. The recent availability of AI capabilities in both platforms has paved the way for a new class of innovative and autonomous applications. ChatBots are one such class of applications and ServiceNow’s offering in this area comes in the form of Virtual Agent which is based on the Parlo acquisition made by ServiceNow a year ago. Amazon has a vast and growing array of AI services, including a veritable collection relating to speech and natural language processing.</p><p>This article demonstrates the power of combining ServiceNow with Amazon AI and IaaS services to build a service desk <a href="https://chatbotslife.com/">Chatbot</a> that interacts with ServiceNow to log and retrieve tickets.</p><p>There are excellent resources available online about Chatbots and Amazon AI services. In particular, I would recommend the book <a href="https://www.amazon.com/Machine-Learning-AWS-artificial-intelligence/dp/1789806194">Machine Learning with AWS by Jeffrey Jakovich and Ruze Richards</a>. The code and concepts described here have been derived from the material in this book.</p><p>The solution uses:</p><ul><li><strong>Amazon Connect</strong>: enables virtual contact centres to be built very quickly in the cloud at low cost. Gone are the days of having to worry about SIP trunking and SBC servers. A virtual contact centre in the cloud can be spun up as easily as bringing up an EC2 instance on AWS. We will set up a phone number and a simple contact flow to drive our chat bot.</li><li><strong>Amazon Lex</strong>: This will be our voice interface. Lex is the same natural language processing technology that is behind Alexa. Our chatbot will interpret voice commands using Lex</li></ul><h3>Top 3 Most Popular Bot Design Articles:</h3><blockquote><a href="https://chatbotslife.com/ultimate-bot-design-guide-a-living-doc-69a589ee0028">1. Ultimate Bot Design Guide</a></blockquote><blockquote><a href="https://chatbotslife.com/how-to-design-a-chatbot-4cddea10a4ab">2. How to design a Chatbot</a></blockquote><blockquote><a href="https://chatbotslife.com/distributing-a-slack-app-d5b4cf9ee317">3. Distributing a slack app</a></blockquote><ul><li><strong>AWS Lambda</strong>: Bots often need to do some work in response to commands. This may involve automation and calls to external services. Lambda functions enable us to run Serverless code without the need for hosting any applications. In our case we’ll use Lambda to call APIs into ServiceNow.</li><li><strong>ServiceNow</strong>: This is our target system that services requests to log and query ticket information. Using REST API, any table within ServiceNow can be accessed via CRUD operations.</li></ul><p>So, here’s how these components are put together in our solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*fuzDYQ67USAN3Obdj5VgkQ.png" /><figcaption>Conceptual overview</figcaption></figure><h3>Prerequisites</h3><h4>AWS account</h4><p>This will be needed to run the Lambda function. If you do not have an AWS account, you can register for a free-tier account at <a href="https://aws.amazon.com/free.">https://aws.amazon.com/free</a>. <strong><em>CAUTION</em></strong><em>: You may incur charges, based on your usage. Please consult the details about the usage and pricing of Amazon services.</em></p><h4>ServiceNow developer instance</h4><p>You can sign up for a developer instance at <a href="https://developer.servicenow.com/">https://developer.servicenow.com</a>. You will receive a personal sandbox environment of the form devNNNNN.service-now.com.</p><h3>Implementing the solution</h3><p>We will implement the solution in reverse order, starting with ServiceNow.</p><h4>ServiceNow</h4><p>We will be using REST calls to query the ServiceNow instance, so there is not much configuration on the ServiceNow side, other that creating a user that can run API calls and have read and write access to the relevant tables. At this stage it’s a good idea to validate that the REST calls to the instance run with the chosen user are working. You can do this with Postman or a similar tool, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQO-lZ05zDyPbzYBy7gyEw.png" /><figcaption>Validate using Postman</figcaption></figure><p>So, our REST call appears to be working directly. Great! Now, let’s build a Lambda function to make the REST calls.</p><h4>AWS Lambda</h4><p>Let’s create the Lambda function using the AWS console.</p><ul><li>Start by choosing <em>Author from scratch</em>, give it a name. We will call it <em>connect-bot-servicenow.</em></li><li>Choose runtime as Node.js 8.10 and then <em>Create function.</em></li><li>The code of the function is available on Github <a href="https://github.com/sanjayraina/connect-bot-servicenow">here</a>.</li><li>Enter the code inline into <em>index.js</em>.</li></ul><p>The code implements a handler that gets invoked when the Lambda function is called. The event parameter gets passed in from the Lex service and it contains the intent and slots. There are two types of intents: GetTickets and LogTicket, that call the corresponding functions:</p><ul><li><em>getTickets()</em> sets up a GET request to ServiceNow as shown below.</li></ul><pre>var snowInstance = process.env.SERVICENOW_HOST;</pre><pre>var options = {<br>      hostname: snowInstance,<br>      port: 443,<br>      path: &#39;/api/now/table/&#39; + recType + &#39;?sysparm_query=ORDERBYDESCsys_updated_on&amp;sysparm_limit=&#39;+count,<br>      method: &#39;get&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        Accept: &#39;application/json&#39;,<br>        Authorization: &#39;Basic &#39; + Buffer.from(process.env.SERVICENOW_USERNAME + &quot;:&quot; + process.env.SERVICENOW_PASSWORD).toString(&#39;base64&#39;),<br>      }<br>  };</pre><ul><li><em>logTickets() </em>sets up a POST request to ServiceNow as shown below.</li></ul><pre>var options = {<br>        host: process.env.SERVICENOW_HOST,<br>        port: &#39;443&#39;,<br>        path: &#39;/api/now/table/&#39; + recType,<br>        method: &#39;POST&#39;,<br>        headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;Accept&#39;: &#39;application/json&#39;,<br>            &#39;Authorization&#39;: &#39;Basic &#39; + Buffer.from(process.env.SERVICENOW_USERNAME + &quot;:&quot; + process.env.SERVICENOW_PASSWORD).toString(&#39;base64&#39;),<br>            &#39;Content-Length&#39;: Buffer.byteLength(postData)<br>        }<br>    };</pre><ul><li>Next we create the following Environment variables with appropriate values:</li></ul><pre>SERVICENOW_HOST        &lt;FQDN of your developer ServiceNow instance&gt;<br>SERVICENOW_USERNAME<br>SERVICENOW_PASSWORD</pre><p>Now that we have created the Lambda function, we’ll move on to creating the conversational interface (aka <a href="https://chatbotslife.com/">ChatBot</a>) in using Lex.</p><h4>Amazon Lex</h4><p>Lex is managed like most other AWS services, from the console:</p><ul><li>From the Lex landing page on AWS console, choose <em>Create</em> and the <em>(Create Your Own) Custom bot</em></li><li>Choose a name. Let’s call it ConnectNow. Set the output voice to None for now, as the voice output is handled by the Connect app</li><li>Set the session timeout to 5 minutes, leave the IAM role to the default chosen and set the COPPA field to No.</li><li>With the above settings, hit the Create button to open up the Lex editor</li><li>To start with let’s create an Intent. We shall call it <em>GetTickets</em> and fill in some details next</li><li><em>Sample utterances </em>are used to invoke the intent. We’ll add just one for now — “Tell me the top tickets”</li><li><em>Lambda initialization and validation</em>. We’ll ignore this for now.</li><li>Before we continue with <em>Slots</em>, we’ll create some slot types. From the left menu, click on the <em>+</em> sign, next to <em>Slot types</em>. In the dialog box enter a name for the slot type, and a sample value. We’ll create two slot types: <em>TicketType</em> and <em>TicketCount</em> with values: <em>incident</em> and <em>1</em> respectively.</li><li><em>Slots</em> are used to pass data to the bot. We’ll define two slots using the two slot types defined above, with prompts: “<em>What is the type of ticket?</em>” and “<em>How many tickets?</em>” respectively.</li><li><em>Confirmation prompt </em>is used to ask the user to confirm the response. We shall leave it out for this example.</li><li>Fulfilment is used to call the Lambda function that we defined earlier, i.e. <em>connect-bot-servicenow.</em></li><li>The editor should look something like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdoE6fuXScYYytK9LSD6hw.png" /><figcaption>GetTickets Intent</figcaption></figure><ul><li>Use the same procedure as above to create another Intent called LogTicket and it should look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBySNCD7ZoW2vdnLoHdUiA.png" /><figcaption>LogTicket Intent</figcaption></figure><p>You can now build the <a href="https://chatbotslife.com/">ChatBot</a> and once done, you will get a confirmation message at the top. At this stage you can test the bot via text interface, using the Test bot window on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*PKWCqeganYCHpHQOc2YFtg.png" /><figcaption>Test your bot</figcaption></figure><p>We’re done with the ChatBot and nearly there. The ChatBot needs the means to interact with callers. We will set up a virtual contact centre where our ChatBot acts as an agent and responds to calls. We do this next using Amazon Connect.</p><h4>Amazon Connect</h4><p>Let’s create a new Amazon Connect instance.</p><ul><li>As usual log into the AWS console and look for the Amazon Connect service and click on <em>Add an instance.</em> This will launch the <em>Amazon Connect resource configuration</em> containing the following steps:</li><li><em>Step 1: Identity management</em>: we’ll stick to the first option, i.e. <em>Store users within Amazon Connect</em> and simply choose a unique name for the instance in the Access URL. We will call it <em>connectnowbot</em>. The access URL will be used to log in to the instance.</li><li><em>Step 2: Administrator</em>: we will create an administrator for this instance and enter the required details.</li><li><em>Step 3: Telephony options</em>: we will just choose incoming calls for now.</li><li><em>Step 4: Data storage</em>: leave as per default.</li><li><em>Step 5: Review and create</em>: to complete creation of the instance.</li><li>Log in to the instance and you should see the Welcome screen.</li><li>When you click <em>Let’s go</em>, you are presented with the option to claim a phone number. We will choose a local, direct dial number.</li><li>Congratulations! you’ve got your very own virtual contact centre! Go on try it out and dial the number. You will notice that the phone number will be associated with a sample inbound flow. This contact flow provides a simple IVR interface.</li><li>Amazon Connect is a sophisticated application and you can configure a variety of options to build a fully functional contact centre. However, we will just focus on the <em>Contact Flows </em>configuration to integrate with the Lex ChatBot we defined earlier.</li><li>Creating flows is a very intuitive experience with the help of the graphical editor. The editor provides a canvas and set of pre-defined blocks that can be assembled together using drag and drop functionality.</li><li>If you choose the <em>Contact flows</em> menu item from the left Routing menu, you will see a list of sample Contact flows that are available by default.</li><li>Go ahead and browse these to get familiar with the interface. When you are ready, click on <em>Create contact flow</em> to create a new flow.</li><li>You will see a blank canvas with the <em>Start</em> entry point block. Give the new contact flow a name, e.g. <em>ConnectNow Lex</em></li><li>Drag and drop the <em>Set voice</em> block from the left menu set and configure it to select the L<em>anguage</em> and V<em>oice</em>. We will choose <em>English (British)</em> and <em>Emma</em> and save.</li><li>Next we will link the output of the Start entry point to the input of the Set voice block.</li><li>To interact with the caller, we will add the <em>Get Customer Input</em> block.</li><li>Configure this block by choosing to play a prompt as <em>Text to speech (Ad hoc)</em> and enter some test, such as: “<em>Hi, this is ServiceNow chatbot. How may I help you today?</em>”</li><li>Next, choose <em>Amazon Lex</em> as the branching interface. Choose the Lex bot and then add the two Intents: <em>GetTickets</em> and <em>LogTicket</em>.</li><li>Add a <em>Play prompt </em>block and configure it to play a prompt as <em>Text to speech (Ad hoc) </em>with the following text: <em>“Thanks for using ServiceNow” Feel free to ask me anything else.</em></li><li>Add a link from GetTickets and LogTicket output to the Play prompt</li><li>Add a <em>Disconnect / hang up</em> block and link its input with the Error output from the <em>Get customer</em> input block.</li><li>The finished Contact flow should look something like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osWpc151smNYhJmE68HT1A.png" /><figcaption>Contact Flow</figcaption></figure><ul><li>Once you’re done you can publish the Contact flow.</li><li>The final step is to associate the newly build Contact flow with the phone number that was allocated earlier during the initial configuration of the Connect instance. This is done using the <em>Routing →Phone</em> <em>numbers</em> menu on the left. In the <em>Edit Phone</em> number screen, choose the ConnectNow Contact flow and <em>Save</em>.</li></ul><p>That’s it! Our ChatBot solution is ready and you can make your first call.</p><h3>Take it for a spin</h3><ul><li>Dial the number you claimed above when setting up Amazon Connect.</li><li>Have a dialog with your ChatBot:</li><li>ChatBot<em>: Hi, this is ServiceNow chatbot. How may I help you today?</em></li><li>You<em>: Tell me the top tickets.</em></li><li>ChatBot<em>: What type of tickets?</em></li><li>You<em>: Incident</em></li><li>ChatBot<em>: How many tickets?</em></li><li>You<em>: Two</em></li><li>ChatBot<em>: Here are the two recent incidents…</em></li><li>Hang up!</li></ul><h3>Don’t forget to give us your 👏 !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*ZxaGcKC3UQEydQIX" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e59ef%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e59ef&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e59ef%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7078d8ad19192c4c53d3bf199468e4ab/href">https://medium.com/media/7078d8ad19192c4c53d3bf199468e4ab/href</a></iframe><figure><a href="https://chatbotslife.com/bot-communities-mastermind-group-d2dae9876709#.53x0py6ou"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*6XUspT9JOSq0w0Fi35HIaA.png" /></a></figure><figure><a href="https://m.me/ChatbotsLife"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*c1LDMH5vbnIz9rmAka8Hwg.png" /></a></figure><figure><a href="https://chatbotslife.com/chatbot-development-hire-top-ai-chatbot-developers-c8b45ef7f207"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*D0Jf3dI6ZThtqcfwDYY7mg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb7ed7f090b4" width="1" height="1" alt=""><hr><p><a href="https://blog.chatbotslife.com/a-chatbot-for-servicenow-using-amazon-connect-lex-and-lambda-cb7ed7f090b4">A ChatBot for ServiceNow using Amazon Connect, Lex and Lambda</a> was originally published in <a href="https://blog.chatbotslife.com/">Chatbots Life</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Serverless Music Streamer with AWS Lambda and Alexa Voice Control]]></title>
            <link>https://medium.com/@sanjayraina/build-a-serverless-music-streamer-with-aws-lambda-and-alexa-voice-control-96887a2c7068?source=rss-53fea6a84fa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/96887a2c7068</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[alexa]]></category>
            <dc:creator><![CDATA[Sanjay Raina]]></dc:creator>
            <pubDate>Sat, 16 Feb 2019 15:01:45 GMT</pubDate>
            <atom:updated>2019-02-16T15:01:45.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*oo1WwoMcXpQ98o0uycxMVQ.jpeg" /></figure><p>Sometime ago I bought my first Amazon Echo device and soon discovered, like many others have, that music streaming options are somewhat limited unless you subscribe to one of the premium services from the likes of Spotify. What I really wanted was a low-cost solution to store my music collection on the cloud and stream it to the Echo. After looking around and not finding a suitable solution, I decided to try my hand at building my own. It was a perfect excuse to learn more about Alexa Skills and Serverless technologies. This article describes the solution that I attempted.</p><p><strong>NOTE</strong>: Amazon has recently released a <a href="https://developer.amazon.com/docs/music-skills/understand-the-music-skill-api.html">Music Skill API</a>. The skill described here does NOT use that API. Instead, this is a custom skill.</p><p>Before I continue, I’d like to mention that I came across some excellent resources on learning about Serverless and Alexa Skills. In particular, I would recommend the following. The code here has been derived from these sources.</p><ul><li>Peter Sbarski’s excellent book: <a href="https://www.manning.com/books/serverless-architectures-on-aws">Serverless Architectures on AWS</a></li><li><a href="https://serverless.com/">Serverless framework</a> examples on <a href="https://github.com/serverless/serverless">Github</a></li><li><a href="https://aws.amazon.com/quickstart/">AWS Quickstart templates</a></li><li>Alexa Skills <a href="https://github.com/alexa">Github</a> repository</li></ul><p>Alright, let’s start with an overview of main components that make up the solution, shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*OfFrlgADtt2RqSpI8rIWVQ.png" /></figure><p>In the main, it consists of:</p><ul><li>A Single Page App (SPA) acts as a front end to upload music. It also enables searching and playing music using a web browser. We use <a href="http://surge.sh/"><em>Surge.sh</em></a> to host the app and thus avoid having any web-hosting infrastructure.</li><li>APIs implemented with AWS API Gateway and associated Lambda functions. The APIs are called by the Alexa skill and the Web app.</li><li>Alexa Skill and the corresponding Lambda function, triggered by the Echo device and Alexa Voice Service.</li><li>OAuth authorisation capability to secure the APIs, implemented using Auth0. The authoriser is able to authenticate via external Identity providers.</li><li>AWS S3 bucket is used to store the music.</li><li>AWS DynamoDB is used to store metadata.</li></ul><h3>Some Prerequisites First</h3><h4>Node.js and npm</h4><p>We will use Node.js to implement our Lambda functions. So we need to install Node.js and npm to build the dependencies locally before deploying the code to AWS Lambda. You will need Node.js version 6.10 or later.</p><h4>AWS account</h4><p>This will be needed to run the Lambda functions. If you do not have an AWS account, you can register for a free-tier account at <a href="https://aws.amazon.com/free.">https://aws.amazon.com/free</a>.</p><p><strong><em>CAUTION</em></strong><em>: You may incur charges if you are not using the free-tier.</em></p><h4>IAM user and policy</h4><p>In the AWS console create an IAM user and attach the following policy to it.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;cloudformation:CreateStack&quot;,<br>		&quot;cloudformation:DeleteStack&quot;,<br>                &quot;cloudformation:DescribeChangeSet&quot;,<br>		&quot;cloudformation:DescribeStackEvents&quot;,<br>                &quot;cloudformation:DescribeStackResource&quot;,<br>                &quot;cloudformation:DescribeStackResources&quot;,<br>                &quot;cloudformation:DescribeStacks&quot;,<br>                &quot;cloudformation:GetTemplate&quot;,<br>                &quot;cloudformation:ListStackResources&quot;,<br>                &quot;cloudformation:UpdateStack&quot;,<br>		&quot;cloudformation:ValidateTemplate&quot;,<br>                &quot;iam:GetPolicy&quot;,<br>                &quot;iam:GetPolicyVersion&quot;,<br>                &quot;iam:GetRole&quot;,<br>                &quot;iam:GetRolePolicy&quot;,<br>                &quot;iam:ListAttachedRolePolicies&quot;,<br>                &quot;iam:ListRolePolicies&quot;,<br>                &quot;iam:ListRoles&quot;,<br>                &quot;iam:PassRole&quot;,<br>                &quot;iam:CreateRole&quot;,<br>                &quot;iam:AttachRolePolicy&quot;,<br>                &quot;iam:PutRolePolicy&quot;,<br> 		&quot;apigateway:*&quot;,<br>                &quot;cloudwatch:*&quot;,<br>                &quot;dynamodb:*&quot;,<br>                &quot;events:*&quot;,<br>                &quot;lambda:*&quot;,<br>                &quot;logs:*&quot;,<br>                &quot;s3:*&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><p>Make a note of the user’s access key and secret key. You will need these to configure the AWS CLI environment below.</p><h4>AWS CLI</h4><p>AWS commands are used during the deployment of various components. Install it as follows.</p><pre>$ pip install awscli --upgrade --user</pre><p>More details can be found at <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html</a>.</p><p>Configure the CLI as follows.</p><pre>$ aws configure<br>AWS Access Key ID [None]: &lt;Your_Access_Key&gt;<br>AWS Secret Access Key [None]: &lt;Your_Secret_Access_Key&gt;<br>Default region name [None]: eu-west-2<br>Default output format [None]: json</pre><h4>Amazon developer account</h4><p>An Amazon developer account is required to create and configure skills. You can create one at <a href="https://developer.amazon.com./">https://developer.amazon.com</a>. We will use Alexa Skills Kit SDK v2.</p><h4>ASK CLI</h4><p>Although skills can be developed using the console, we will use the command line interface. ASK CLI is a Node.js package, installed as follows.</p><pre>$ npm install -g ask-cli</pre><p>Configure the CLI tool as follows.</p><pre>$ ask init<br>? <strong>Please create a new profile or overwrite the existing profile.<br></strong>Create new profile<br>? <strong>Please type in your new profile name:<br></strong>default<br>-------------------- Initialize CLI --------------------<br>Setting up ask profile: [default]<br>? <strong>Please choose one from the following AWS profiles for skill&#39;s Lambda function deployment.<br></strong>mytunes-dev</pre><p>This will open a browser window and prompt you to log into your Amazon account.</p><h4>Auth0 account</h4><p>The Alexa Skill as well as the Browser app only allows authenticated users access to the music streamer APIs. We will use Auth0 to manage authentication. You can sign-up for an Auth0 account at: <a href="https://auth0.com/">https://auth0.com</a>. Auth0 authenticates users and then provides an OAuth access token that is used to provide secure access to APIs.</p><h4>Surge.sh account</h4><p>We will user Surge.sh to host our SPA Web app. Surge is a static web hosting facility where you can build highly interactive web apps using client-side code, all for free! You can find more information at <a href="https://surge.sh/help/getting-started-with-surge">https://surge.sh/help/getting-started-with-surge</a>.</p><p>You will need the Surge CLI. Install it with:</p><pre>$ sudo npm install --global surge</pre><p>Simply create your code (HTML + Javascript) locally and run surge from the directory to deploy. First time use will create an account for you and log you in. That simple!</p><h4>Serverless framework</h4><p>We will use the Serverless framework for building the APIs and associated Lambda functions. More details about the framework can be found at <a href="https://serverless.com/">https://serverless.com/</a>. It is an excellent tool for developing serverless code quickly. The Serverless CLI can be installed with:</p><pre>$ sudo npm install -g serverless</pre><h4>Download code</h4><p>The code for this project is available at <a href="https://github.com/sanjayraina/alexa-mytunes">https://github.com/sanjayraina/alexa-mytunes</a>. It contains the following sub-directories:</p><ul><li>Serverless: APIs and Lambda functions built using Serverless framework</li><li>SPA: Single Page Application hosted on Surge.sh</li><li>Alexa: Skill manifest and the Lambda function</li></ul><h3>Auth0 Setup</h3><p>If you haven’t already got one, create an <a href="https://auth0.com/">Auth0 account</a>. You should end up with a tenant domain like <em>mysite.eu.auth0.com</em>.</p><p>Create a new Application (API) with a name such as <em>MyTunes</em> and Identifier as <a href="https://mytunes/"><em>https://mytunes/</em></a>. This will be used as <em>Audience</em> value later. A machine to machine application will be created.</p><p>Make note of the Client Id and Client Secret. You will need these in the next step below. On the application page, click on <em>Show Advanced Settings</em> to reveal extra options. Click on the Certificates tab. Download the certificate to a file, e.g. <em>mysite.pem</em>. Convert the certificate to a string:</p><pre>$ awk &#39;NF {sub(/\r/, &quot;&quot;); printf &quot;%s\\n&quot;,$0;}&#39; mysite.pem</pre><p>You will need the certificate string in the next step below.</p><p>While you’re here, you may want to set up connections to one or more of social media sites, so these can be used as identity providers when authenticating users. You can also create local users if you want — these will be authenticated locally within the Auth0 database.</p><h3>Streamer APIs</h3><p>Serverless framework is a command line based toolkit for building and deploying Services and Functions using a number of Cloud providers, including AWS. The central concept in the framework is that of a Service that consists of Lambda functions, events and AWS infrastructure resources, defined in a file called serverless.yml. Our serverless.yml file in the Serverless sub-directory contains a single service definition called my-tunes. In the provider section it defines a number of environment variables obtained from a file called secrets.json in the same directory. You will need to set appropriate values in this file.</p><pre>{<br>  &quot;AUTH0_CLIENT_ID&quot;: &quot;&lt;Enter the Auth0 Client Id&gt;&quot;,<br>  &quot;AUTH0_CLIENT_CERT&quot;: &quot;&lt;Enter the long, certificate string&gt;&quot;,<br>  &quot;AUTH0_CLIENT_AUDIENCE&quot;: &quot;&lt;Enter the identifier, e.g. https://mytunes/&gt;&quot;,<br>  &quot;DYNAMODB_TABLE&quot;: &quot;&lt;Enter a name for the metaDB table, e.g. my-tunes-tracks&gt;&quot;,<br>  &quot;USERS_TABLE&quot;: &quot;&lt;Enter a name for the users table, e.g. my-tunes-users&gt;&quot;,<br>  &quot;UPLOAD_BUCKET&quot;: &quot;&lt;Enter a name for the S3 bucket to hold the media, e.g. my-tunes-tracks&gt;&quot;,<br>  &quot;ACCESS_KEY&quot;: &quot;&lt;Enter the AWS user Access Key&gt;&quot;,<br>  &quot;SECRET_ACCESS_KEY&quot;: &quot;&lt;Enter the secret key for the above user&gt;&quot;,<br>  &quot;UPLOAD_URI&quot;: &quot;&lt;Enter the S3 URI, e.g. https://s3.eu-west-2.amazonaws.com&gt;&quot;<br>}</pre><p>AUTH0_CLIENT_ID, AUTH_CLIENT_CERT and AUTH_CLIENT_AUDIENCE need to be set to values created when setting up the Auth0 client in previous section.</p><p>ACCESS_KEY and SECRET_ACCESS_KEY are obtained from the AWS IAM user you created earlier.</p><p>The next section in serverless.yml defines the four Lambda functions and the API resources.</p><h4>auth</h4><p>This is a custom authoriser used by the API. The handler for this function is defined in lambda/auth.js. The handler validates the authorisation token in the event. The validation is performed by jwt.verify() and in addition, the user is looked up in the DynamoDB users table to verify if the user is registered to access the application. If token validation fails or the user doesn’t exist in the users table, the custom authoriser fails and returns “Unauthorised user”.</p><h4>tracklist</h4><p>This function returns a list of tracks based on search criteria. The handler for this function is defined in lambda/tracklist.js. The search criteria includes a search attribute such as Album, Genre or Artist and a string value to search for. These are used to query the Metadata DynamoDB table and the result is returned as an array.</p><h4>metadb</h4><p>This function creates an entry in the Metadata table when a track is uploaded to S3. The handler for this function is defined in lambda/metadb.js.</p><h4>signedurl</h4><p>This function is used to return a temporary signed URL when uploading a file to S3 or playing a file. The handler for this function is defined in lambda/metadb.js.</p><h4>Deploy Serverless APIs</h4><p>Now that we have the code set up, we can go ahead and deploy it. First, install the NodeJS dependencies.</p><pre>$ cd Serverless<br>$ npm install</pre><p>Now deploy the APIs and associated Lambda functions on AWS.</p><pre>$ sls deploy</pre><p>This will create a set of API endpoints. Make note of these as you will need them in the next step.</p><h3>SPA Setup</h3><p>Although not strictly necessary, I also built a single page web app for a couple of reasons. One, to have an easy interface to upload tracks to the S3 bucket. And secondly, to compare the Alexa voice interface with a traditional web based player. The Web app follows a familiar layout in the SPA sub-directory:</p><ul><li>index.html — contains the static layout of the Web app</li><li>js/mytunes.js — contains the code for dynamic interactivity</li><li>images and css contain the associated images and stylesheets</li></ul><p>It uses the Bootstrap and Material Icons libraries to build a tabbed interface.</p><h4>Deployment</h4><p>Change directory to SPA and set the constants in js/mytunes.js as follows:</p><pre>AUTH0_CLIENT_ID = &quot;&lt;Enter the Auth0 Client Id&gt;&quot;;<br>AUTH0_DOMAIN = &quot;&lt;Enter the Auth0 domain&gt;&quot;;<br>AUTH0_AUDIENCE = &quot;&lt;Enter the identifier e.g. https://mytunes/&gt;&quot;;<br>METADB_ENDPOINT = &quot;&lt;Enter the metadb endpoint URI&gt;&quot;;<br>SIGNED_URL_ENDPOINT = &quot;&lt;Enter the signedurl endpoint URI&gt;&quot;;<br>TRACKS_ENDPOINT = &quot;&lt;Enter the tracklist endpoint URI&gt;&quot;;</pre><p>We will deploy the app to surge.sh. Choose a name for your SPA, e.g my-tunes, so your surge domain will correspondingly be my-tunes.surge.sh. Create a file called CNAME and enter this domain name in it.</p><p>Now go back to the Auth0 application page and enter the surge.sh URI in the Allowed Callback URL section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JaM5_oBF9DptZLhHitXxg.png" /></figure><p>Deploy the SPA to surge:</p><pre>$ surge</pre><p>The above will ask to create a surge.sh account on first run. Now you’re ready to launch the web app. Before we do that, we have to authorise the authenticated users with appropriate permissions. We want some users to be able to upload and play music tracks, while others are only allowed to play. I could automate this user management through the app, but I’m afraid at the moment this is a manual process.</p><h4>Add Authorised Users</h4><p>The Serverless framework service above creates a Dynamo DB table (USERS_TABLE) to keep track of authorised users and their permissions. Users that have authenticated will not be able to play or upload music, unless they have an entry in this table. Use the following procedure to add the user entry.</p><ul><li>Decide on what user account you are going to use to authenticate with, i.e. one of a social media accounts or a local account created on Auth0.</li><li>Use this account to log in to the SPA page (e.g. my-tunes.surge.sh)</li><li>On successful login, click on <em>Logged in as…</em> at the top right to bring up a pop up with the User Id. Copy the value.</li><li>Log in to the AWS console and head over to Dynamo DB. Locate the users table and create a record with following fields:</li></ul><pre>id = &lt;User Id value from above&gt;<br>name = &lt;Your name as will appear in &quot;Logged in as&quot;.<br>role = &lt;User or Admin. User allows play only. Admin allow play and upload&gt;</pre><h3>Launch App</h3><p>From a browser launch the SPA at <a href="http://my-tunes.surge.sh./">http://my-tunes.surge.sh</a> and log in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TBCR0K8uZlKddu8crcMvg.png" /></figure><p>An Auth0 dialog will prompt you for your credentials. Enter either a social media or local account that you have set up on Auth0 site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HFLATJarOeOIwDpNl2tQQ.png" /></figure><p>Once the user is logged in, the Upload and Search tabs become visible.</p><h4>Upload</h4><p>To upload one or more music tracks click on the Choose file button, fill in the Album and Artist details and click the Upload icon at the bottom. make sure the fields are not empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8CCm3Q7-AaFai96zdCgSg.png" /></figure><h4>Search and play</h4><p>The Search tab allows tracks to be searched based on Album, Artist etc. The search results are displayed in a table below. One or more of these tracks can be selected and the player buttons at the bottom used to play the music.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUEhBdeSyn2WvDoiXXw1pw.png" /></figure><h3>Alexa Skill</h3><p>This is the final part of the project that builds an Alexa skill to play music from the S3 bucket that music has been uploaded to as above. The skill uses Auth0 and AWS Lambda components described above to authenticate the user and to play the tracks.</p><p>The code is contained in the Alexa sub-directory and consists of the following files.</p><ul><li>.ask/config — deployment configuration</li><li>skill.json — the skill configuration</li><li>models/en-GB.json — the interaction model</li><li>lambda/custom/index.js — core lambda function</li><li>lambda/custom/package.json — package dependencies</li></ul><h4>Interaction Model</h4><p>The definition of the interaction model is contained in skill.json and en-GB.json. Alexa voice interactions work by decomposing speech into words and phrases that are sent to Alexa Voice Service (AVS) and an AWS Lambda function to be processed. The interaction schema is described in models/en-GB.json.</p><h4>Invocation</h4><p>Invocations are used to launch the skill. Our skill uses the following invocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*hrQueTCRTtDU8Hf1oB1eWQ.png" /></figure><p>Wake word initiates a new session. Launch “opens’ the skill and the invocation name identifies the skill.</p><h4>Utterance</h4><p>Utterances define the dialog in the skill and include phrases that get mapped onto Intents. Utterances can also include Slots that can take “variable” values. In our skill, sample utterances are of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*FEkq3ZvfHGgejpXPBa8FRg.png" /></figure><h4>Intents</h4><p>Intents define the goal or action that is to be accomplished by a voice exchange. The model defines a custom intent called PlayTrackIntent, with a number of slots types.</p><ul><li>Album</li><li>Genre</li><li>Artist</li><li>Playlist</li></ul><h4>Lambda function</h4><p>The Lambda function contains handlers to process the launch request and intents. There are also a number of Audio handlers.</p><p>The <strong>Launch handler </strong>simply plays a greeting and awaits a response to trigger an intent. It also retrieves the access token from the request, to be used later in the Intent handler. The access token is provided by Auth0 on authentication, once Account Linking has been enabled.</p><pre>const speechText = &#39;Welcome to the myTunes App. How can I help?&#39;;<br>accessToken = handlerInput.requestEnvelope.context.System.user.accessToken;<br>return handlerInput.responseBuilder<br>  .speak(speechText)<br>  .reprompt(speechText)<br>  .getResponse();</pre><p>The <strong>PlayTrack Intent handler</strong> contains code to construct a REST query to the Play Track endpoint. The POST request:</p><pre>const options = {<br>  hostname: API_HOST,<br>  port: 443,<br>  path: &#39;/dev/tracklist&#39;,<br>  method: &#39;POST&#39;,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;Content-Length&#39;: post_data.length,<br>    Authorization: hdr_auth<br>  }<br>};<br>const request = https.request(options, (response) =&gt; {<br>...</pre><p>The track list is stored in the persistent attributes table.</p><p>A signed URL is requested for the first track.</p><pre>const options = {<br>  hostname: API_HOST,<br>  port: 443,<br>  path: &#39;/dev/signedurl&#39; + &#39;?trackid=&#39; + encodeURI(track_id),<br>  method: &#39;GET&#39;,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    Authorization: hdr_auth<br>  }<br>};<br>const request = https.request(options, (response) =&gt; {</pre><p>The first track is played with the audioPlayerPlayDirective.</p><pre>addAudioPlayerPlayDirective(&#39;REPLACE_ALL&#39;, signed_url.url, track_list[0].id, 0, null);</pre><p>There are a number of other handlers.</p><ul><li>PlaybackStartedHandler</li><li>CancelAndStopIntentHandler</li><li>PlaybackNearlyFinishedHandler</li><li>PlaybackStoppedHandler</li><li>PlaybackFinishedHandler</li><li>NextTrackIntentHandler</li><li>PreviousTrackIntentHandler</li></ul><h4>Persistent Attributes</h4><p>Persistent attributes in a skill persist beyond the lifecycle of a session and we use it to store the state of the list of tracks that have been selected to be played. When a track is skipped or at the end of the pla back of a track, the next track is selected from this list using Persistent Attributes.</p><p>AttributesManager exposes attributes through the methods: getPersistentAttributes() and savePersistentAttributes(). More details on Persistent Attributes can be found in the <a href="https://ask-sdk-for-nodejs.readthedocs.io/en/latest/Managing-Attributes.html">ASK Node.js SDK docs</a>.</p><h4>Deployment</h4><p>Set the API_HOST variable in Alexa/lambda/custom/index.js to the API endpoint FQDN as obtained in the Serverless step above:</p><pre>const API_HOST = “&lt;YOUR API HOST FQDN&gt;”;</pre><p>Download the skill dependencies:</p><pre>$ cd Alexa/lambda/custom <br>$ npm install</pre><p>Deploy the skill and lambda function with ASK CLI:</p><pre>$ cd Alexa<br>$ ask deploy</pre><h4>Account linking</h4><p>Link the skill with Auth0. Log into [Alexa developer console] (<a href="https://developer.amazon.com/alexa/console/ask">https://developer.amazon.com/alexa/console/ask</a>) and navigate to the skill. Select the Account Linking tab to fill out the Auth0 application linking details. To obtain these details, refer to the Auth0 application created earlier. Expand the advanced settings link and and go to the <em>Endpoints</em> section.</p><p>Now go back to the Alexa Account Linking page and fill out the form as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gL3FUVJJFrkY6hf0oIQ-Q.png" /></figure><ul><li>Head over to your Amazon developer account at developer.amazon.comand log in.</li><li>Navigate to your newly deployed skill and click on Account Linking on the left to open the Account Linking form.</li><li>Turn on account linking using the first toggle button at the top and fill out the details from your Auth0 OAuth Endpoint.</li><li>Select an authorization grant type: Auth Code Grant</li><li>Authorization URI: <a href="https://optumis.eu.auth0.com/authorize?audience=https://mytunes/">https://&lt;Your Auth0 Domain&gt;/authorize?audience=https://mytunes/</a></li><li>Access Token URI: <a href="https://optumis.eu.auth0.com/oauth/token">https://&lt;Your Auth0 Domain&gt;/oauth/token</a></li><li>Client Id: &lt;As generated by Auth0 above&gt;</li><li>Client Secret: &lt;As generated by Auth0 above&gt;</li><li>Scope: openid, email, profile</li><li>Domain List: Your Auth0 Domain</li><li>Save the form.</li></ul><p>At the bottom of the Account Linking page you will find a number of <em>Redirect URLs</em>. Copy the first one (e.g. <a href="https://layla.amazon.com/api/skill/link/M26D1D2CM95YM6">https://layla.amazon.com/api/skill/link/M26D1D2CM95YM6</a>) and head over to the Auth0 configuration page. In the Allowed Callback URLs section, paste this URL, separated by a comma from the previous (SPA domain) entry. Save the Auth0 as well as Account Linking forms.</p><h3>Take it for a spin</h3><p>First, upload some music tracks using the SPA Web app. Use the browser to launch your Streamer app, e.g. <em>mytunes.surge.sh</em>.</p><ul><li>Log in with one of your social media accounts or a user account you have created in your Auth0 tenant. Once successful, you should see the <em>Upload</em> and <em>Play</em> tabs.</li><li>Before you progress further, make sure that the account you log in with has been added to the authorised users table (see above).</li><li>Go to the Upload tab and click on <em>Choose file</em> button to select an audio file on your local device.</li><li>Fill in the name of the <em>Album</em>, <em>Artist</em> and <em>Genre</em>.</li><li>Click on the <em>Upload</em> link at the bottom and wait for the file to be uploaded.</li></ul><p>If you haven’t already done so, install the Alexa app on your mobile device and make sure it is linked to your Amazon account and any Echo devices you want to use are registered with it. You should be able to see the newly installed Alexa skill in the Alexa app.</p><p>You: “Alexa, open myTunes”</p><p>Alexa: “Welcome to the myTunes app. How can I help?”</p><p>You: “Play track from Album Songs of Innocence”</p><p>Alexa: “Playing track The Miracle from Album Songs of Innocence …”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96887a2c7068" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Alexa, Meet ServiceNow”]]></title>
            <link>https://medium.com/@sanjayraina/alexa-meet-servicenow-29a9141332d9?source=rss-53fea6a84fa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/29a9141332d9</guid>
            <category><![CDATA[chatops]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[servicenow]]></category>
            <category><![CDATA[alexa-skills]]></category>
            <dc:creator><![CDATA[Sanjay Raina]]></dc:creator>
            <pubDate>Thu, 03 Jan 2019 18:35:41 GMT</pubDate>
            <atom:updated>2019-01-13T17:44:22.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*ztU8Kew7IgbkamrKT8kBTQ.jpeg" /></figure><p>Smart speakers have seen phenomenal growth over the last few years and devices such as Amazon Echo and Google Home have been one of the top gift items this holiday season. This year alone, Amazon has shipped over 20 million Echo devices. Part of the reason for Amazon’s success in this space is its extensible Alexa voice assistant and the associated Skills. There are now over 70,000 skills available worldwide. In addition to adding new functionality to the voice assistant, Alexa Skills enable the devices to call external services such as ride-sharing and music streaming apps. This enables voice interface to be added to virtually any application. In this article we will look at adding voice user interface capability to the ServiceNow ITSM application.</p><p>ServiceNow is the leading IT Service Management and IT Operations Management platform that provides capabilities for enterprises to manage their IT infrastructure and services. It is an extensible SaaS platform, integrating easily with third party applications through open interfaces, offering great potential in building the latest AIOps, ChatOps and voice-enabled applications for enterprise management.</p><p>We will build a simple skill that queries a ServiceNow instance for most recent tickets and plays them back. The figure below shows the overview of the skill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*Lp7t8h6hTqoQYBk_Q_m6pQ.png" /></figure><p>When the skill is invoked, Alexa triggers an AWS Lambda function to process the command or Intent. The Lambda function in turn calls the REST API to query the appropriate ServiceNow table and retrieves the relevant records. The records returned are then played back through the Echo device. The skill uses Account Linking to authenticate the skill user with ServiceNow.</p><h3>Prerequisites</h3><p>We need to perform some preparatory work in order to get started.</p><h4>Node.js and npm</h4><p>We will use Node.js to implement our Lambda function. So we need to install Node.js and npm to build the dependencies locally before deploying the code to AWS Lambda. You will need Node.js version 6.10 or later.</p><h4>AWS account</h4><p>This will be needed to run the Lambda function. If you do not have an AWS account, you can register for a free-tier account at <a href="https://aws.amazon.com/free.">https://aws.amazon.com/free</a>. <strong><em>CAUTION</em></strong><em>: You may incur charges if you are not using the free-tier.</em></p><h4>IAM user and policy</h4><p>In the AWS console create an IAM user and attach the following policy to it.</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;iam:CreateRole&quot;,<br>        &quot;iam:GetRole&quot;,<br>        &quot;iam:AttachRolePolicy&quot;,<br>        &quot;iam:PassRole&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;arn:aws:iam::*:role/ask-*&quot;<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;lambda:AddPermission&quot;,<br>        &quot;lambda:CreateFunction&quot;,<br>        &quot;lambda:GetFunction&quot;,<br>        &quot;lambda:UpdateFunctionCode&quot;,<br>        &quot;lambda:ListFunctions&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;arn:aws:lambda:*:*:function:alexa-servicenow&quot;<br>    }<br>  ]<br>}</pre><p>Make a note of the user’s access key and secret key. You will need these to configure the AWS CLI environment further on.</p><h4>Amazon developer account</h4><p>An Amazon developer account is required to create and configure skills. You can create one at <a href="https://developer.amazon.com./">https://developer.amazon.com</a>. We will use Alexa Skills Kit SDK v2.</p><h4>AWS CLI</h4><p>The AWS CLI is used during skill deployment by the ASK CLI. Install it as follows.</p><pre>$ pip install awscli --upgrade --user</pre><p>More details can be found at <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html</a>.</p><p>Configure the CLI as follows.</p><pre>$ aws configure<br>AWS Access Key ID [None]: &lt;Your_Access_Key&gt;<br>AWS Secret Access Key [None]: &lt;Your_Secret_Access_Key&gt;<br>Default region name [None]: eu-west-2<br>Default output format [None]: json</pre><h4>ASK CLI</h4><p>Although skills can be developed using the console, we will use the command line interface. ASK CLI is a Node.js package, installed as follows.</p><pre>$ npm install -g ask-cli</pre><p>Configure the CLI tool as follows.</p><pre>$ ask init<br>? <strong>Please create a new profile or overwrite the existing profile.<br></strong>Create new profile<br>? <strong>Please type in your new profile name:<br></strong>default<br>-------------------- Initialize CLI --------------------<br>Setting up ask profile: [default]<br>? <strong>Please choose one from the following AWS profiles for skill&#39;s Lambda function deployment.<br></strong>alexa-dev</pre><p>This will open a browser window and prompt you to log into your Amazon account.</p><h4>ServiceNow developer instance</h4><p>You can sign up for a developer instance at <a href="https://developer.servicenow.com/">https://developer.servicenow.com</a>. You will receive a personal sandbox environment of the form devNNNNN.service-now.com.</p><h4>Alexa companion app</h4><p>This is required to authenticate the skill user with ServiceNow, once Account Linking has been configured. Install the app on your phone from the Android or Apple store.</p><h4>Download code</h4><p>The code for the skill is available at <a href="https://github.com/sanjayraina/alexa-servicenow">https://github.com/sanjayraina/alexa-servicenow</a>. It contains the following files.</p><ul><li>.ask/config — deployment configuration</li><li>skill.json — the skill configuration</li><li>models/en-GB.json — the interaction model</li><li>lambda/custom/index.js — core lambda function</li><li>lambda/custom/constants.js — constants used in the code</li><li>lambda/custom/package.json — package dependencies</li></ul><h3>Interaction Model</h3><p>The definition of the interaction model is contained in skill.json and en-GB.json. Alexa voice interactions work by decomposing speech into words and phrases that are sent to Alexa Voice Service (AVS) and an AWS Lambda function to be processed. The interaction schema is described in models/en-GB.json.</p><h4>Invocation</h4><p>Invocations are used to launch the skill. Our skill uses the following invocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*FSK1Tn0R0w05EAQ25px6yA.png" /></figure><p>Wake word initiates a new session. Launch “opens’ the skill and the invocation name identifies the skill.</p><h4>Utterance</h4><p>Utterances define the dialog in the skill and include phrases that get mapped onto Intents. Utterances can also include Slots that can take “variable” values. In our skill, sample utterances are of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*DSbVXRqbT7ST6AeYknyxQA.png" /></figure><h4>Intents</h4><p>Intents define the goal or action that is to be accomplished by a voice exchange. There is only one custom Intent in our skill.</p><pre>{<br>  &quot;name&quot;: &quot;ServiceNowIntent&quot;,<br>  &quot;slots&quot;: [{<br>    &quot;name&quot;: &quot;Tickets&quot;,<br>    &quot;type&quot;: &quot;TICKETS&quot;<br>  }],<br>  &quot;samples&quot;: [&quot;Read out the recent {Tickets}&quot;]<br>}</pre><p>It has one slot called Tickets, that can take values such as Incidents, Changes, Problems etc.</p><h3>Lambda Function</h3><p>The Lambda function contains handlers to process the launch request and intents.</p><h4>Launch Request Handler</h4><p>The handler simply plays a greeting and awaits a response to trigger an intent. It also retrieves the access token from the request, to be used later in the Intent handler. The access token is provided by ServiceNow on authentication, once Account Linking has been enabled.</p><pre>const speechText = &#39;Welcome to the ServiceNow skill, how can I help?&#39;;</pre><pre>accessToken = handlerInput.requestEnvelope.session.user.accessToken;</pre><pre>return handlerInput.responseBuilder<br>  .speak(speechText)<br>  .reprompt(speechText)<br>  .getResponse();</pre><h4>Intent Handler</h4><p>The handler contains code to determine the slot value and then to make the appropriate REST API request to the ServiceNow instance.</p><p>The slot value is obtained from the request envelope to determine which table in the ServiceNow instance to retrieve the records from.</p><pre>const filledSlots = handlerInput.requestEnvelope.request.intent.slots;</pre><pre>const ticketType = filledSlots.Tickets.value;</pre><p>Next, the handler makes a GET request as follows.</p><pre>const options = {<br>  hostname: snowInstance,<br>  port: 443,<br>  path: &#39;/api/now/table/&#39; + recType + <br>        &#39;sysparm_query=ORDERBYDESCsys_updated_on&amp;sysparm_limit=5&#39;,<br>  method: &#39;GET&#39;,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    Authorization: hdrAuth<br>  }<br>};<br>const request = https.request(options, (response) =&gt; {<br>...</pre><p>The returned records are then assembled into speech text as follows.</p><pre>let speechText =  &quot;Here are the 5 most recent &quot; + ticketType + &quot;: &quot;;<br>for (let i = 0; i &lt; 5; i++) {<br>  var rec_number = i + 1;<br>  speechText += &quot;Record &quot; + (i+1) + &#39;&lt;break time=&quot;.5s&quot;/&gt;&#39; <br>                 + records.result[i].short_description + &quot;. &quot;;<br>}<br>speechText += &#39;&lt;break time=&quot;.5s&quot;/&gt;&#39; + &quot;End of &quot; + ticketType + &quot;.&quot;;</pre><p>Notice the extra pauses added with the “break time” markup.</p><h3>Account Linking with ServiceNow</h3><p>External client applications that access ServiceNow need to be authenticated. To achieve this, an OAuth endpoint needs to be created in ServiceNow so that it can generate a token on authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxpbXYaXbvcnqpCWxFV9kw.png" /></figure><p>The above identity is used when setting up Account Linking to enable the Alexa Skills user to authenticate and connect to ServiceNow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ipYwbKDibYobgVUuG8e5Q.png" /></figure><h3>Skill Deployment</h3><p>Ensure that all the prerequisite steps have been completed. Perform the following steps to deploy the code.</p><ul><li>Clone or download code from Github repository:</li></ul><pre>$ git clone https://github.com/sanjayraina/alexa-servicenow.git<br>$ cd alexa-servicenow</pre><ul><li>Amend constants.js with the name of your instance:</li></ul><pre>exports.servicenow = {<br>  instance: &#39;devNNNNN.service-now.com&#39;,<br>};</pre><ul><li>Download the skill dependencies:</li></ul><pre>$ cd lambda/custom; npm install</pre><ul><li>Deploy the skill and lambda function with ASK CLI:</li></ul><pre>$ ask deploy</pre><p>Once the code is deployed, the next step is to setup Account Linking and authentication with ServiceNow.</p><p>Create OAuth API Endpoint in ServiceNow.</p><ul><li>Log in to your ServiceNow developer instance at devNNNNN.service-now.com. Navigate to System OAuth →Application Registry.</li><li>Click on New to create a new Endpoint and fill out the fields as follows:</li><li>Name: Alexa Skill Test</li><li>Redirect URL: <a href="https://layla.amazon.com/api/skill/link/M26D1D2CM95YM6">https://layla.amazon.com/api/skill/link/M26D1D2CM95YM6</a></li><li>Client Id will be filled out automatically and Client Secret will be generated automatically once the form is saved.</li></ul><p>Now we need to link the Amazon developer account with ServiceNow using the Endpoint and credentials created above.</p><ul><li>Head over to your Amazon developer account at developer.amazon.com and log in.</li><li>Navigate to your newly deployed skill and click on Account Linking on the left to open the Account Linking form.</li><li>Turn on account linking using the first toggle button at the top and fill out the details from your ServiceNow OAuth Endpoint.</li><li>Select an authorization grant type: Auth Code Grant</li><li>Authorization URI: https://devNNNNN.service-now.com/oauth_auth.do</li><li>Access Token URI: https://devNNNNN.service-now.com/oauth_token.do</li><li>Client Id: &lt;As generated by ServiceNow above&gt;</li><li>Client Secret: &lt;As generated by ServiceNow above&gt;</li><li>Save the form.</li></ul><p>Finally, open the Alexa app on the phone and authenticate the linked account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*VB75cuEqukNRm3c9rURqeQ.png" /></figure><p>Enter your ServiceNow credentials when prompted to login. A message will appear asking your permission to link the accounts. Press “Allow” to proceed and complete the Account Linking set up.</p><p>Deployment and setup is now complete.</p><h3>Take it for a spin</h3><p>Now that we have the skill deployed, let’s try it out.</p><p>Make sure that the Skill has been linked with ServiceNow using the companion phone app. You will need to login with your ServiceNow user credentials.</p><p>You should now be able to initial a dialog with your Echo device.</p><p>You: “Alexa, open ServiceNow”</p><p>Alexa: “Welcome to the ServiceNow skill. How can I help?”</p><p>You: “Tell me the recent incidents”</p><p>Alexa: “Here are the 5 most recent incidents…”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29a9141332d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>