### Install and Initialize Calljmp CLI Source: https://context7_llms This snippet shows the basic commands to install the Calljmp CLI globally and then initialize a new Calljmp project. It's the first step to start building AI agents with Calljmp. ```bash npm install -g @calljmp/cli calljmp init calljmp agent deploy ``` -------------------------------- ### Install Web SDK (Bash) Source: https://calljmp.com/llms-full.txt Command to install the CallJMP Web SDK using npm, which is necessary for integrating CallJMP agents into React applications. ```bash npm install @calljmp/sdk-web ``` -------------------------------- ### Install Calljmp CLI Source: https://calljmp.com/llms-full.txt Installs the Calljmp command-line interface globally using npm. This tool is used for initializing, building, deploying, and managing Calljmp agents. ```bash npm install -g @calljmp/cli ``` -------------------------------- ### Calljmp CLI Commands for Authentication and Setup Source: https://calljmp.com/llms-full.txt Provides essential CLI commands for initializing a Calljmp agent project and generating TypeScript types for prompts and vaults. These are foundational steps for agent development. ```bash calljmp init # Initialize agent project calljmp typegen # Generate TypeScript types for prompts and vault ``` -------------------------------- ### Define Agent Configuration with Input Schema (TypeScript) Source: https://calljmp.com/llms-full.txt An example of configuring an agent, including defining its input schema and the main run function. This sets up the agent's behavior and expected input. ```typescript import { schema, AgentConfig } from '@calljmp/agent'; const inputSchema = { properties: { text: { title: 'Text', type: 'string', minLength: 1, }, }, required: ['text'], } as const satisfies schema.Schema; export const config: AgentConfig = { name: 'My Agent', description: 'Processes text input', forms: { inputSchema }, }; export async function run(input: schema.infer) { return { result: input.text.toUpperCase() }; } ``` -------------------------------- ### Get Agent Instance from Client (TypeScript) Source: https://calljmp.com/llms-full.txt Demonstrates how to obtain an agent instance from the initialized CallJMP client, using either a string shorthand or an object with a lookup key. ```typescript // Using string shorthand const agent = client.agents.agent('your-agent-lookup-key'); // Using object const agent = client.agents.agent({ lookupKey: 'your-agent-lookup-key' }); ``` -------------------------------- ### Basic Chat Agent with Memory Example in TypeScript Source: https://calljmp.com/llms-full.txt An example of a basic chat agent using '@calljmp/agent'. It configures the agent with a name and description, and the run function processes user messages, utilizes short-term memory, and generates a response using an LLM. ```typescript import { llm, memory, AgentConfig } from '@calljmp/agent'; export const config: AgentConfig = { name: 'Chat Agent', description: 'A simple chat agent with memory', }; export async function run(input: { message: string; sessionId: string }) { const context = memory.short.context(`chat:${input.sessionId}`); const response = await llm.generate({ input: [ { role: 'system', content: 'You are a helpful AI assistant.' }, { role: 'user', content: input.message }, ], memory: context, }); return { reply: response.response }; } ``` -------------------------------- ### Connect and Disconnect from Agent WebSocket (TypeScript) Source: https://calljmp.com/llms-full.txt Provides code examples for establishing a WebSocket connection to an agent, checking its connection status, and disconnecting from it. ```typescript // Connect await agent.connect(); // Check connection status console.log(agent.connected); // true if connected console.log(agent.connecting); // true if connecting console.log(agent.reconnecting); // true if reconnecting // Disconnect await agent.disconnect(); ``` -------------------------------- ### Implement RAG Pattern with Datasets and LLM (TypeScript) Source: https://calljmp.com/llms-full.txt Provides a complete example of the Retrieval-Augmented Generation (RAG) pattern, combining `datasets.query` for retrieving relevant context and `llm.generate` for synthesizing an answer based on that context. ```typescript import { llm, datasets, workflow } from '@calljmp/agent'; export async function run(input: { question: string }) { // Step 1: Retrieve relevant documents const docs = await workflow.phase({ name: 'Retrieve documents' }, async () => { const { segments } = await datasets.query({ prompt: input.question, topK: 5, minScore: 0.6, }); return segments; }); // Step 2: Generate answer using retrieved context const answer = await workflow.phase({ name: 'Generate answer' }, async () => { if (docs.length === 0) { return { answer: "I couldn't find relevant information.", sources: [] }; } const context = docs .map(s => `[${s.metadata.document.title || 'Doc'}]: ${s.content}`) .join(' '); const response = await llm.generate({ input: [ { role: 'system', content: `Answer based on the context. If unsure, say so. Context: ${context}`, }, { role: 'user', content: input.question }, ], }); return { answer: response.response, sources: docs.map(s => ({ title: s.metadata.document.title, page: s.metadata.pageIndex, score: s.score, })), }; }); return answer; } ``` -------------------------------- ### Document Q&A with RAG and Tool Calling (TypeScript) Source: https://calljmp.com/llms-full.txt Enables users to ask questions about documents and receive answers based on retrieved context. This agent uses Retrieval Augmented Generation (RAG) and defines a tool for document retrieval. It specifies a system prompt to guide the LLM and uses Zod for tool parameter validation. The `llm.generate` function is configured with a specific model and tools. ```typescript import { llm, workflow, datasets, schema, AgentConfig } from '@calljmp/agent'; import { z } from 'zod'; const inputSchema = { properties: { query: { title: 'Query', type: 'string', description: 'The query to search for in the documents.', minLength: 1, maxLength: 1000, }, }, required: ['query'], } as const satisfies schema.Schema; export const config: AgentConfig = { name: 'Document retrieval', description: 'A simple document retrieval agent.', forms: { inputSchema }, }; export async function run(input: schema.infer) { const { response } = await workflow.phase('Chat with documents', () => llm.generate({ model: 'openai/gpt-4o', input: [ { role: 'system', content: `You are a document assistant. Answer questions using ONLY the retrieved context. If information is not in the documents, say so clearly.`, }, { role: 'user', content: input.query }, ], tools: [ llm.tool({ name: 'retrieve_documents', description: 'Retrieve relevant documents based on the query.', parameters: z.object({ query: z.string().min(1).max(1000).describe('The search query'), }), execute: ({ query }) => workflow.phase( { name: 'Retrieve documents', scope: { query } }, async () => { const { segments } = await datasets.query(query); return segments .map(seg => `[${seg.source ?? 'Unknown'}] Relevance: ${seg.score.toFixed(2)} ${seg.content}`) .join('\n\n---\n\n'); } ), }), ], temperature: 0.2, }) ); return response; } ``` -------------------------------- ### Interact with Memory Context State (Get, Set, Delete) (TypeScript) Source: https://calljmp.com/llms-full.txt Details how to use a `MemoryContext` object to get, set, and delete state. It supports getting state with or without a default value, and setting state to a value or null. ```typescript const ctx = memory.short.context({ key: 'my-state' }); // Get current state const state = await ctx.get(); const stateWithDefault = await ctx.get({ count: 0 }); // Set state await ctx.set({ count: 1 }); // Clear state (set to null or call delete) await ctx.set(null); await ctx.delete(); ``` -------------------------------- ### Define Input Schema using Schema Module (TypeScript) Source: https://calljmp.com/llms-full.txt An example of defining a JSON schema for agent input using the schema module. It includes properties like 'query' and 'count' with validation rules. ```typescript const inputSchema = { properties: { query: { title: 'Query', type: 'string', description: 'The query to search for', minLength: 1, maxLength: 1000, }, count: { title: 'Result Count', type: 'integer', description: 'Number of results to return', minimum: 1, maximum: 100, }, }, required: ['query'], } as const satisfies schema.Schema; ``` -------------------------------- ### Calljmp CLI Commands for Resuming Suspended Agents Source: https://calljmp.com/llms-full.txt Explains how to resume agents that have been suspended, using a target run ID and a resumption token. Optional input can be provided to guide the resumption process. ```bash calljmp agent resume --target {RUN_ID} --resumption {TOKEN} calljmp agent resume --target {RUN_ID} --resumption {TOKEN} --input '{"approved":true}' ``` -------------------------------- ### Publish Live Events within Workflow Phases Source: https://calljmp.com/llms-full.txt Integrate `live.publish` calls within `workflow.phase` blocks to provide real-time updates on specific stages of an agent's workflow. This example shows publishing 'tool.call' before querying datasets and 'tool.result' after. ```typescript import { workflow, live, datasets } from '@calljmp/agent'; export async function run(input: { query: string }) { await workflow.phase({ name: 'Query knowledge base' }, async () => { await live.publish({ type: 'tool.call', data: { summary: 'Searching knowledge base' }, }); const results = await datasets.query(input.query); await live.publish({ type: 'tool.result', data: { resultsCount: results.segments.length }, }); return results; }); } ``` -------------------------------- ### Create New Calljmp Agent Project Source: https://calljmp.com/llms-full.txt Initializes a new Calljmp agent project. This command sets up the necessary files, including the main agent code (`index.ts`), package dependencies (`package.json`), and configuration files (`.calljmp/`). ```bash calljmp init ``` -------------------------------- ### Initialize CallJMP Web Client (TypeScript) Source: https://calljmp.com/llms-full.txt Shows how to initialize the CallJMP client for web applications, including options for specifying the project ID and enabling development mode with a custom base URL. ```typescript import { Calljmp } from '@calljmp/sdk-web'; const client = new Calljmp({ projectId: 'your-project-id', }); // For development const devClient = new Calljmp({ projectId: 'your-project-id', development: { enabled: true, baseUrl: 'http://localhost:8787', }, }); ``` -------------------------------- ### Deploy and Run Calljmp Agent Source: https://calljmp.com/llms-full.txt Commands for building, deploying, and running Calljmp agents. Includes options for local execution, deployment only, testing with specific input, and running named agent files. ```bash calljmp agent run # Build, deploy, and run locally calljmp agent deploy # Deploy only (no local run) calljmp agent run --input '{}' # Test with specific input calljmp agent run -n sentiment # Run a specific agent file (sentiment.ts) ``` -------------------------------- ### LLM Module - Basic Text Generation Source: https://calljmp.com/llms-full.txt Demonstrates how to perform basic text generation using the `llm.generate` function with system and user prompts. ```APIDOC ## LLM Module - Basic Text Generation ### Description Performs basic text generation by providing a system prompt and a user prompt to the LLM. ### Method `llm.generate(options)` ### Parameters #### Request Body - **input** (Array) - Required - An array of message objects, each with a `role` ('system' or 'user') and `content` (string). - **role** (string) - Required - The role of the message sender ('system' or 'user'). - **content** (string) - Required - The content of the message. ### Request Example ```typescript const response = await llm.generate({ input: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'What is TypeScript?' }, ], }); // response.response is a string ``` ### Response #### Success Response (200) - **response** (string) - The generated text response from the LLM. #### Response Example ```json { "response": "TypeScript is a strongly typed programming language that builds on JavaScript..." } ``` ``` -------------------------------- ### Query Datasets with Optimized Prompt (TypeScript) Source: https://calljmp.com/llms-full.txt Shows how to use the `optimize: true` option within the prompt object to enhance query performance for better retrieval results. ```typescript const { segments } = await datasets.query({ prompt: { text: 'pricing information', optimize: true, // Optimize query for better retrieval (default: true) }, }); ``` -------------------------------- ### Handle Incoming Messages from Agent (TypeScript) Source: https://calljmp.com/llms-full.txt Shows two ways to set up a message handler for incoming messages from an agent: either during client initialization or by assigning to the `onMessage` property later. ```typescript // Set handler via constructor options const agent = client.agents.agent({ lookupKey: 'my-agent', onMessage: async (message) => { console.log('Received:', message); }, autoConnect: true, // Connect automatically (default: true) }); // Or set handler later agent.onMessage = async (message) => { // Handle incoming message }; ``` -------------------------------- ### CLI Commands - Initialization and Type Generation Source: https://calljmp.com/llms-full.txt Commands for initializing a new Calljmp agent project and generating TypeScript types. ```APIDOC ## CLI Commands: Initialization & Type Generation ### `calljmp init` **Description:** Initializes a new agent project in the current directory. ### `calljmp typegen` **Description:** Generates TypeScript types for prompts and vault variables. ``` -------------------------------- ### CLI Commands - Agent Management Source: https://calljmp.com/llms-full.txt Commands for building, deploying, running, and testing agents locally. ```APIDOC ## CLI Commands: Agent Management ### `calljmp agent run` **Description:** Builds, deploys, and runs the agent locally. **Options:** - `--input '{}'` : Test the agent with specific input JSON. - `-n myagent` : Run a specific agent file (e.g., `myagent.ts`). - `--force-deploy` : Force redeployment of the agent. ### `calljmp agent deploy` **Description:** Deploys the agent without running it locally. **Options:** - `--force` : Force deployment even if the code has not changed. ``` -------------------------------- ### LLM Module Import and Basic Text Generation (TypeScript) Source: https://calljmp.com/llms-full.txt Shows how to import the LLM module and perform basic text generation. It requires the '@calljmp/agent' library. ```typescript import { llm } from '@calljmp/agent'; const response = await llm.generate({ input: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'What is TypeScript?' }, ], }); // response.response is a string ``` -------------------------------- ### Define and Execute Workflow Phases (TypeScript) Source: https://calljmp.com/llms-full.txt Illustrates how to define sequential execution steps (phases) within a workflow, including analyzing input and generating a response based on the analysis. Each phase can involve LLM calls. ```typescript import { workflow, llm } from '@calljmp/agent'; export async function run(input: { text: string }) { // Phase 1: Analyze const analysis = await workflow.phase( { name: 'Analyze sentiment', description: 'Classify text sentiment' }, async () => { return llm.generate({ input: [ { role: 'system', content: 'Classify as positive/negative/neutral.' }, { role: 'user', content: input.text }, ], }); } ); // Phase 2: Generate response based on analysis const response = await workflow.phase( { name: 'Generate response' }, async () => { const tone = analysis.response.includes('positive') ? 'enthusiastic' : 'professional'; return llm.generate({ input: [ { role: 'system', content: `Respond in a ${tone} tone.` }, { role: 'user', content: input.text }, ], }); } ); return response.response; } ``` -------------------------------- ### Agent Orchestration with Multiple Tools (TypeScript) Source: https://calljmp.com/llms-full.txt Demonstrates an agent workflow that gathers context from memory and datasets, generates a response using an LLM, and notifies via Slack. It utilizes the workflow, memory, datasets, and integrations modules. ```typescript import { llm, workflow, memory, datasets, web, vault, integrations } from '@calljmp/agent'; export async function run(input: { query: string; userId: string }) { // Phase 1: Get context from memory and datasets const context = await workflow.phase({ name: 'Gather context' }, async () => { const memoryContext = memory.short.context(`user:${input.userId}`); const { segments } = await datasets.query(input.query); return { memoryContext, segments }; }); // Phase 2: Generate response with LLM const response = await workflow.phase({ name: 'Generate response' }, async () => { return llm.generate({ input: [ { role: 'system', content: `Context: ${context.segments.map(s => s.content).join(' ')}`, }, { role: 'user', content: input.query }, ], memory: context.memoryContext, }); }); // Phase 3: Notify via Slack await workflow.phase({ name: 'Notify' }, async () => { await integrations.slack.postMessage({ channel: '#alerts', text: `Processed query for user ${input.userId}`, }); }); return response.response; } ``` -------------------------------- ### Calljmp CLI Commands for Agent Management Source: https://calljmp.com/llms-full.txt Details commands for managing the lifecycle of Calljmp agents, including running, deploying, testing with specific inputs, and forcing redeployments. These commands facilitate agent development and deployment workflows. ```bash calljmp agent run # Build, deploy, and run locally calljmp agent deploy # Deploy without running calljmp agent run --input '{}' # Test with specific input calljmp agent run -n myagent # Run specific agent (myagent.ts) calljmp agent run --force-deploy # Force redeployment calljmp agent deploy --force # Force deploy even if code unchanged ``` -------------------------------- ### Import Live Module Source: https://calljmp.com/llms-full.txt Import the `live` module from the `@calljmp/agent` package to enable real-time event publishing during agent execution. ```typescript import { live } from '@calljmp/agent'; ``` -------------------------------- ### LLM Module - Structured Output with Zod Schema Source: https://calljmp.com/llms-full.txt Demonstrates how to request structured output from the LLM by providing a Zod schema. ```APIDOC ## LLM Module - Structured Output with Zod Schema ### Description Generates a structured output from the LLM that conforms to a provided Zod schema. ### Method `llm.generate(options)` ### Parameters #### Request Body - **input** (Array) - Required - An array of message objects. - **responseSchema** (ZodObject) - Required - A Zod schema object defining the expected structure and types of the response. ### Request Example ```typescript import { llm } from '@calljmp/agent'; import { z } from 'zod'; const response = await llm.generate({ input: [{ role: 'user', content: 'Extract: John Doe, john@example.com' }], responseSchema: z.object({ name: z.string().describe('Full name'), email: z.string().email().describe('Email address'), }), }); // response.response is { name: string; email: string } console.log(response.response.name); // "John Doe" console.log(response.response.email); // "john@example.com" ``` ### Response #### Success Response (200) - **response** (Object) - An object conforming to the provided `responseSchema`. #### Response Example ```json { "response": { "name": "John Doe", "email": "john@example.com" } } ``` ``` -------------------------------- ### Use Generated Prompt Types in Agent Code (TypeScript) Source: https://calljmp.com/llms-full.txt Demonstrates how to import and use typed prompts within an agent's run function. It shows fetching prompt content and using it in an LLM generation call. ```typescript import { llm, prompts } from '@calljmp/agent'; export async function run(input: { text: string }) { const response = await llm.generate({ input: [ { role: 'system', content: await prompts.customerService.content(), }, { role: 'user', content: input.text }, ], }); return response.response; } ``` -------------------------------- ### LLM Tool Calling with Parameters (TypeScript) Source: https://calljmp.com/llms-full.txt Shows how to enable LLM tool calling by defining tools with descriptions and parameter schemas using Zod. The 'execute' function within the tool definition handles the actual tool logic. ```typescript import { llm } from '@calljmp/agent'; import { z } from 'zod'; const response = await llm.generate({ input: [{ role: 'user', content: 'What is the weather in Paris?' }], tools: [ llm.tool({ name: 'getWeather', description: 'Get current weather for a city', parameters: z.object({ city: z.string().describe('City name'), unit: z.enum(['celsius', 'fahrenheit']).optional(), }), execute: async ({ city, unit }) => { // Call weather API here return { temperature: 22, condition: 'sunny', unit: unit || 'celsius' }; }, }), ], toolChoice: 'auto', // 'auto' | 'required' | 'none' }); ``` -------------------------------- ### LLM Module - Specifying a Model Source: https://calljmp.com/llms-full.txt Shows how to specify a particular LLM model for generation, such as OpenAI's GPT-4o. ```APIDOC ## LLM Module - Specifying a Model ### Description Allows you to explicitly choose which LLM model to use for the generation request. ### Method `llm.generate(options)` ### Parameters #### Request Body - **model** (string) - Optional - The identifier of the LLM model to use (e.g., 'openai/gpt-4o'). If not specified, a default model is used. - **input** (Array) - Required - An array of message objects. ### Request Example ```typescript const response = await llm.generate({ model: 'openai/gpt-4o', input: [{ role: 'user', content: 'Hello' }], }); ``` ### Response #### Success Response (200) - **response** (string) - The generated text response from the specified LLM model. #### Response Example ```json { "response": "Hello! How can I assist you today?" } ``` ``` -------------------------------- ### Query Datasets with TopK and MinScore Options (TypeScript) Source: https://calljmp.com/llms-full.txt Explains how to refine dataset queries by specifying `topK` for the maximum number of results and `minScore` to filter by relevance. ```typescript const { segments } = await datasets.query({ prompt: 'What are the pricing options?', topK: 10, minScore: 0.7, }); ``` -------------------------------- ### Publish Live Events Source: https://calljmp.com/llms-full.txt Use the `live.publish` function to send real-time events. Events have a `type` (e.g., 'tool.call') and associated `data` payload. This is useful for monitoring agent progress and actions. ```typescript await live.publish({ type: 'tool.call', data: { summary: 'Searching knowledge base' }, }); ``` -------------------------------- ### Initialize Short-Term Memory Context with Default Values (TypeScript) Source: https://calljmp.com/llms-full.txt Shows how to create a short-term memory context with a specified key and a default value. This is useful for initializing state that might not yet exist. ```typescript const context = memory.short.context({ key: 'chat:data', defaultValue: { messages: [] }, }); ``` -------------------------------- ### Calljmp REST API: Run Agent (Bash) Source: https://calljmp.com/llms-full.txt Demonstrates how to run an agent using the Calljmp REST API via a cURL command. It requires an Authorization header with an invocation key and a JSON payload specifying the input. ```bash curl -X POST https://api.calljmp.com/target/v1/agent/run \ -H "Authorization: Bearer inv_YOUR_KEY" \ -H "Content-Type: application/json" \ -d '{"input":{"text":"Your message"}}' ``` -------------------------------- ### Send Message to Agent (TypeScript) Source: https://calljmp.com/llms-full.txt Illustrates how to send a message, including its type and payload, to an agent using the agent instance. ```typescript // Send a message await agent.send({ type: 1, payload: { message: 'Hello' }, }); ``` -------------------------------- ### Publish Various Live Event Patterns Source: https://calljmp.com/llms-full.txt The `live.publish` function supports various event types for different stages of agent execution, including 'progress', 'tool.call', 'tool.result', and custom events like 'analysis.complete'. Each event type has a specific data structure. ```typescript // Progress event await live.publish({ type: 'progress', data: { step: 1, total: 5, message: 'Processing data...' }, }); // Tool call event await live.publish({ type: 'tool.call', data: { tool: 'queryKnowledgeBase', summary: 'Searching for pricing information', }, }); // Tool result event await live.publish({ type: 'tool.result', data: { resultsCount: 5 }, }); // Custom event await live.publish({ type: 'analysis.complete', data: { result: 'positive', confidence: 0.95, timestamp: Date.now(), }, }); ``` -------------------------------- ### Import Workflow Module (TypeScript) Source: https://calljmp.com/llms-full.txt Demonstrates how to import the `workflow` module from the `@calljmp/agent` library for orchestrating agent tasks. ```typescript import { workflow } from '@calljmp/agent'; ``` -------------------------------- ### Import Datasets Module (TypeScript) Source: https://calljmp.com/llms-full.txt Shows the basic import statement for accessing the `datasets` module from the `@calljmp/agent` SDK. ```typescript import { datasets } from '@calljmp/agent'; ``` -------------------------------- ### Query Datasets for Relevant Segments (TypeScript) Source: https://calljmp.com/llms-full.txt Demonstrates how to query the datasets module with a simple text prompt to retrieve relevant document segments. It outlines the structure of the returned `segments` object. ```typescript const { segments } = await datasets.query('What are the main features?'); // Each segment contains: // - type: 'page' // - index: number // - source?: string // - content: string // - score: number (0-1 relevance score) // - metadata: { document: { title?, language? }, pageIndex: number } ``` -------------------------------- ### Specifying LLM Model for Generation (TypeScript) Source: https://calljmp.com/llms-full.txt Demonstrates how to specify a particular LLM model for text generation. This is useful for selecting models based on performance or feature requirements. ```typescript import { llm } from '@calljmp/agent'; const response = await llm.generate({ model: 'openai/gpt-4o', input: [{ role: 'user', content: 'Hello' }], }); ``` -------------------------------- ### Full Signature for llm.generate() (TypeScript) Source: https://calljmp.com/llms-full.txt Provides the complete TypeScript signature for the `llm.generate` function, detailing all available parameters for controlling LLM behavior and response formatting. ```typescript function generate< Schema extends z.ZodObject | undefined = undefined, Tools extends Array> | undefined = undefined, >(args: { model?: Model; input: (Input | Promise)[]; maxTokens?: number; temperature?: number; topP?: number; topK?: number; seed?: number; repetitionPenalty?: number; frequencyPenalty?: number; presencePenalty?: number; toolChoice?: 'auto' | 'required' | 'none'; tools?: Tools; responseSchema?: Schema; maxIterations?: number; memory?: MemoryContext; trim?: { strategy?: 'removeOldest' | 'summarizeOldest'; maxTokens?: number; } | 'removeOldest' | 'summarizeOldest'; }): Promise<{ response: Schema extends z.ZodObject ? z.infer : string; }>; ``` -------------------------------- ### Define Workflow Phases with Scoping for Loops (TypeScript) Source: https://calljmp.com/llms-full.txt Demonstrates how to use phase scoping within a loop to uniquely identify and track individual phases, particularly useful when processing collections of items. ```typescript export async function run(input: { items: { id: string }[] }) { for (const item of input.items) { await workflow.phase( { name: 'Processing item', description: 'Process each item in the collection.', scope: { itemId: item.id }, // Phase scoping for unique identification }, async () => { // Phase logic here } ); } } ``` -------------------------------- ### Calljmp Client Class Signature (TypeScript) Source: https://calljmp.com/llms-full.txt Defines the constructor for the Calljmp client, which requires a project ID and optional development configuration. It initializes the agents property. ```typescript class Calljmp { readonly agents: Agents; constructor(config: { projectId: string; development?: { enabled?: boolean; baseUrl?: string; }; }); } ``` -------------------------------- ### Scrape web page with activity simulation in TypeScript Source: https://calljmp.com/llms-full.txt Enable activity simulation in `web.scrape` to mimic user interactions like scrolling. The `maxScrolls` option limits the number of scroll actions performed. ```typescript const result = await web.scrape({ url: 'https://example.com', format: 'text', activity: { enabled: true, maxScrolls: 5, }, }); ``` -------------------------------- ### Import Schema Module (TypeScript) Source: https://calljmp.com/llms-full.txt Shows how to import the schema module from the '@calljmp/agent' package, which provides utilities for defining and working with JSON schemas. ```typescript import { schema } from '@calljmp/agent'; ``` -------------------------------- ### Structured Output Generation with Zod Schema (TypeScript) Source: https://calljmp.com/llms-full.txt Illustrates generating structured output from an LLM using a Zod schema for validation and type safety. Requires the 'zod' library and '@calljmp/agent'. ```typescript import { llm } from '@calljmp/agent'; import { z } from 'zod'; const response = await llm.generate({ input: [{ role: 'user', content: 'Extract: John Doe, john@example.com' }], responseSchema: z.object({ name: z.string().describe('Full name'), email: z.string().email().describe('Email address'), }), }); // response.response is { name: string; email: string } console.log(response.response.name); // "John Doe" console.log(response.response.email); // "john@example.com" ``` -------------------------------- ### Query Datasets with datasets.query() Source: https://calljmp.com/llms-full.txt The `datasets.query()` function allows agents to search and retrieve information from datasets. It accepts a string prompt or a more structured object with options like `topK` and `minScore`. The function returns a promise that resolves to an array of `DatasetSegment` objects, each containing content, score, and metadata. ```typescript function query( args: string | { prompt: string | { text: string; optimize?: boolean }; topK?: number; minScore?: number; } ): Promise<{ segments: DatasetSegment[]; }>; ``` -------------------------------- ### Calljmp Agent with Configuration Source: https://calljmp.com/llms-full.txt An enhanced Calljmp agent that includes an optional `config` object. This configuration can specify metadata like the agent's name and description, which can be used for documentation or UI generation. ```typescript import { llm, AgentConfig } from '@calljmp/agent'; export const config: AgentConfig = { name: 'My Agent', description: 'A helpful AI assistant', }; export async function run(input: { text: string }) { const response = await llm.generate({ input: [ { role: 'system', content: 'You are helpful.' }, { role: 'user', content: input.text }, ], }); return response.response; } ``` -------------------------------- ### Chat Agent with Knowledge Base and Live Events (TypeScript) Source: https://calljmp.com/llms-full.txt Implements a chat agent that can query a knowledge base. It uses LLM for response generation and includes live event publishing for tool calls and results. Dependencies include '@calljmp/agent' and 'zod'. ```typescript import { workflow, llm, datasets, live, memory, AgentConfig } from '@calljmp/agent'; import { z } from 'zod'; export const config: AgentConfig = { name: 'Knowledge Chat', description: 'A chat agent with knowledge base integration.', }; export async function run(input: { message: string }) { return workflow.phase({ name: 'Chat' }, async () => { const { response } = await llm.generate({ input: [ { role: 'system', content: `You are a helpful assistant. Use the knowledge base tool to answer questions.`, }, { role: 'user', content: input.message }, ], memory: memory.short.context('chat:data'), trim: { maxTokens: 5000 }, tools: [ llm.tool({ name: 'queryKnowledgeBase', description: 'Search the knowledge base for information.', parameters: z.object({ query: z.string().describe('The search query'), summary: z.string().describe('Brief description of the action'), }), execute: ({ query, summary }) => workflow.phase({ name: 'Query knowledge base', scope: { query } }, async () => { await live.publish({ type: 'tool.call', data: { summary } }); const { segments } = await datasets.query(query); await live.publish({ type: 'tool.result', data: { count: segments.length } }); return segments.map(s => s.content).join('\n---\n'); }), }), ], }); return response; }); } ``` -------------------------------- ### Manage Conversation History with Short-Term Memory Context (TypeScript) Source: https://calljmp.com/llms-full.txt Demonstrates how to use `memory.short.context()` to manage conversation history and session state. It shows integration with `llm.generate` for automatic loading and saving of history within a session. ```typescript import { llm, memory } from '@calljmp/agent'; export async function run(input: { message: string; sessionId: string }) { // Create a context for this session const context = memory.short.context(`session:${input.sessionId}`); // Use with LLM - automatically loads/saves history const response = await llm.generate({ input: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: input.message }, ], memory: context, }); return response.response; } ``` -------------------------------- ### LLM Generation with Automatic Memory Context (TypeScript) Source: https://calljmp.com/llms-full.txt Demonstrates using the LLM module with automatic memory context management. The 'memory.short.context' function handles loading and saving conversation history implicitly. ```typescript import { llm, memory } from '@calljmp/agent'; export async function run(input: { message: string; userId: string }) { const context = memory.short.context(`chat:${input.userId}`); const response = await llm.generate({ input: [ { role: 'system', content: 'You are helpful.' }, { role: 'user', content: input.message }, ], memory: context, // Automatically loads/saves conversation history }); return response.response; } ``` -------------------------------- ### Web Scraping Module Source: https://calljmp.com/llms-full.txt The `web` module provides capabilities for scraping web content, allowing you to extract text or HTML from specified URLs with options for consent handling and activity simulation. ```APIDOC ## POST /web/scrape ### Description Scrapes content from a given URL. Supports extracting content as plain text or raw HTML, with options to handle cookie consent and simulate user activity. ### Method POST ### Endpoint /web/scrape ### Parameters #### Request Body - **url** (string | URL) - Required - The URL of the web page to scrape. - **format** (string) - Optional - The desired format of the scraped content. Can be 'text' or 'html'. Defaults to 'text'. - **consent** (object) - Optional - Configuration for handling cookie consent banners. - **selectors** (array of strings) - Optional - CSS selectors for consent buttons. - **textPatterns** (array of strings) - Optional - Text patterns to identify consent buttons. - **activity** (object) - Optional - Configuration for simulating user activity during scraping. - **enabled** (boolean) - Optional - Whether to enable activity simulation. Defaults to false. - **maxScrolls** (number) - Optional - The maximum number of times to scroll the page during activity simulation. ### Request Example ```json { "url": "https://example.com", "format": "text", "consent": { "selectors": ["#accept-cookies", ".consent-button"], "textPatterns": ["Accept", "I agree"] }, "activity": { "enabled": true, "maxScrolls": 5 } } ``` ### Response #### Success Response (200) - **format** (string) - The format of the returned content ('text' or 'html'). - **text** (string) - The scraped text content (if format is 'text'). - **content** (string) - The scraped HTML content (if format is 'html'). #### Response Example ```json { "format": "text", "text": "This is the scraped text content of the page." } ``` ``` -------------------------------- ### Calljmp Agent with Input Schema Source: https://calljmp.com/llms-full.txt Demonstrates a Calljmp agent that defines an input schema using the `schema` module. This schema is used to generate forms or portals for user input, providing validation and type safety for the agent's arguments. ```typescript import { llm, schema, AgentConfig } from '@calljmp/agent'; const inputSchema = { properties: { text: { title: 'Input Text', type: 'string', description: 'Text to analyze', minLength: 1, maxLength: 1000, }, }, required: ['text'], } as const satisfies schema.Schema; export const config: AgentConfig = { name: 'Text Analyzer', description: 'Analyzes input text', forms: { inputSchema }, }; export async function run(input: schema.infer) { // input.text is typed as string const response = await llm.generate({ input: [ { role: 'user', content: input.text }, ], }); return response.response; } ``` -------------------------------- ### Define LLM Input Message Types (TypeScript) Source: https://calljmp.com/llms-full.txt Illustrates the different types of messages that can be used as input for LLM generation, including system, user, and assistant roles, with an option to include timestamps. ```typescript // System message { role: 'system', content: 'You are an expert.' } // User message { role: 'user', content: 'Hello' } // Assistant message (for conversation history) { role: 'assistant', content: 'Hi there!' } // With timestamp { role: 'user', content: 'Hello', timestamp: Date.now() } ``` -------------------------------- ### LLM Module - Loading Memory Context Explicitly Source: https://calljmp.com/llms-full.txt Shows how to explicitly load conversation history from memory and include it in the LLM input. ```APIDOC ## LLM Module - Loading Memory Context Explicitly ### Description Manually loads conversation history from a memory context and prepends it to the user's current message for LLM generation. ### Method `llm.context(memoryContext)` and `llm.generate(options)` ### Parameters #### Request Body (for `llm.generate`) - **input** (Array) - Required - An array of message objects, including loaded history and the current user message. ### Request Example ```typescript import { llm, memory } from '@calljmp/agent'; export async function run(input: { message: string }) { const chatContext = memory.short.context('chat:data'); const { history } = await llm.context(chatContext); const response = await llm.generate({ input: [ ...history, // Include conversation history { role: 'user', content: input.message }, ], }); return response.response; } ``` ### Response #### Success Response (200) - **response** (string) - The generated text response based on the explicit conversation history. #### Response Example ```json { "response": "Based on our previous conversation, you were asking about..." } ``` ``` -------------------------------- ### Run Agent Source: https://calljmp.com/llms-full.txt Initiates a new run for an agent. You can provide input data for the agent to process. ```APIDOC ## POST /agent/run ### Description Initiates a new run for an agent with optional input. ### Method POST ### Endpoint https://api.calljmp.com/target/v1/agent/run ### Parameters #### Query Parameters None #### Request Body - **input** (object) - Required - The input data for the agent. - **text** (string) - Optional - Example input field. ### Request Example ```json { "input": { "text": "Your message" } } ``` ### Response #### Success Response (200) - **runId** (string) - The unique identifier for the agent run. - **status** (string) - The initial status of the agent run (e.g., "pending"). #### Response Example ```json { "runId": "run_abc123", "status": "pending" } ``` ``` -------------------------------- ### Implement Workflow Retries for Fault Tolerance (TypeScript) Source: https://calljmp.com/llms-full.txt Illustrates how to wrap workflow phases with retry logic to handle transient errors, specifying the number of retries, delay between attempts, backoff strategy, and an error handling callback. ```typescript const result = await workflow.retry( { retries: 3, delay: 1000, // ms backoff: 'exponential', // or 'linear' onError: (error, attempt) => { console.log(`Attempt ${attempt} failed: ${error.message}`); }, }, workflow.phase({ name: 'Call external API' }, async () => { const response = await fetch('https://api.example.com/data'); if (!response.ok) throw new Error('API failed'); return response.json(); }) ); ``` -------------------------------- ### Perform a simple web scrape (defaults to text) in TypeScript Source: https://calljmp.com/llms-full.txt A simplified usage of `web.scrape` where only the URL is provided. This defaults to scraping the page as text and automatically simulates user-like browsing actions. ```typescript const result = await web.scrape({ url: 'https://calljmp.com' }); // Automatically performs user-like browsing actions ``` -------------------------------- ### Import Integrations Module Source: https://calljmp.com/llms-full.txt Import the `integrations` module from the `@calljmp/agent` package to connect your agent to external services. ```typescript import { integrations } from '@calljmp/agent'; ``` -------------------------------- ### Scrape web page with consent handling in TypeScript Source: https://calljmp.com/llms-full.txt Configure consent handling for `web.scrape` by providing an array of CSS selectors and text patterns to identify and interact with consent banners or pop-ups. ```typescript const result = await web.scrape({ url: 'https://example.com', format: 'text', consent: { selectors: ['#accept-cookies', '.consent-button'], textPatterns: ['Accept', 'I agree'], }, }); ``` -------------------------------- ### Basic Calljmp Agent Structure Source: https://calljmp.com/llms-full.txt Defines a minimal Calljmp agent. It exports an asynchronous `run` function that accepts an input object and uses the `@calljmp/agent` LLM module to generate a response based on the input text. ```typescript import { llm } from '@calljmp/agent'; export async function run(input: { text: string }) { const response = await llm.generate({ input: [ { role: 'system', content: 'You are helpful.' }, { role: 'user', content: input.text }, ], }); return response.response; } ``` -------------------------------- ### Multi-Step Workflow with Retry and Web Scraping (TypeScript) Source: https://calljmp.com/llms-full.txt Orchestrates a multi-step process involving web scraping, content analysis using LLM, and notification via Slack. Includes retry logic for web scraping. Dependencies include '@calljmp/agent', 'zod'. ```typescript import { llm, workflow, web, integrations, AgentConfig } from '@calljmp/agent'; import { z } from 'zod'; export const config: AgentConfig = { name: 'Web Analyzer', description: 'Scrapes and analyzes web content', }; export async function run(input: { url: string }) { // Phase 1: Scrape website with retry const content = await workflow.retry( { retries: 3, delay: 2000, backoff: 'exponential' }, workflow.phase({ name: 'Scrape website' }, async () => { const result = await web.scrape({ url: input.url, format: 'text' }); return result.text; }) ); // Phase 2: Analyze content const analysis = await workflow.phase({ name: 'Analyze content' }, async () => { return llm.generate({ input: [ { role: 'system', content: 'Summarize the main points of this content.' }, { role: 'user', content: content }, ], responseSchema: z.object({ summary: z.string(), keyPoints: z.array(z.string()), sentiment: z.enum(['positive', 'negative', 'neutral']), }), }); }); // Phase 3: Notify via Slack await workflow.phase({ name: 'Send notification' }, async () => { await integrations.slack.postMessage({ channel: '#analysis-results', blocks: [ { type: 'header', text: { type: 'plain_text', text: 'Website Analysis Complete' } }, { type: 'section', text: { type: 'mrkdwn', text: `*URL:* ${input.url}` } }, { type: 'section', text: { type: 'mrkdwn', text: `*Summary:* ${analysis.response.summary}` } }, ], }); }); return analysis.response; } ```