### LLM Tool Creation Source: https://context7.com/calljmp/calljmp-agent/llms.txt Defines and creates callable tools for LLM function calling capabilities. ```APIDOC ## llm.tool ### Description Creates a callable tool that can be provided to LLM generate calls, enabling function calling capabilities. ### Method `llm.tool` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the tool. - **description** (string) - Required - A description of what the tool does. - **parameters** (zod.ZodObject) - Required - A Zod schema defining the tool's parameters. - **execute** (function) - Required - The function to execute when the tool is called. ### Request Example ```typescript import { llm } from '@calljmp/agent'; import { z } from 'zod'; const weatherTool = llm.tool({ name: 'get_weather', description: 'Get current weather for a location', parameters: z.object({ city: z.string().describe('City name'), units: z.enum(['celsius', 'fahrenheit']).default('celsius'), }), execute: async ({ city, units }) => { // Simulated weather API call return { city, temperature: units === 'celsius' ? 22 : 72, condition: 'sunny', }; }, }); ``` ### Response #### Success Response (200) Returns a tool object that can be used with `llm.generate`. #### Response Example (No direct response example for tool creation, as it returns a tool object for further use.) ``` -------------------------------- ### Publish Real-time Messages with Live Module Source: https://context7.com/calljmp/calljmp-agent/llms.txt The live.publish function sends real-time messages to connected clients. It can publish simple objects, typed messages, or include error handling options. This is useful for streaming progress updates or results during agent execution. ```typescript import { live } from '@calljmp/agent'; // Publish a simple object await live.publish({ status: 'processing', progress: 0.5, message: 'Halfway done...', }); // Publish a typed message await live.publish({ type: 1, // Custom message type identifier payload: { event: 'task_completed', taskId: 'abc123', result: { success: true }, }, }); // Publish with error handling options await live.publish( { status: 'critical', error: 'Something went wrong' }, { throwOnError: true } ); ``` -------------------------------- ### Dataset Querying Source: https://context7.com/calljmp/calljmp-agent/llms.txt Enables semantic search over uploaded document datasets using vector embeddings. ```APIDOC ## datasets.query ### Description Queries the agent's dataset for relevant segments based on a text prompt. Returns scored results with metadata. ### Method `datasets.query` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **prompt** (string | object) - Required - The query prompt. Can be a string or an object with `text` and optional `optimize` flag. - **text** (string) - The query text. - **optimize** (boolean) - Optional - Whether to optimize the query for better results. - **topK** (number) - Optional - The number of top results to return. Defaults to a system-defined value. - **minScore** (number) - Optional - The minimum relevance score threshold for results. Defaults to a system-defined value. ### Request Example ```typescript import { datasets } from '@calljmp/agent'; // Simple string query const simpleResult = await datasets.query('How to reset password?'); // Advanced query with options const advancedResult = await datasets.query({ prompt: { text: 'authentication methods available', optimize: true, }, topK: 5, minScore: 0.7, }); ``` ### Response #### Success Response (200) - **segments** (Array) - An array of relevant segments found in the dataset. - **type** (string) - The type of the segment (e.g., 'page'). - **index** (number) - The index of the segment within its document. - **content** (string) - The text content of the segment. - **score** (number) - The relevance score of the segment. - **metadata** (object) - Metadata associated with the segment. - **document** (object) - Information about the source document. - **title** (string) - The title of the document. - **language** (string) - The language of the document. - **pageIndex** (number) - The page number or index within the document. #### Response Example ```json { "segments": [ { "type": "page", "index": 0, "content": "To reset your password, go to Settings...", "score": 0.92, "metadata": { "document": { "title": "User Guide", "language": "en" }, "pageIndex": 15 } } ] } ``` ``` -------------------------------- ### Create LLM Callable Tool with TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt Defines a callable tool for LLM function calling. It includes defining the tool's name, description, parameters using Zod schema, and an execution function. The tool can then be used with `llm.generate`. ```typescript import { llm } from '@calljmp/agent'; import { z } from 'zod'; // Define a weather lookup tool const weatherTool = llm.tool({ name: 'get_weather', description: 'Get current weather for a location', parameters: z.object({ city: z.string().describe('City name'), units: z.enum(['celsius', 'fahrenheit']).default('celsius'), }), execute: async ({ city, units }) => { // Simulated weather API call return { city, temperature: units === 'celsius' ? 22 : 72, condition: 'sunny', }; }, }); // Use the tool with generate const result = await llm.generate({ model: 'openai/gpt-4o', input: [ { role: 'user', content: 'What is the weather in Paris?' }, ], tools: [weatherTool], toolChoice: 'auto', maxIterations: 3, }); ``` -------------------------------- ### Query Datasets with TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt Enables semantic search over uploaded document datasets. It allows querying with simple text prompts or advanced options including prompt optimization, top-K results, and a minimum relevance score. Results include scored segments with metadata. ```typescript import { datasets } from '@calljmp/agent'; // Simple string query const simpleResult = await datasets.query('How to reset password?'); console.log(simpleResult.segments); // [ // { // type: 'page', // index: 0, // content: 'To reset your password, go to Settings...', // score: 0.92, // metadata: { // document: { title: 'User Guide', language: 'en' }, // pageIndex: 15 // } // } // ] // Advanced query with options const advancedResult = await datasets.query({ prompt: { text: 'authentication methods available', optimize: true, // Query optimization for better results }, topK: 5, // Return top 5 matches minScore: 0.7, // Minimum relevance score threshold }); // Use results in LLM context for (const segment of advancedResult.segments) { console.log(`[${segment.score.toFixed(2)}] ${segment.metadata.document.title}`); console.log(` Page ${segment.metadata.pageIndex}: ${segment.content.slice(0, 100)}...`); } ``` -------------------------------- ### Web Scraping Source: https://context7.com/calljmp/calljmp-agent/llms.txt Scrapes content from a URL, returning either plain text or HTML. Supports consent dialog handling and scroll-based content loading. ```APIDOC ## web.scrape ### Description Scrapes content from a URL, returning either plain text or HTML. Supports consent dialog handling and scroll-based content loading. ### Method `web.scrape` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string | URL) - Required - The URL to scrape. - **format** (string) - Optional - The desired output format ('text' or 'html'). Defaults to 'text'. - **consent** (object) - Optional - Configuration for handling consent dialogs. - **selectors** (Array) - CSS selectors for consent buttons. - **textPatterns** (Array) - Text patterns to identify consent buttons. - **activity** (object) - Optional - Configuration for simulating user activity. - **enabled** (boolean) - Whether to enable activity simulation. - **maxScrolls** (number) - Maximum number of scrolls to perform. ### Request Example ```typescript import { web } from '@calljmp/agent'; // Scrape as plain text const textResult = await web.scrape({ url: 'https://example.com/article', format: 'text', }); // Scrape as HTML const htmlResult = await web.scrape({ url: 'https://example.com/page', format: 'html', }); // Scrape with consent and activity simulation const fullResult = await web.scrape({ url: new URL('https://example.com/dynamic-page'), format: 'text', consent: { selectors: ['#accept-cookies', '.consent-button'], textPatterns: ['Accept All', 'I Agree'], }, activity: { enabled: true, maxScrolls: 5, }, }); ``` ### Response #### Success Response (200) - **text** (string) - The scraped content as plain text (if format is 'text'). - **content** (string) - The scraped content as HTML (if format is 'html'). #### Response Example ```json { "text": "This is the scraped content..." } ``` ```json { "content": "

Scraped Page

" } ``` ``` -------------------------------- ### Scrape Web Content with TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt Scrapes content from a given URL, supporting both plain text and HTML formats. It includes options for consent handling (accepting cookies, agreeing to terms) and activity simulation (scrolling). The function returns the scraped content along with metadata. ```typescript import { web } from '@calljmp/agent'; // Scrape as plain text (default) const textResult = await web.scrape({ url: 'https://example.com/article', format: 'text', }); console.log(textResult.text); // Scrape as HTML const htmlResult = await web.scrape({ url: 'https://example.com/page', format: 'html', }); console.log(htmlResult.content); // Scrape with consent handling and activity simulation const fullResult = await web.scrape({ url: new URL('https://example.com/dynamic-page'), format: 'text', consent: { selectors: ['#accept-cookies', '.consent-button'], textPatterns: ['Accept All', 'I Agree'], }, activity: { enabled: true, maxScrolls: 5, }, }); ``` -------------------------------- ### Generate Text and Structured Outputs with LLMs in TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt The `llm.generate` function facilitates text generation using various LLM models. It supports standard input formats (system, user, assistant roles), optional Zod schemas for structured outputs, and configuration for parameters like `maxTokens` and `temperature`. ```typescript import { llm } from '@calljmp/agent'; import { z } from 'zod'; // Simple text generation const textResult = await llm.generate({ model: 'openai/gpt-4o', input: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'Explain quantum computing in one sentence.' }, ], maxTokens: 100, temperature: 0.7, }); console.log(textResult.response); // "Quantum computing uses quantum bits..." // Structured output with Zod schema const structuredResult = await llm.generate({ model: 'openai/gpt-4o', input: [ { role: 'user', content: 'Extract info: John Doe, age 30, engineer' }, ], responseSchema: z.object({ name: z.string(), age: z.number(), occupation: z.string(), }), }); console.log(structuredResult.response); // { name: "John Doe", age: 30, occupation: "engineer" } ``` -------------------------------- ### Send Messages to Slack Channel via Integrations Module Source: https://context7.com/calljmp/calljmp-agent/llms.txt The integrations.slack.postMessage function sends messages to a specified Slack channel using a pre-configured Slack integration. It supports simple text messages, markdown-formatted messages, and rich Block Kit messages for more complex layouts. ```typescript import { integrations } from '@calljmp/agent'; // Simple text message await integrations.slack.postMessage({ channel: '#notifications', text: 'Agent completed successfully!', }); // Markdown-formatted message await integrations.slack.postMessage({ channel: '#reports', markdown_text: '*Daily Report*\n- Processed: 150 items\n- Errors: 2', mrkdwn: true, }); // Rich Block Kit message await integrations.slack.postMessage({ channel: '#alerts', blocks: [ { type: 'header', text: { type: 'plain_text', text: 'Agent Status Update', emoji: true, }, }, { type: 'section', fields: [ { type: 'mrkdwn', text: '*Status:*\nComplete' }, { type: 'mrkdwn', text: '*Duration:*\n45 seconds' }, ], }, { type: 'section', text: { type: 'mrkdwn', text: 'View details in the ', }, }, ], }); ``` -------------------------------- ### Memory Management (Short-Term) Source: https://context7.com/calljmp/calljmp-agent/llms.txt Provides short-term memory for storing and retrieving values during agent execution. Supports typed contexts for scoped storage. ```APIDOC ## memory.short ### Description Short-term memory provider for storing and retrieving values during agent execution. Supports typed contexts for scoped storage. ### Methods - **store(key, value)**: Stores a value under a given key. - **retrieve(key, defaultValue?)**: Retrieves a value by key. Optionally provides a default value. - **delete(key)**: Deletes a value by key. - **context(config)**: Creates a typed memory context for scoped storage. ### Parameters for `context` #### Path Parameters None #### Query Parameters None #### Request Body - **key** (string) - Required - The unique key for the memory context. - **defaultValue** (any) - Optional - The default value if the key does not exist. ### Request Example ```typescript import { memory } from '@calljmp/agent'; // Direct key-value operations await memory.short.store('user-preference', { theme: 'dark', lang: 'en' }); const prefs = await memory.short.retrieve<{ theme: string; lang: string }>('user-preference'); // With default value const settings = await memory.short.retrieve('settings', { volume: 50 }); // Delete a key await memory.short.delete('user-preference'); // Typed context for scoped storage interface UserState { lastLogin: number; visitCount: number; } const userContext = memory.short.context({ key: 'user-state', defaultValue: { lastLogin: 0, visitCount: 0 }, }); const state = await userContext.get(); await userContext.set({ lastLogin: Date.now(), visitCount: state.visitCount + 1, }); ``` ### Response #### Success Response (200) Methods return promises that resolve to the result of the operation (e.g., retrieved value, boolean for delete, or void). #### Response Example ```json { "theme": "dark", "lang": "en" } ``` ``` -------------------------------- ### Define Agent Input Schema with Schema Module Source: https://context7.com/calljmp/calljmp-agent/llms.txt The schema module allows defining JSON Schema for agent input forms, including validation rules and UI hints. The AgentConfig type helps structure agent definitions with input schemas for configuration. ```typescript import { schema, type AgentConfig } from '@calljmp/agent'; // Define an agent with input schema const agentConfig: AgentConfig = { name: 'data-processor', description: 'Processes and analyzes uploaded data files', forms: { inputSchema: { $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'object', properties: { filename: { type: 'string', title: 'File Name', description: 'Name of the file to process', minLength: 1, maxLength: 255, }, outputFormat: { type: 'string', title: 'Output Format', enum: ['json', 'csv', 'xml'], default: 'json', 'ui:widget': 'select', }, maxRows: { type: 'integer', title: 'Maximum Rows', minimum: 1, maximum: 10000, default: 1000, 'ui:widget': 'updown', }, includeMetadata: { type: 'boolean', title: 'Include Metadata', default: true, }, tags: { type: 'array', title: 'Tags', items: { type: 'string' }, minItems: 0, maxItems: 10, }, }, required: ['filename', 'outputFormat'], }, }, }; ``` -------------------------------- ### Define and Execute Workflow Phases in TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt The `workflow.phase` function creates named execution phases for agent workflows. These phases can be monitored, retried, or run in parallel. They support basic execution or configuration with options like timeout and retryability. ```typescript import { workflow } from '@calljmp/agent'; // Create a simple named phase const result = await workflow.phase('fetch-data', async () => { const response = await fetch('https://api.example.com/data'); return response.json(); }); // Create a phase with configuration options const configuredResult = await workflow.phase( { name: 'process-data', timeout: 30000, retryable: true, }, async () => { // Perform data processing return { processed: true, count: 42 }; } ); ``` -------------------------------- ### LLM Context Retrieval Source: https://context7.com/calljmp/calljmp-agent/llms.txt Retrieves conversation history from a memory context for use in LLM generation. ```APIDOC ## llm.context ### Description Retrieves conversation history from a memory context for use in LLM generation. ### Method `llm.context` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **memoryContext** (MemoryContext) - Required - The memory context to retrieve history from. ### Request Example ```typescript import { llm, memory } from '@calljmp/agent'; const conversationMemory = memory.short.context({ key: 'conversation-history', }); const { history } = await llm.context(conversationMemory); ``` ### Response #### Success Response (200) - **history** (Array) - The conversation history retrieved from the memory context. #### Response Example ```json { "history": [ { "role": "user", "content": "Hello!" }, { "role": "assistant", "content": "Hi there! How can I help you today?" } ] } ``` ``` -------------------------------- ### Implement Retries for Workflow Phases in TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt The `workflow.retry` function wraps a phase to enable automatic retries upon failure. It supports default retry options or custom configurations for maximum attempts, backoff strategy, and initial delay. ```typescript import { workflow } from '@calljmp/agent'; // Retry a phase with default options const phaseResult = workflow.phase('unstable-api', async () => { const response = await fetch('https://api.example.com/unstable'); if (!response.ok) throw new Error('API failed'); return response.json(); }); const retriedResult = await workflow.retry(phaseResult); // Retry with custom options const customRetry = await workflow.retry( { maxAttempts: 5, backoff: 'exponential', initialDelay: 1000, }, phaseResult ); ``` -------------------------------- ### Manage Short-Term Memory with TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt Provides short-term memory operations for storing, retrieving, and deleting key-value pairs. It supports direct key-value access and typed contexts for scoped storage. Default values can be provided for retrieval operations. ```typescript import { memory } from '@calljmp/agent'; // Direct key-value operations await memory.short.store('user-preference', { theme: 'dark', lang: 'en' }); const prefs = await memory.short.retrieve<{ theme: string; lang: string }>( 'user-preference' ); console.log(prefs); // { theme: 'dark', lang: 'en' } // With default value const settings = await memory.short.retrieve('settings', { volume: 50 }); // Delete a key await memory.short.delete('user-preference'); // Typed context for scoped storage interface UserState { lastLogin: number; visitCount: number; } const userContext = memory.short.context({ key: 'user-state', defaultValue: { lastLogin: 0, visitCount: 0 }, }); const state = await userContext.get(); await userContext.set({ lastLogin: Date.now(), visitCount: state.visitCount + 1, }); ``` -------------------------------- ### Retrieve Conversation History with TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt Retrieves conversation history from a memory context for LLM generation. It uses `memory.short.context` to define the history storage and then passes this context to `llm.context` to fetch the history. The retrieved history is prepended to the new input for `llm.generate`. ```typescript import { llm, memory } from '@calljmp/agent'; const conversationMemory = memory.short.context({ key: 'conversation-history', }); // Retrieve previous conversation context const { history } = await llm.context(conversationMemory); // Continue the conversation with history const result = await llm.generate({ model: 'openai/gpt-4o', input: [ ...history, { role: 'user', content: 'Continue from where we left off.' }, ], memory: conversationMemory, trim: { strategy: 'removeOldest', maxTokens: 4000, }, }); ``` -------------------------------- ### Execute Workflow Phases Concurrently in TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt The `workflow.parallel` function allows for concurrent execution of multiple workflow phases. It supports a `maxConcurrency` option to limit the number of tasks running simultaneously and returns results in the order of the input tasks. ```typescript import { workflow } from '@calljmp/agent'; const task1 = workflow.phase('fetch-users', async () => { return { users: ['alice', 'bob'] }; }); const task2 = workflow.phase('fetch-orders', async () => { return { orders: [101, 102, 103] }; }); const task3 = workflow.phase('fetch-products', async () => { return { products: ['widget', 'gadget'] }; }); // Run all tasks in parallel with concurrency limit const [users, orders, products] = await workflow.parallel( { maxConcurrency: 2 }, [task1, task2, task3] ); console.log(users); // { users: ['alice', 'bob'] } console.log(orders); // { orders: [101, 102, 103] } console.log(products); // { products: ['widget', 'gadget'] } ``` -------------------------------- ### Suspend and Resume Agent Execution in TypeScript Source: https://context7.com/calljmp/calljmp-agent/llms.txt The `workflow.suspend` function pauses agent execution, allowing it to be resumed later. This is useful for long-running tasks requiring external events or human intervention. It supports a reason string or a configuration object with timeout and resume conditions. ```typescript import { workflow } from '@calljmp/agent'; // Simple suspend with reason await workflow.suspend('waiting-for-approval'); // Suspend with configuration await workflow.suspend({ reason: 'pending-human-review', timeout: 86400000, // 24 hours resumeOn: 'webhook', }); ``` -------------------------------- ### Access Secure Values from Vault Module Source: https://context7.com/calljmp/calljmp-agent/llms.txt The vault.values object provides access to securely stored key-value configuration secrets from the Calljmp vault. These values are populated at runtime and can be used for API authentication or configuration settings. ```typescript import { vault } from '@calljmp/agent'; // Access vault values (populated at runtime) const apiKey = vault.values['API_KEY'] as string; const config = vault.values['SERVICE_CONFIG'] as { endpoint: string; timeout: number }; const userId = vault.values['USER_ID'] as number; // Use in API calls const response = await fetch(config.endpoint, { headers: { 'Authorization': `Bearer ${apiKey}`, 'X-User-ID': String(userId), }, }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.