### Create Sandbox Environment and Start Development Server (NPM/AMPLIFY) Source: https://github.com/aws-samples/agents4energy/blob/main/README.md These commands facilitate setting up a personal development sandbox and starting a local development server. The 'ampx sandbox' command initializes the sandbox, while 'npm run dev' starts a server that hot-reloads both frontend and backend changes, accessible at localhost:3000. ```bash npx ampx sandbox npm run dev ``` -------------------------------- ### Install Dependencies and Authenticate ECR (NPM) Source: https://github.com/aws-samples/agents4energy/blob/main/README.md This snippet outlines the steps to install project dependencies using npm and authenticate with the AWS Elastic Container Registry (ECR) to pull necessary Lambda build images. It's a prerequisite for local development and deployment. ```bash npm install npm run ecrAuth ``` -------------------------------- ### Example JSON for Table Definition (Athena Federated Query) Source: https://github.com/aws-samples/agents4energy/blob/main/README.md This JSON object provides an example structure for defining a table when adding new data sources via Amazon Athena Federated Query. It specifies the data source, database, table name, and the table's schema definition, enabling the agent to query this new data. ```json { "dataSource": "AwsDataCatalog", "database": "production_db_171", "tableName": "crawler_pricing", "tableDefinition": "\"date\"\tvarchar\n\"wti_price\"\tdouble\n\"brent_price\"\tdouble\n\"volume\"\tbigint" } ``` -------------------------------- ### Stable Stability Banner Markdown Source: https://github.com/aws-samples/agents4energy/blob/main/CONTRIBUTING.md Markdown code snippet for a 'Stable' stability banner. It includes a shield badge and descriptive text indicating the example is stable and has no infrastructure prerequisites. ```markdown --- ![Stability: Stable](https://img.shields.io/badge/stability-Stable-success.svg?style=for-the-badge) > **This is a stable example. It should successfully build out of the box** > > This example is built on Construct Libraries marked "Stable" and does not have any infrastructure prerequisites to build. --- ``` -------------------------------- ### Developer Preview Stability Banner Markdown Source: https://github.com/aws-samples/agents4energy/blob/main/CONTRIBUTING.md Markdown code snippet for a 'Developer Preview' stability banner. It features a distinct badge and text highlighting the experimental nature of the example, potential build issues, and the need for infrastructure prerequisites. ```markdown --- ![Stability: Developer Preview](https://img.shields.io/badge/stability-Developer--Preview-important.svg?style=for-the-badge) > **This is an experimental example. It may not build out of the box** > > This example is built on Construct Libraries marked "Developer Preview" and may not be updated for latest breaking changes. > > It may additionally requires infrastructure prerequisites that must be created before successful build. > > If build is unsuccessful, please create an [issue](https://github.com/aws-samples/aws-cdk-examples/issues/new) so that we may debug the problem --- ``` -------------------------------- ### Lambda Function: Get Table Definitions Tool (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt This tool, defined in `toolBox.ts`, retrieves database table definitions from a Bedrock Knowledge Base. It takes `tableFeatures` as input to query the knowledge base and returns structured table definitions along with their relevance scores. This is crucial for text-to-SQL generation. ```typescript // Tool definition in toolBox.ts import { tool } from "@langchain/core/tools"; import { z } from "zod"; const getTableDefinitionsSchema = z.object({ tableFeatures: z.string().describe("Key words and likely SQL column names") }); export const getTableDefinitionsTool = tool( async ({ tableFeatures }) => { const relevantTables = await queryKnowledgeBase({ knowledgeBaseId: env.AWS_KNOWLEDGE_BASE_ID, query: tableFeatures }); const tableDefinitions = relevantTables.map((result) => ({ ...JSON.parse(result?.content?.text || ""), score: result?.score })); return { messageContentType: 'tool_json', tableDefinitions: tableDefinitions }; }, { name: "getTableDefinitionsTool", description: "Always call this tool before executing SQL. Retrieves table definitions.", schema: getTableDefinitionsSchema } ); // Agent automatically invokes this tool when user asks data questions ``` -------------------------------- ### Initialize CDK App Java Source: https://github.com/aws-samples/agents4energy/blob/main/CONTRIBUTING.md Command to initialize a new AWS CDK application project in Java. This command generates the essential file structure and project configuration for a CDK application using Java. ```bash npx cdk init app --language java ``` -------------------------------- ### Initialize CDK App TypeScript Source: https://github.com/aws-samples/agents4energy/blob/main/CONTRIBUTING.md Command to initialize a new AWS CDK application project in TypeScript. This command generates the basic file structure and configuration for a CDK application. ```bash npx cdk init app --language typescript ``` -------------------------------- ### CDK Construct: Maintenance Agent Builder (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt This construct, located in `amplify/agents/maintenance/maintenanceAgent.ts`, deploys a Bedrock Agent configured with an Aurora PostgreSQL CMMS database and a text-to-SQL action group. It sets up the necessary AWS resources including the database, the agent, a knowledge base, and a Lambda function for populating sample data. ```typescript // amplify/agents/maintenance/maintenanceAgent.ts import { maintenanceAgentBuilder } from './agents/maintenance/maintenanceAgent'; const maintenanceAgentStack = backend.createStack('maintAgentStack'); const { defaultDatabaseName, maintenanceAgent, maintenanceAgentAlias } = maintenanceAgentBuilder(maintenanceAgentStack, { vpc: vpc, s3Deployment: uploadToS3Deployment, s3Bucket: backend.storage.resources.bucket }); // Creates: // - Aurora Serverless v2 PostgreSQL cluster (CMMS database) // - 8 tables: equipment, maintenance, equipmenttypes, mainttypes, // locations, locationtypes, businessunits, statustypes // - Bedrock Agent with text-to-SQL action group // - Bedrock Knowledge Base with shift handover reports // - Lambda prep function to populate sample data // Query example: "Show me all pumps that failed in the last 30 days" ``` -------------------------------- ### GraphQL Subscription: recieveResponseStreamChunk Source: https://context7.com/aws-samples/agents4energy/llms.txt Receives real-time token-level streaming from agent responses as they are generated for a specific chat session. ```APIDOC ## POST /graphql ### Description Receives real-time token-level streaming from agent responses as they are generated for a specific chat session. ### Method POST ### Endpoint /graphql ### Parameters #### Request Body - **operationName** (String) - Optional - The name of the operation to perform. - **query** (String) - Required - The GraphQL query string for the subscription. - **variables** (Object) - Optional - Variables for the subscription. - **chatSessionId** (String) - Required - The ID of the chat session to subscribe to. ### Request Example ```json { "query": "subscription RecieveResponseStreamChunk($chatSessionId: String!) {\n recieveResponseStreamChunk(chatSessionId: $chatSessionId) {\n chunk\n index\n }\n}\n", "variables": { "chatSessionId": "session-abc-123" } } ``` ### Response #### Success Response (200) - **data** (Object) - The response data from the server. - **recieveResponseStreamChunk** (Object) - A chunk of the streaming response. - **chunk** (String) - The text chunk or token. - **index** (Int) - The sequence number of the chunk. #### Response Example ```json { "data": { "recieveResponseStreamChunk": { "chunk": "The production agent is analyzing", "index": 1 } } } ``` ``` -------------------------------- ### Configure Allowed Email Suffixes for Sign-up (AWS Lambda Environment Variables) Source: https://github.com/aws-samples/agents4energy/blob/main/README.md This describes how to configure environment variables for a pre-signup Lambda function in AWS Amplify. The 'ALLOWED_EMAIL_SUFFIXES' variable controls which email domains are permitted during user sign-up. An empty element in the comma-separated list allows any email address. ```json { "ALLOWED_EMAIL_SUFFIXES": "@example.com,@anotherdomain.org" } ``` -------------------------------- ### GraphQL Query: invokeProductionAgent Source: https://context7.com/aws-samples/agents4energy/llms.txt Invokes the production agent to analyze oil & gas production data, execute SQL queries against structured datasets, and retrieve petroleum engineering knowledge. Response streaming via GraphQL subscription. ```APIDOC ## POST /graphql ### Description Invokes the production agent to analyze oil & gas production data, execute SQL queries against structured datasets, and retrieve petroleum engineering knowledge. ### Method POST ### Endpoint /graphql ### Parameters #### Request Body - **operationName** (String) - Optional - The name of the operation to perform. - **query** (String) - Required - The GraphQL query string. - **variables** (Object) - Optional - Variables for the query. - **lastMessageText** (String) - Required - The last message text for the agent. - **chatSessionId** (String) - Required - The ID of the chat session. - **usePreviousMessageContext** (Boolean) - Optional - Whether to use previous message context. - **messageOwnerIdentity** (String) - Required - The identity of the message owner. - **doNotSendResponseComplete** (Boolean) - Optional - Flag to indicate if response completion should not be sent. ### Request Example ```json { "query": "mutation InvokeProductionAgent($lastMessageText: String!, $chatSessionId: String!, $usePreviousMessageContext: Boolean, $messageOwnerIdentity: String!, $doNotSendResponseComplete: Boolean) {\n invokeProductionAgent(lastMessageText: $lastMessageText, chatSessionId: $chatSessionId, usePreviousMessageContext: $usePreviousMessageContext, messageOwnerIdentity: $messageOwnerIdentity, doNotSendResponseComplete: $doNotSendResponseComplete)\n}\n", "variables": { "lastMessageText": "Show me total oil production for well API 42-123-12345 over the last 12 months", "chatSessionId": "session-abc-123", "usePreviousMessageContext": true, "messageOwnerIdentity": "user-sub-id", "doNotSendResponseComplete": false } } ``` ### Response #### Success Response (200) - **data** (Object) - The response data from the server. - **invokeProductionAgent** (String) - The response from the production agent. #### Response Example ```json { "data": { "invokeProductionAgent": "The agent will query the knowledge base, generate and execute an Athena SQL query, and return structured results with visualization data." } } ``` ``` -------------------------------- ### React ChatBox Component for Real-time Agent Messages (TypeScript/TSX) Source: https://context7.com/aws-samples/agents4energy/llms.txt A React component that displays agent messages, including real-time streaming responses and tool outputs. It subscribes to message updates and streaming chunks via GraphQL subscriptions using Amplify. ```tsx // src/components/ChatBox.tsx import { Schema } from '@/../amplify/data/resource'; import { amplifyClient } from '@/utils/amplify-utils'; const ChatBox: React.FC = ({ chatSession }) => { const [messages, setMessages] = useState([]); useEffect(() => { // Subscribe to messages const sub = amplifyClient.models.ChatMessage.observeQuery({ filter: { chatSessionId: { eq: chatSession.id } } }).subscribe({ next: ({ items }) => { const sorted = combineAndSortMessages(messages, items); setMessages(sorted); } }); // Subscribe to streaming chunks const streamSub = client.subscriptions.recieveResponseStreamChunk({ chatSessionId: chatSession.id }).subscribe({ next: (data) => setCharacterStreamMessage(prev => ({ ...prev, content: prev.content + data.chunk })) }); return () => { sub.unsubscribe(); streamSub.unsubscribe(); }; }, [chatSession]); return ; }; ``` -------------------------------- ### Receive Response Stream Chunk Subscription (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt Subscribes to real-time token-level streaming of agent responses using AWS Amplify's GraphQL subscriptions. This allows for progressive UI updates as the agent generates its output. The subscription receives chunks of data along with their sequence index for ordered processing. It includes error handling and a method to unsubscribe. ```typescript const client = generateClient(); // Subscribe to streaming chunks for a chat session const subscription = client.subscriptions.recieveResponseStreamChunk({ chatSessionId: "session-abc-123" }).subscribe({ next: (data) => { const chunk = data.chunk; // Token or partial response const index = data.index; // Sequence number console.log(`Chunk ${index}: ${chunk}`); // Update UI with streaming text }, error: (err) => console.error('Subscription error:', err) }); // Clean up subscription.unsubscribe(); ``` -------------------------------- ### Configure S3 Storage Access for Agents (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt Defines authenticated access to S3 prefixes for agent-specific document storage. It uses Amplify's defineStorage to specify read access for authenticated users on different agent prefixes. Frontend applications can then use 'aws-amplify/storage' to list and retrieve files. ```typescript // amplify/storage/resource.ts import { defineStorage } from '@aws-amplify/backend'; export const storage = defineStorage({ name: 'fileDrive', access: (allow) => ({ 'production-agent/*': [allow.authenticated.to(['read'])], 'maintenance-agent/*': [allow.authenticated.to(['read'])], 'petrophysics-agent/*': [allow.authenticated.to(['read'])], 'regulatory-agent/*': [allow.authenticated.to(['read'])] }) }); // Frontend usage: import { list, getUrl } from 'aws-amplify/storage'; const files = await list({ prefix: 'production-agent/' }); const url = await getUrl({ key: 'production-agent/well-logs/log-123.pdf' }); ``` -------------------------------- ### LangGraph Agent Orchestration Lambda Function (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt An AWS Lambda function that orchestrates multi-step planning and execution workflows using LangGraph and Bedrock. It creates a React agent, defines its tools, and streams events as the agent processes a user's request, facilitating complex task decomposition and execution. ```typescript // amplify/functions/planAndExecuteAgent/index.ts import { createReactAgent } from "@langchain/langgraph/prebuilt"; import { ChatBedrockConverse } from "@langchain/aws"; export const handler = async (event) => { const model = new ChatBedrockConverse({ model: process.env.MODEL_ID, temperature: 0 }); const agent = createReactAgent({ llm: model, tools: [/* planning and execution tools */] }); // Agent breaks down complex requests into steps: // 1. Create plan from user goal // 2. Execute steps sequentially // 3. Aggregate results // 4. Return comprehensive answer const stream = agent.streamEvents( { messages: [new HumanMessage(event.arguments.lastMessageText)] }, { version: "v2" } ); for await (const event of stream) { if (event.event === "on_chat_model_stream") { // Stream to client via AppSync } } }; // Example: "Analyze production trends and recommend optimization strategies" // Plan: 1) Get production data 2) Calculate trends 3) Query best practices 4) Generate recommendations ``` -------------------------------- ### Invoke Bedrock Agent (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt Invokes a Bedrock-managed agent (Maintenance, Regulatory, or Petrophysics) using AWS Amplify's data generation client for GraphQL queries. It supports session management and trace streaming. The agent queries an Aurora PostgreSQL CMMS database with text-to-SQL. The response includes the completion and an orchestration trace detailing the agent's rationale, tool calls, and intermediate steps. ```typescript import { generateClient } from 'aws-amplify/data'; import type { Schema } from '@/../amplify/data/resource'; const client = generateClient(); // Invoke maintenance agent for CMMS queries const result = await client.queries.invokeBedrockAgent({ prompt: "What equipment needs preventive maintenance this month at Eagle Ford facility?", agentId: "MAINTENANCE_AGENT_ID", agentAliasId: "AGENT_ALIAS_ID", chatSessionId: "session-xyz-789" }); // Returns: { completion: string, orchestrationTrace: string } // Agent queries Aurora PostgreSQL CMMS database with text-to-SQL // Trace includes rationale, tool calls, and intermediate steps ``` -------------------------------- ### GraphQL Query: invokeBedrockAgent Source: https://context7.com/aws-samples/agents4energy/llms.txt Invokes a Bedrock-managed agent (Maintenance, Regulatory, or Petrophysics) with session management and trace streaming. The agent queries Aurora PostgreSQL CMMS database with text-to-SQL. ```APIDOC ## POST /graphql ### Description Invokes a Bedrock-managed agent (Maintenance, Regulatory, or Petrophysics) with session management and trace streaming. The agent queries Aurora PostgreSQL CMMS database with text-to-SQL. ### Method POST ### Endpoint /graphql ### Parameters #### Request Body - **operationName** (String) - Optional - The name of the operation to perform. - **query** (String) - Required - The GraphQL query string. - **variables** (Object) - Optional - Variables for the query. - **prompt** (String) - Required - The prompt for the Bedrock agent. - **agentId** (String) - Required - The ID of the Bedrock agent. - **agentAliasId** (String) - Required - The alias ID of the Bedrock agent. - **chatSessionId** (String) - Required - The ID of the chat session. ### Request Example ```json { "query": "mutation InvokeBedrockAgent($prompt: String!, $agentId: String!, $agentAliasId: String!, $chatSessionId: String!) {\n invokeBedrockAgent(prompt: $prompt, agentId: $agentId, agentAliasId: $agentAliasId, chatSessionId: $chatSessionId)\n}\n", "variables": { "prompt": "What equipment needs preventive maintenance this month at Eagle Ford facility?", "agentId": "MAINTENANCE_AGENT_ID", "agentAliasId": "AGENT_ALIAS_ID", "chatSessionId": "session-xyz-789" } } ``` ### Response #### Success Response (200) - **data** (Object) - The response data from the server. - **invokeBedrockAgent** (Object) - The response from the Bedrock agent. - **completion** (String) - The agent's completion text. - **orchestrationTrace** (String) - The orchestration trace, including rationale, tool calls, and intermediate steps. #### Response Example ```json { "data": { "invokeBedrockAgent": { "completion": "Equipment requiring preventive maintenance this month includes Pump X and Valve Y.", "orchestrationTrace": "Agent identified the need to query the CMMS database for maintenance schedules..." } } } ``` ``` -------------------------------- ### Invoke Production Agent (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt Invokes the production agent to analyze oil & gas data, execute SQL queries, and retrieve knowledge. It uses AWS Amplify's data generation client for GraphQL queries. The agent queries a knowledge base, generates an Athena SQL query, and returns structured results with visualization data. Responses are streamed via GraphQL subscription. ```typescript import { generateClient } from 'aws-amplify/data'; import type { Schema } from '@/../amplify/data/resource'; const client = generateClient(); const response = await client.queries.invokeProductionAgent({ lastMessageText: "Show me total oil production for well API 42-123-12345 over the last 12 months", chatSessionId: "session-abc-123", usePreviousMessageContext: true, messageOwnerIdentity: "user-sub-id", doNotSendResponseComplete: false }); // The agent will: // 1. Query knowledge base for table definitions // 2. Generate and execute Athena SQL query // 3. Return structured results with visualization data // Response streaming via GraphQL subscription ``` -------------------------------- ### GraphQL Query: invokeBedrockWithStructuredOutput Source: https://context7.com/aws-samples/agents4energy/llms.txt Extracts structured data from chat messages using Claude with JSON schema validation. Returns a JSON string matching the specified schema. ```APIDOC ## POST /graphql ### Description Extracts structured data from chat messages using Claude with JSON schema validation. Returns a JSON string matching the specified schema. ### Method POST ### Endpoint /graphql ### Parameters #### Request Body - **operationName** (String) - Optional - The name of the operation to perform. - **query** (String) - Required - The GraphQL query string. - **variables** (Object) - Optional - Variables for the query. - **lastMessageText** (String) - Required - The last message text to process. - **usePastMessages** (Boolean) - Optional - Whether to use past messages for context. - **outputStructure** (String) - Required - A JSON string representing the desired output schema. - **chatSessionId** (String) - Required - The ID of the chat session. ### Request Example ```json { "query": "mutation InvokeBedrockWithStructuredOutput($lastMessageText: String!, $usePastMessages: Boolean, $outputStructure: String!, $chatSessionId: String!) {\n invokeBedrockWithStructuredOutput(lastMessageText: $lastMessageText, usePastMessages: $usePastMessages, outputStructure: $outputStructure, chatSessionId: $chatSessionId)\n}\n", "variables": { "lastMessageText": "Well 42-123-45678 produced 150 barrels per day", "usePastMessages": false, "outputStructure": "{\"type\": \"object\", \"properties\": {\"wellAPI\": { \"type\": \"string\" }, \"productionRate\": { \"type\": \"number\" }, \"productionUnit\": { \"type\": \"string\" }}, \"required\": [\"wellAPI\", \"productionRate\"]}", "chatSessionId": "session-123" } } ``` ### Response #### Success Response (200) - **data** (Object) - The response data from the server. - **invokeBedrockWithStructuredOutput** (String) - A JSON string containing the extracted structured data. #### Response Example ```json { "data": { "invokeBedrockWithStructuredOutput": "{\"wellAPI\": \"42-123-45678\", \"productionRate\": 150, \"productionUnit\": \"bbls/day\"}" } } ``` ``` -------------------------------- ### Lambda Function: Execute SQL Query Tool (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt This tool executes Trino SQL queries against Athena workgroups and automatically transforms the results. It takes a SQL query as input, initiates execution in Athena, waits for completion, retrieves raw results, and then transforms them into a usable format. This is typically invoked by an agent for data analysis. ```typescript // Example SQL query tool invocation by agent const executeSQLQuerySchema = z.object({ query: z.string().describe("Trino SQL query with dataSource.database.table format") }); export const executeSQLQueryTool = tool( async ({ query }) => { // Start Athena query execution const queryExecutionId = await startQueryExecution({ query: query, workgroupName: env.ATHENA_WORKGROUP_NAME, databaseName: env.DATABASE_NAME }); // Wait for completion await waitForQueryToComplete(queryExecutionId); // Get and transform results const rawResults = await getQueryResults(queryExecutionId); const transformed = transformResultSet(rawResults); return { messageContentType: 'tool_table_trend', data: transformed }; }, { name: "executeSQLQueryTool", schema: executeSQLQuerySchema } ); // Agent generates SQL like: // SELECT DATE_TRUNC('month', CAST("firstDayOfMonth" AS DATE)) AS month, // SUM("oil(bbls)") AS total_oil // FROM "AwsDataCatalog"."production_db"."monthly_production" // WHERE "well api" = '42-123-45678' // GROUP BY DATE_TRUNC('month', CAST("firstDayOfMonth" AS DATE)) ``` -------------------------------- ### Lambda Function: Convert PDF to YAML (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt This Lambda function, triggered by S3 uploads to `production-agent/pdf-files/`, processes PDF documents using Amazon Textract to extract text. It then converts this extracted text into a YAML format, which is subsequently uploaded to `production-agent/yaml-files/` for knowledge base ingestion. The function handles multiple S3 event records. ```typescript // Triggered by S3 upload to production-agent/pdf-files/ // amplify/functions/convertPdfToYaml/index.ts export const handler = async (event: S3Event) => { for (const record of event.Records) { const bucket = record.s3.bucket.name; const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, ' ')); // Extract text using Textract const textractClient = new TextractClient(); const response = await textractClient.send(new DetectDocumentTextCommand({ Document: { S3Object: { Bucket: bucket, Name: key }} })); // Convert to YAML const yamlContent = stringify({ fileName: key, content: extractedText, metadata: { processedAt: new Date().toISOString() } }); // Upload to knowledge base folder await s3Client.send(new PutObjectCommand({ Bucket: bucket, Key: key.replace('/pdf-files/', '/yaml-files/'), Body: yamlContent })); } }; // Sample upload: // aws s3 cp well-completion-report.pdf s3://bucket/production-agent/pdf-files/ // Automatically converted and indexed in knowledge base ``` -------------------------------- ### Invoke Bedrock with Structured Output (TypeScript) Source: https://context7.com/aws-samples/agents4energy/llms.txt Extracts structured data from chat messages using Amazon Bedrock's Claude model, enforcing JSON schema validation. This function is useful for parsing specific information from natural language inputs. It takes a message, a desired output structure defined by a JSON schema, and returns a JSON string that conforms to the schema. The output can be parsed into a JavaScript object. ```typescript const outputStructure = JSON.stringify({ type: "object", properties: { wellAPI: { type: "string" }, productionRate: { type: "number" }, productionUnit: { type: "string" } }, required: ["wellAPI", "productionRate"] }); const result = await client.queries.invokeBedrockWithStructuredOutput({ lastMessageText: "Well 42-123-45678 produced 150 barrels per day", usePastMessages: false, outputStructure: outputStructure, chatSessionId: "session-123" }); // Returns JSON string matching schema const parsed = JSON.parse(result); // { wellAPI: "42-123-45678", productionRate: 150, productionUnit: "bbls/day" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.