API Reference
Comprehensive reference for the Agentuity JavaScript SDK API
This section provides detailed documentation for the Agentuity JavaScript SDK API, including method signatures, parameters, return values, and example usage.
Table of Contents
Agent Lifecycle
The Agentuity SDK provides a structured way to define and handle agents. An agent consists of a handler function, with its configuration managed by the Agentuity CLI.
Agent Configuration
Agent configuration is managed by the Agentuity CLI and stored in the project configuration file. The AgentConfig
interface is used internally by the CLI and SDK:
interface AgentConfig {
/**
* the name of the agent
*/
name: string;
/**
* the description of the agent
*/
description?: string;
}
Agent Handler
The AgentHandler
type defines the handler function for an agent:
type AgentHandler = (
request: AgentRequest,
response: AgentResponse,
context: AgentContext
) => Promise<AgentResponseType>;
Parameters
request
: AnAgentRequest
object containing the request dataresponse
: AnAgentResponse
object for creating responsescontext
: AnAgentContext
object providing access to various capabilities
Return Value
The handler function should return a Promise that resolves to an AgentResponseType
object.
Example
import { AgentHandler } from '@agentuity/sdk';
// Agent handler function
const handler: AgentHandler = async (request, response, context) => {
try {
// Get the request data
const { name } = await request.data.json();
// Log the request
context.logger.info(`Received greeting request for ${name}`);
// Return a personalized greeting
return response.json({
message: `Hello, ${name}! Welcome to Agentuity.`
});
} catch (error) {
// Handle errors
context.logger.error('Error processing request', error);
return response.json({ error: 'Failed to process request' });
}
};
export default handler;
Storage APIs
The Agentuity SDK provides three storage APIs: Key-Value Storage, Vector Storage, and Object Storage.
Key-Value Storage
The Key-Value Storage API provides a simple way to store and retrieve data. It is accessed through the context.kv
object.
get
get(name: string, key: string): Promise<DataResult>
Retrieves a value from the key-value storage.
Parameters
name
: The name of the key-value storagekey
: The key to retrieve the value for
Return Value
Returns a Promise that resolves to a DataResult object. The DataResult has an exists
boolean property and a data
property containing the value if found.
Example
// Retrieve a value from key-value storage
const result = await context.kv.get('user-preferences', 'user-123');
if (result.exists) {
// Access data using the Data interface methods
const valueString = await result.data.text();
console.log(`User preferences: ${valueString}`);
} else {
console.log('User preferences not found');
}
set
set(name: string, key: string, value: ArrayBuffer | string | Json, ttl?: number): Promise<void>
Stores a value in the key-value storage.
Parameters
name
: The name of the key-value storagekey
: The key to store the value undervalue
: The value to store (can be an ArrayBuffer, string, or JSON object)ttl
(optional): Time-to-live in seconds (minimum 60 seconds)
Return Value
Returns a Promise that resolves when the value has been stored.
Example
// Store a string value
await context.kv.set('user-preferences', 'user-123', JSON.stringify({ theme: 'dark' }));
// Store a JSON value
await context.kv.set('user-preferences', 'user-123', { theme: 'dark' });
// Store a binary value
const binaryData = new Uint8Array([1, 2, 3, 4]).buffer;
await context.kv.set('user-data', 'user-123', binaryData);
// Store a value with TTL (expires after 1 hour)
await context.kv.set('session', 'user-123', 'active', 3600);
delete
delete(name: string, key: string): Promise<void>
Deletes a value from the key-value storage.
Parameters
name
: The name of the key-value storagekey
: The key to delete
Return Value
Returns a Promise that resolves when the value has been deleted.
Example
// Delete a value
await context.kv.delete('user-preferences', 'user-123');
Vector Storage
The Vector Storage API provides a way to store and search for data using vector embeddings. It is accessed through the context.vector
object.
upsert
upsert(name: string, ...documents: VectorUpsertParams[]): Promise<string[]>
Inserts or updates vectors in the vector storage.
Parameters
name
: The name of the vector storagedocuments
: One or more documents to upsert, each with either embeddings or text
Return Value
Returns a Promise that resolves to an array of string IDs for the upserted vectors.
Example
// Upsert documents with text
const ids = await context.vector.upsert(
'product-descriptions',
{ document: 'Ergonomic office chair with lumbar support', metadata: { category: 'furniture' } },
{ document: 'Wireless noise-cancelling headphones', metadata: { category: 'electronics' } }
);
// Upsert documents with embeddings
const ids2 = await context.vector.upsert(
'product-embeddings',
{ embeddings: [0.1, 0.2, 0.3, 0.4], metadata: { productId: '123' } },
{ embeddings: [0.5, 0.6, 0.7, 0.8], metadata: { productId: '456' } }
);
search
search(name: string, params: VectorSearchParams): Promise<VectorSearchResult[]>
Searches for vectors in the vector storage.
Parameters
name
: The name of the vector storageparams
: Search parameters object with the following properties:query
(string, required): The text query to search for. This will be converted to embeddings and used to find semantically similar documents.limit
(number, optional): Maximum number of search results to return. Must be a positive integer. If not specified, the server default will be used.similarity
(number, optional): Minimum similarity threshold for results (0.0-1.0). Only vectors with similarity scores greater than or equal to this value will be returned. 1.0 means exact match, 0.0 means no similarity requirement.metadata
(object, optional): Metadata filters to apply to the search. Only vectors whose metadata matches all specified key-value pairs will be included in results. Must be a valid JSON object.
Return Value
Returns a Promise that resolves to an array of search results, each containing an ID, key, metadata, and similarity score.
Examples
// Basic search with query only
const results = await context.vector.search('product-descriptions', {
query: 'comfortable office chair'
});
// Search with limit and similarity threshold
const results = await context.vector.search('product-descriptions', {
query: 'comfortable office chair',
limit: 5,
similarity: 0.7
});
// Search with metadata filtering
const results = await context.vector.search('product-descriptions', {
query: 'comfortable office chair',
limit: 10,
similarity: 0.6,
metadata: { category: 'furniture', inStock: true }
});
// Process search results
for (const result of results) {
console.log(`Product ID: ${result.id}, Similarity: ${result.similarity}`);
console.log(`Key: ${result.key}`);
console.log(`Metadata: ${JSON.stringify(result.metadata)}`);
}
delete
delete(name: string, ...keys: string[]): Promise<number>
Deletes one or more vectors from the vector storage.
Parameters
name
: The name of the vector storagekeys
: One or more keys of the vectors to delete
Return Value
Returns a Promise that resolves to the number of vectors that were deleted.
Examples
// Delete a single vector
const deletedCount = await context.vector.delete('product-descriptions', 'id1');
console.log(`Deleted ${deletedCount} vector(s)`); // Output: Deleted 1 vector(s)
// Delete multiple vectors in bulk (more efficient than individual calls)
const deletedCount = await context.vector.delete('product-descriptions', 'id1', 'id2', 'id3');
console.log(`Deleted ${deletedCount} vector(s)`); // Output: Deleted 3 vector(s)
// Delete with array spread
const keysToDelete = ['id1', 'id2', 'id3'];
const deletedCount = await context.vector.delete('product-descriptions', ...keysToDelete);
// Handle cases where some vectors might not exist
const deletedCount = await context.vector.delete('product-descriptions', 'existing-id', 'non-existent-id');
console.log(`Deleted ${deletedCount} vector(s)`); // Output: Deleted 1 vector(s)
Object Storage
The Object Storage API provides a way to store and retrieve objects (files, documents, media) with support for public URL generation. It is accessed through the context.objectstore
object.
get
get(bucket: string, key: string): Promise<DataResult>
Retrieves an object from the object storage.
Parameters
bucket
: The bucket to get the object fromkey
: The key of the object to get
Return Value
Returns a Promise that resolves to a DataResult object. The DataResult has an exists
boolean property and a data
property containing the object data if found.
Example
// Retrieve an object from object storage
const result = await context.objectstore.get('user-uploads', 'profile-123.jpg');
if (result.exists) {
// Access data using the Data interface methods
const imageData = await result.data.binary();
console.log(`Image size: ${imageData.byteLength} bytes`);
} else {
console.log('Image not found');
}
put
put(bucket: string, key: string, data: DataType, params?: ObjectStorePutParams): Promise<void>
Stores an object in the object storage.
Parameters
bucket
: The bucket to put the object intokey
: The key of the object to putdata
: The data to store (can be ArrayBuffer, string, or other DataType)params
(optional): Additional parameters for the object. The following properties map to canonical HTTP headers:contentType
(Content-Type),contentEncoding
(Content-Encoding),cacheControl
(Cache-Control),contentDisposition
(Content-Disposition), andcontentLanguage
(Content-Language). The optionalmetadata
property accepts a dictionary of arbitrary key-value pairs that will be stored as metadata with the object but not returned as part of HTTP results when the object is fetched. ThecontentType
parameter is optional - if not provided, the content type will be automatically detected based on the data type (e.g., objects will be set toapplication/json
). If the content type cannot be determined, it defaults toapplication/octet-stream
.
Return Value
Returns a Promise that resolves when the object has been stored.
Example
// Store a text file with explicit content type
await context.objectstore.put('documents', 'readme.txt', 'Hello, world!', {
contentType: 'text/plain'
});
// Store an object (content type auto-detected as application/json)
const userData = { name: 'John', age: 30 };
await context.objectstore.put('users', 'user-123.json', userData);
// Store a binary file
const imageData = new Uint8Array([/* image bytes */]).buffer;
await context.objectstore.put('images', 'photo.jpg', imageData, {
contentType: 'image/jpeg'
});
// Store without specifying content type (will default to application/octet-stream if unknown)
await context.objectstore.put('files', 'unknown-data', someData);
// Store with custom encoding and cache control
await context.objectstore.put('compressed', 'data.gz', compressedData, {
contentType: 'application/octet-stream',
contentEncoding: 'gzip',
cacheControl: 'max-age=3600'
});
// Store with metadata (not returned in HTTP results when fetched)
await context.objectstore.put('uploads', 'document.pdf', pdfData, {
contentType: 'application/pdf',
contentDisposition: 'attachment; filename="report.pdf"',
contentLanguage: 'en-US',
metadata: {
'user-id': '12345',
'upload-source': 'web-app',
'version': '2.0'
}
});
delete
delete(bucket: string, key: string): Promise<boolean>
Deletes an object from the object storage.
Parameters
bucket
: The bucket to delete the object fromkey
: The key of the object to delete
Return Value
Returns a Promise that resolves to a boolean indicating whether the object was deleted (true) or didn't exist (false).
Example
// Delete an object
const wasDeleted = await context.objectstore.delete('user-uploads', 'old-file.pdf');
if (wasDeleted) {
console.log('File deleted successfully');
} else {
console.log('File did not exist');
}
createPublicURL
createPublicURL(bucket: string, key: string, expiresDuration?: number): Promise<string>
Creates a time-limited public URL for accessing an object.
Parameters
bucket
: The bucket containing the objectkey
: The key of the objectexpiresDuration
(optional): Duration in milliseconds until the URL expires. Defaults to 1 hour (3600000ms) if not provided. Minimum value is 1 minute (60000ms) - values less than 1 minute will be set to 1 minute.
Return Value
Returns a Promise that resolves to a public URL string that can be used to access the object.
Example
// Create a public URL that expires in 1 hour
const publicUrl = await context.objectstore.createPublicURL(
'user-uploads',
'document.pdf',
3600000 // 1 hour in milliseconds
);
// Share the URL with users
console.log(`Download link: ${publicUrl}`);
// Create a URL with default expiration (1 hour)
const defaultUrl = await context.objectstore.createPublicURL('images', 'photo.jpg');
// Create a URL with minimum expiration (1 minute)
const shortUrl = await context.objectstore.createPublicURL(
'temp-files',
'quick-access.txt',
60000 // 1 minute in milliseconds
);
// Values less than 1 minute will be automatically set to 1 minute
const autoMinUrl = await context.objectstore.createPublicURL(
'temp-files',
'auto-min.txt',
30000 // Will be set to 60000ms (1 minute)
);
Agent Communication
The Agentuity SDK allows agents to communicate with each other through the context.getAgent()
method and agent redirection.
getAgent
getAgent(params: GetAgentRequestParams): Promise<RemoteAgent>
Retrieves a handle to a remote agent that can be invoked.
Parameters
params
: Parameters to identify the agent, either by ID or by name and project ID
Return Value
Returns a Promise that resolves to a RemoteAgent
object that can be used to invoke the agent.
Example
// Get an agent by ID
const agent = await context.getAgent({ id: 'agent-123' });
// Get an agent by name
const agent2 = await context.getAgent({
name: 'data-processing-agent',
projectId: 'project-456'
});
// Invoke the agent
const result = await agent.run({ data: 'process this' }, 'application/json');
Agent Handoff
The response.handoff()
method allows an agent to handoff the request to another agent.
handoff
handoff(agent: GetAgentRequestParams, payload?: Json | ArrayBuffer | string, contentType?: string, metadata?: Record<string, Json>): AgentRedirectResponse
Redirects the current request to another agent.
Parameters
agent
: Parameters to identify the target agentpayload
(optional): The payload to send to the target agentcontentType
(optional): The content type of the payloadmetadata
(optional): Additional metadata to include with the request
Return Value
Returns an AgentRedirectResponse
object.
Examples
// By ID
return response.handoff({
id: 'agent_9e478ebc1b6b58f921725e2f6f0025ab',
});
// By Name
return response.handoff({
name: 'my agent',
});
// By Name Scoped to a Project
return response.handoff({
name: 'my agent',
projectId: 'proj_fc9a68c544c486cebf982c9843b9032b',
});
// With payload and metadata
return response.handoff(
{ name: 'data-processing-agent' },
{ data: 'process this' },
'application/json',
{ source: 'web-agent' }
);
Response Types
The Agentuity SDK provides various methods for creating different types of responses through the response
object.
Stream Method
The stream
method allows you to stream responses back to the client, supporting both ReadableStream
and AsyncIterable
inputs with optional transformer functions for filtering and transforming stream data.
Method Signature
stream<T = unknown, U = T, M = unknown>(
stream: ReadableStream<T> | AsyncIterable<T>,
contentType?: string,
metadata?: M,
transformer?:
| ((item: T) => U | null | undefined)
| ((item: T) => Generator<U, void, unknown>)
): Promise<AgentResponseData>
Parameters
stream
: The stream to return - can be aReadableStream
orAsyncIterable
contentType
(optional): The content type of the stream. If not provided, the SDK will auto-detect based on the stream contentmetadata
(optional): Metadata to return as headerstransformer
(optional): Function or generator to transform/filter each stream item- Function transformer:
(item: T) => U | null | undefined
- returns single value or skips with null/undefined - Generator transformer:
(item: T) => Generator<U, void, unknown>
- yields transformed values
- Function transformer:
Auto-Conversion Features
The stream method automatically detects object streams and converts them to JSON newline format with the appropriate application/json
content type. This makes it seamless to work with structured data from AI SDKs.
Basic Usage
import type { AgentRequest, AgentResponse, AgentContext } from "@agentuity/sdk";
export default async function Agent(
req: AgentRequest,
resp: AgentResponse,
ctx: AgentContext,
) {
// Stream from another source
const dataStream = getDataStream();
return resp.stream(dataStream);
}
Vercel AI SDK Integration
The stream method works seamlessly with Vercel AI SDK's streamObject
for structured streaming:
import type { AgentRequest, AgentResponse, AgentContext } from "@agentuity/sdk";
import { openai } from '@ai-sdk/openai';
import { streamObject } from 'ai';
import { z } from 'zod';
export default async function Agent(
req: AgentRequest,
resp: AgentResponse,
ctx: AgentContext,
) {
const { elementStream } = streamObject({
model: openai('gpt-4o'),
output: 'array',
schema: z.object({
name: z.string(),
class: z
.string()
.describe('Character class, e.g. warrior, mage, or thief.'),
description: z.string(),
}),
prompt: 'Generate 3 hero descriptions for a fantasy role playing game.',
});
return resp.stream(elementStream);
}
Function Transformers
Use function transformers to filter and transform stream items:
export default async function Agent(
req: AgentRequest,
resp: AgentResponse,
ctx: AgentContext,
) {
const dataStream = getUserStream();
// Transform and filter items
const transformer = (user: any) => {
// Filter out inactive users (return null to skip)
if (!user.active) return null;
// Transform the user object
return {
id: user.id,
name: user.name.toUpperCase(),
timestamp: Date.now()
};
};
return resp.stream(dataStream, undefined, {}, transformer);
}
Generator Transformers
Use generator transformers for more complex transformations:
export default async function Agent(
req: AgentRequest,
resp: AgentResponse,
ctx: AgentContext,
) {
const batchStream = getBatchStream();
// Generator that can yield multiple items or filter
function* transformer(batch: any) {
if (batch.type === 'user_batch') {
// Yield multiple items from a batch
for (const user of batch.users) {
if (user.active) {
yield { ...user, processed: true };
}
}
} else if (batch.valid) {
// Yield single transformed item
yield { ...batch, enhanced: true };
}
// Return nothing to filter out invalid batches
}
return resp.stream(batchStream, undefined, {}, transformer);
}
Error Handling
Transformer errors are propagated when the stream is consumed:
export default async function Agent(
req: AgentRequest,
resp: AgentResponse,
ctx: AgentContext,
) {
const dataStream = getDataStream();
const transformer = (item: any) => {
// Validate item before transformation
if (!item || typeof item !== 'object') {
throw new Error(`Invalid item: ${JSON.stringify(item)}`);
}
return { ...item, validated: true };
};
return resp.stream(dataStream, undefined, {}, transformer);
}
Backward Compatibility
The transformer parameter is optional, so all existing stream usage continues to work unchanged:
// This continues to work exactly as before
return resp.stream(textStream);
return resp.stream(dataStream, 'application/json');
return resp.stream(binaryStream, 'application/octet-stream', { version: '1.0' });
JSON Responses
json(data: Json, metadata?: Record<string, Json>): AgentResponseType
Creates a JSON response.
Parameters
data
: The JSON data to include in the responsemetadata
(optional): Additional metadata to include with the response
Return Value
Returns an AgentResponseType
object with the JSON data.
Example
return response.json({
message: 'Success',
data: { id: 123, name: 'Example' }
});
Text Responses
text(data: string, metadata?: Record<string, Json>): AgentResponseType
Creates a text response.
Parameters
data
: The text to include in the responsemetadata
(optional): Additional metadata to include with the response
Return Value
Returns an AgentResponseType
object with the text data.
Example
return response.text('Hello, world!');
Binary Responses
binary(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
Creates a binary response.
Parameters
data
: The binary data to include in the responsemetadata
(optional): Additional metadata to include with the response
Return Value
Returns an AgentResponseType
object with the binary data.
Example
const binaryData = new Uint8Array([1, 2, 3, 4]).buffer;
return response.binary(binaryData, { filename: 'data.bin' });
Media Type Responses
The SDK provides specialized methods for various media types:
pdf(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
png(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
jpeg(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
gif(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
webp(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
mp3(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
mp4(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
m4a(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
m4p(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
webm(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
wav(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
ogg(data: ArrayBuffer, metadata?: Record<string, Json>): AgentResponseType
data(data: Json | ArrayBuffer | string, contentType: string, metadata?: Record<string, Json>): AgentResponseType
markdown(content: string, metadata?: Record<string, Json>): AgentResponseType
Each method works similarly to the binary()
method but sets the appropriate content type. The data
method allows setting specific data with an exact content type, while the markdown
method provides a convenient way to return markdown content.
Example
// Return a PNG image
return response.png(imageData, { filename: 'chart.png' });
// Return an MP3 audio file
return response.mp3(audioData, { duration: 120 });
HTML Responses
html(data: string, metadata?: Record<string, Json>): AgentResponseType
Creates an HTML response.
Parameters
data
: The HTML content to include in the responsemetadata
(optional): Additional metadata to include with the response
Return Value
Returns an AgentResponseType
object with the HTML content.
Example
return response.html('<h1>Hello, world!</h1><p>This is an HTML response.</p>');
Empty Responses
empty(metadata?: Record<string, Json>): AgentResponseType
Creates an empty response.
Parameters
metadata
(optional): Additional metadata to include with the response
Return Value
Returns an AgentResponseType
object with no payload.
Example
return response.empty();
Request Handling
The Agentuity SDK provides various methods for accessing request data through the request
object.
Accessing Request Data
get trigger
get trigger(): string
Gets the trigger type of the request.
Return Value
Returns a string representing the trigger type (webhook, cron, manual, agent, etc.).
Example
const triggerType = request.trigger;
console.log(`Request triggered by: ${triggerType}`);
get
get(key: string, defaultValue?: Json): Json
Gets a value from the request. The available properties depend on the trigger type.
Parameters
key
: The key to retrievedefaultValue
(optional): A default value to return if the key does not exist
Return Value
Returns the value for the specified key, or the default value if the key does not exist.
Trigger-specific Properties
Different trigger types provide different properties:
- Webhook: Includes a
headers
property containing the HTTP headers from the webhook request.
Example
// For webhook triggers, access headers
const headers = request.get('headers');
// Access a specific header
const githubSignature = headers['x-hub-signature'];
// Get a user ID with a default value
const userId = request.get('userId', 'anonymous');
metadata
metadata(key: string, defaultValue?: Json): Json
Note: This method is deprecated. Use get(key, defaultValue)
instead.
Gets metadata associated with the request.
Parameters
key
: The metadata key to retrievedefaultValue
(optional): A default value to return if the key does not exist
Return Value
Returns the metadata value for the specified key, or the default value if the key does not exist.
json
json(): Promise<Json>
Gets the payload of the request as a JSON object.
Return Value
Returns a Promise that resolves to the request payload as a JSON object.
Example
const data = await request.data.json();
console.log(`Request data: ${JSON.stringify(data)}`);
text
text(): Promise<string>
Gets the payload of the request as a string.
Return Value
Returns a Promise that resolves to the request payload as a string.
Example
const text = await request.data.text();
console.log(`Request text: ${text}`);
binary
binary(): Promise<ArrayBuffer>
Gets the payload of the request as an ArrayBuffer.
Return Value
Returns a Promise that resolves to the request payload as an ArrayBuffer.
Example
const binaryData = await request.data.binary();
console.log(`Binary data size: ${binaryData.byteLength} bytes`);
Media-Specific Methods
The SDK provides specialized methods for various media types, all of which now return Promises:
pdf(): Promise<ArrayBuffer>
png(): Promise<ArrayBuffer>
jpeg(): Promise<ArrayBuffer>
gif(): Promise<ArrayBuffer>
webp(): Promise<ArrayBuffer>
mp3(): Promise<ArrayBuffer>
mp4(): Promise<ArrayBuffer>
m4a(): Promise<ArrayBuffer>
m4p(): Promise<ArrayBuffer>
webm(): Promise<ArrayBuffer>
wav(): Promise<ArrayBuffer>
ogg(): Promise<ArrayBuffer>
email(): Promise<Email>
Each method returns a Promise that resolves to the request payload as an ArrayBuffer with the appropriate content type validation, except for email()
which returns an Email object.
Example
// Get an image from the request
const image = await request.png();
// Process the image...
// Get audio from the request
const audio = await request.mp3();
// Process the audio...
// Get email from the request (for message/rfc822 content type)
const email = await request.data.email();
// Process the email...
Email Processing
The Agentuity SDK provides an Email
class for parsing and processing inbound email data when the content type is message/rfc822
.
Email Class
The Email
class represents a parsed email message with methods to access various email properties.
date
date(): Date | null
Returns the date of the email.
Return Value
Returns a Date
object representing the email's date, or null
if no date is available.
Example
const email = await request.data.email();
const emailDate = email.date();
console.log('Email received on:', emailDate);
messageId
messageId(): string | null
Returns the message ID of the email.
Return Value
Returns a string containing the email's message ID, or null
if no message ID is available.
Example
const email = await request.data.email();
const msgId = email.messageId();
console.log('Message ID:', msgId);
headers
headers(): Headers
Returns the headers of the email.
Return Value
Returns a Headers
object containing all email headers.
Example
const email = await request.data.email();
const headers = email.headers();
console.log('Email headers:', headers);
to
to(): string | null
Returns the email address of the recipient(s).
Return Value
Returns a string containing the recipient email address. If there are multiple recipients, they are comma-separated. Returns null
if no recipient is available.
Example
const email = await request.data.email();
const recipients = email.to();
console.log('Recipients:', recipients);
fromEmail
fromEmail(): string | null
Returns the email address of the sender.
Return Value
Returns a string containing the sender's email address, or null
if no sender email is available.
Example
const email = await request.data.email();
const senderEmail = email.fromEmail();
console.log('From email:', senderEmail);
fromName
fromName(): string | null
Returns the name of the sender.
Return Value
Returns a string containing the sender's name, or null
if no sender name is available.
Example
const email = await request.data.email();
const senderName = email.fromName();
console.log('From name:', senderName);
subject
subject(): string | null
Returns the subject of the email.
Return Value
Returns a string containing the email subject, or null
if no subject is available.
Example
const email = await request.data.email();
const subject = email.subject();
console.log('Subject:', subject);
text
text(): string | null
Returns the plain text body of the email.
Return Value
Returns a string containing the plain text body, or null
if no plain text body is available.
Example
const email = await request.data.email();
const textBody = email.text();
console.log('Text content:', textBody);
html
html(): string | null
Returns the HTML body of the email.
Return Value
Returns a string containing the HTML body, or null
if no HTML body is available.
Example
const email = await request.data.email();
const htmlBody = email.html();
console.log('HTML content:', htmlBody);
attachments
attachments(): IncomingEmailAttachment[]
Returns the attachments of the email.
Return Value
Returns an array of IncomingEmailAttachment
objects. Returns an empty array if there are no attachments.
Example
const email = await request.data.email();
const attachments = email.attachments();
context.logger.debug('Attachments:', attachments.length);
for (const attachment of attachments) {
context.logger.debug('Attachment:', attachment.filename, attachment.contentDisposition);
const data = await attachment.data();
const buffer = await data.buffer();
context.logger.debug('Size:', buffer.length, 'bytes');
}
sendReply
sendReply(request, context, reply, from?): Promise<void>
Send a reply to the incoming email using the Agentuity email API.
Parameters
request
(AgentRequest): The triggering agent request containing email-auth-token in metadatacontext
(AgentContext): The agent context providing access to email servicesreply
(EmailReply): The reply configuration objectfrom?
(object, optional): Custom sender information for the replyname?
(string): Custom sender name. Defaults to the agent name if not providedemail?
(string): Custom sender email address. Defaults to the original recipient if not provided
Return Value
Returns a Promise<void>
that resolves when the reply is sent successfully.
Example
async function handler(request, response, context) {
const email = await request.data.email();
const attachment = {
filename: "response.pdf",
data: pdfData,
contentDisposition: "attachment"
};
await email.sendReply(request, context, {
subject: "Re: Your inquiry",
text: "Thank you for contacting us. We'll get back to you soon.",
html: "<p>Thank you for contacting us. We'll get back to you soon.</p>",
attachments: [attachment]
}, {
name: "Support Team",
email: "support@yourcompany.com"
});
context.logger.info("Reply sent successfully");
return response.json({
status: "Reply sent successfully"
});
}
Email Interfaces
EmailReply Interface
The EmailReply
interface defines the structure for email reply configuration.
Properties
subject?
(string): The subject of the reply. If not provided, defaults to 'RE: <original subject>'text
(string): The plain text body of the replyhtml?
(string): The optional HTML body of the replyattachments?
(OutgoingEmailAttachment[]): Optional attachments to includefrom?
(object, optional): Custom sender information for the replyname?
(string): Custom sender name. Defaults to the agent name if not providedemail?
(string): Custom sender email address. Defaults to the original recipient if not provided. Can only be overridden if custom email sending is enabled
Using a custom email address in the reply requires organizational email domain setup. Please contact us if you would like to configure for your organization.
IncomingEmailAttachment Interface
The IncomingEmailAttachment
interface represents an attachment from an incoming email.
Properties
filename
(string): The filename of the attachmentcontentDisposition
('attachment' | 'inline'): The content disposition of the attachment
Methods
data
data(): Promise<Data>
Asynchronously retrieves the attachment data as a Data object. For large attachments, this uses streaming to efficiently handle the data transfer.
Example
async function handler(request, response, context) {
const email = await request.data.email();
for (const attachment of email.attachments()) {
context.logger.debug(`Processing: ${attachment.filename}`);
context.logger.debug(`Disposition: ${attachment.contentDisposition}`);
const data = await attachment.data();
const buffer = await data.buffer();
context.logger.debug(`Size: ${buffer.length} bytes`);
context.logger.debug(`Content-Type: ${data.contentType}`);
}
return response.json({ message: "Attachments processed" });
}
OutgoingEmailAttachment Interface
The OutgoingEmailAttachment
interface represents an attachment to be included in an outgoing email reply.
Properties
filename
(string): The filename of the attachmentdata
(DataType): The data of the attachmentcontentDisposition?
('attachment' | 'inline'): The content disposition. Defaults to 'attachment' if not provided
Logging
The Agentuity SDK provides logging functionality through the context.logger
object.
Logger Interface
The Logger
interface defines the following methods:
interface Logger {
debug(message: string, ...args: unknown[]): void;
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
error(message: string, ...args: unknown[]): void;
child(opts: Record<string, Json>): Logger;
}
Logging Methods
debug
debug(message: string, ...args: unknown[]): void
Logs a debug message.
Parameters
message
: The message to logargs
: Additional arguments to include in the log
Example
context.logger.debug('Processing request', { requestId: '123' });
info
info(message: string, ...args: unknown[]): void
Logs an informational message.
Parameters
message
: The message to logargs
: Additional arguments to include in the log
Example
context.logger.info('Request processed successfully', { requestId: '123' });
warn
warn(message: string, ...args: unknown[]): void
Logs a warning message.
Parameters
message
: The message to logargs
: Additional arguments to include in the log
Example
context.logger.warn('Resource not found', { resourceId: '456' });
error
error(message: string, ...args: unknown[]): void
Logs an error message.
Parameters
message
: The message to logargs
: Additional arguments to include in the log
Example
context.logger.error('Failed to process request', error);
Creating Child Loggers
child
child(opts: Record<string, unknown>): Logger
Creates a child logger with additional context.
Parameters
opts
: Additional context to include in all logs from the child logger
Return Value
Returns a new Logger
instance with the additional context.
Example
const requestLogger = context.logger.child({ requestId: '123', userId: '456' });
requestLogger.info('Processing request'); // Includes requestId and userId
Welcome Function
The Agentuity SDK allows you to customize the initial appearance of DevMode when it starts interacting with your agents by exporting a welcome()
function. This function returns an AgentWelcomeResult
object that includes a welcome message and optional example prompts.
AgentWelcomeResult Interface
export interface AgentWelcomePrompt {
/**
* The data to display to the user
*/
data: Buffer | Uint8Array | ArrayBuffer | string | Json | Blob | ReadableStream | Data;
/**
* The content type of the data
*/
contentType: string;
}
export interface AgentWelcomeResult {
/**
* The welcome prompt to display to the user
*/
welcome: string;
/**
* The example prompts to display to the user
*/
prompts?: AgentWelcomePrompt[];
}
welcome
welcome(): AgentWelcomeResult
Defines a welcome message and optional example prompts for DevMode.
Return Value
Returns an AgentWelcomeResult
object with a welcome message and optional prompts.
Example
export const welcome = (): AgentWelcomeResult => {
return {
welcome: "Welcome to my Agent! How can I help you today?",
prompts: [
{
data: "What can you do?",
contentType: "text/plain",
}
],
};
};
Session
The Agentuity SDK provides a Session
interface that represents the current agent execution context.
interface Session {
request: AgentRequestType;
context: AgentContext;
}
Telemetry
The Agentuity SDK integrates with OpenTelemetry for tracing and metrics.
Tracing
The SDK provides access to OpenTelemetry tracing through the context.tracer
object.
Example
// Create a span
context.tracer.startActiveSpan('process-data', async (span) => {
try {
// Add attributes to the span
span.setAttribute('userId', '123');
// Perform some work
const result = await processData();
// Add events to the span
span.addEvent('data-processed', { itemCount: result.length });
return result;
} catch (error) {
// Record the error
span.recordException(error);
span.setStatus({ code: SpanStatusCode.ERROR });
throw error;
}
});
Breaking Changes
Data API
In version X.X.X, the Data API was refactored to use async methods instead of static properties to better support streaming capabilities:
Before:
// Accessing data properties directly
const jsonData = request.data.json;
const textData = request.data.text;
const base64Data = request.data.base64;
After:
// Using async methods to access data
const jsonData = await request.data.json();
const textData = await request.data.text();
const base64Data = await request.data.base64();
This change affects all methods on the Data
interface:
data.base64
→data.base64()
data.text
→data.text()
data.json
→data.json()
data.object<T>()
→data.object<T>()
data.binary
→data.binary()
data.buffer
→data.buffer()
data.stream
→data.stream()
Deprecated Features
/run/:id
Route
The /run/:id
route is now deprecated as it provides the same functionality as /:id
. Applications should update their code to use the /:id
route instead.
Need Help?
Join our Community for assistance or just to hang with other humans building agents.
Send us an email at hi@agentuity.com if you'd like to get in touch.
Please Follow us on
If you haven't already, please Signup for your free account now and start building your first agent!