> ## Documentation Index
> Fetch the complete documentation index at: https://prismeai-legacy.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool Integration

> Learn how to connect AI agents to external systems, APIs, and services through tool integration in Prisme.ai

Tool integration connects AI agents to external systems, databases, and services, enabling them to perform actions beyond conversation. This guide explores the options for implementing tools in Prisme.ai and provides practical examples for different integration scenarios.

## Understanding Tool Integration

Tools in Prisme.ai represent functional capabilities that agents can use to:

1. **Access external data** from APIs, databases, and services
2. **Perform actions** in connected systems
3. **Process information** using specialized logic
4. **Execute workflows** across multiple systems

<Note>
  Effective tool integration requires a clear understanding of both the agent's needs and the target systems' capabilities and requirements.
</Note>

## Tool Integration Approaches

Prisme.ai offers multiple approaches to tool integration, each suited to different requirements and technical expertise levels:

<Tabs>
  <Tab title="No-Code in AI Knowledge">
    Configure tools through AI Knowledge's graphical interface.

    **Ideal for**:

    * Business users and subject matter experts
    * Simple integrations with existing systems
    * Quick deployment of common tool types
    * Combining knowledge and tool capabilities

    **Key capabilities**:

    * Visual tool configuration
    * Pre-built tool templates
    * Custom tool definition
    * Direct integration with RAG agents
    * Basic error handling
  </Tab>

  <Tab title="Low-Code in AI Builder">
    Create automations using the visual workflow editor in AI Builder.

    **Ideal for**:

    * Technical users with limited coding experience
    * Moderately complex workflows
    * Integration with multiple systems
    * Custom business logic implementation

    **Key capabilities**:

    * Visual automation design
    * Built-in action blocks
    * Conditional logic and branching
    * Error handling and retries
    * Event-based triggering
  </Tab>

  <Tab title="Code-Based in AI Builder">
    Develop advanced integrations in AI Builder using YAML (preferred for performance, maintainability and readability), or with Python and Node.js.

    **Ideal for**:

    * Developers and technical integration specialists
    * Complex system integrations
    * Advanced data processing requirements
    * Custom algorithms and specialized logic

    **Key capabilities**:

    * Full programmatic control
    * Custom API clients
    * Advanced error handling
    * Complex data transformations
    * Specialized business logic
  </Tab>
</Tabs>

## The AI Builder Foundation

AI Builder provides the foundational capabilities for all tool integrations in Prisme.ai, built on these core concepts:

<CardGroup cols="2">
  <Card title="Workspaces" icon="folder-tree">
    Project environments that organize related components

    **Key aspects**:

    * Unique slug identifier
    * Access control and sharing
    * Integration configuration
    * Event visibility and management
  </Card>

  <Card title="Automations" icon="gears">
    Server-side processes that perform actions and logic

    **Key aspects**:

    * Triggering via events, URLs, or schedules
    * Sequential or parallel execution
    * Conditional branching and loops
    * Variable management
    * Error handling
  </Card>

  <Card title="Event-Driven Architecture" icon="network-wired">
    Communication pattern using asynchronous events

    **Key aspects**:

    * System and custom events
    * Event publishing and subscription
    * Asynchronous/synchronous operations
    * Event history and monitoring
  </Card>

  <Card title="Apps Marketplace" icon="store">
    Pre-built integrations that can be installed

    **Key aspects**:

    * Ready-to-use connectors
    * Configuration options
    * Documentation access
    * Custom blocks and automations
  </Card>
</CardGroup>

## Creating Tools in AI Knowledge

For business users, AI Knowledge provides a straightforward interface for adding tools to agents:

<Steps>
  <Step title="Access Tool Configuration">
    Navigate to the Tools section in your AI Knowledge agent.

    The Tools section allows you to:

    * View currently configured tools
    * Add new tools
    * Edit existing tool configurations
    * Test tool functionality
  </Step>

  <Step title="Select Tool Type">
    Choose from built-in tools or custom integrations.

    Available options typically include:

    * **Built-in tools**: Web browsing, image generation, code interpreter
    * **Custom tools**: API endpoints, AI Builder automations
    * **Third-party tools**: Integrations from the marketplace
  </Step>

  <Step title="Configure Tool Parameters">
    Set up the required parameters and options.

    Configuration typically includes:

    * Tool name and description (used by the LLM for selection)
    * Required parameters (what the agent needs to provide)
    * Authentication settings
    * Output formatting preferences
    * Usage limits and constraints
  </Step>

  <Step title="Connect to Backend">
    Link the tool to its execution environment.

    This connection can be to:

    * A built-in service endpoint
    * An AI Builder automation
    * An external API endpoint
    * A marketplace app integration
  </Step>

  <Step title="Test and Validate">
    Verify the tool functions correctly.

    Testing should include:

    * Verification with sample inputs
    * Error case testing
    * Performance assessment
    * Output format validation
  </Step>
</Steps>

## Building Custom Tools in AI Builder

For more advanced requirements, AI Builder provides comprehensive capabilities for creating custom tools:

<Steps>
  <Step title="Create an Automation">
    Start by creating a new automation in your AI Builder workspace.

    Key configuration elements:

    * Unique slug identifier
    * Human-readable name
    * Description (critical for LLM understanding)
    * Trigger type (endpoint for tools)
  </Step>

  <Step title="Define Input Schema">
    Create a structured definition of the tool's parameters.

    The schema should include:

    * Required and optional parameters
    * Parameter types and constraints
    * Default values where appropriate
    * Descriptive field names
    * Validation rules
  </Step>

  <Step title="Implement Logic">
    Build the workflow that executes when the tool is called.

    Implementation options include:

    * Visual workflow with built-in actions
    * Native YAML workflows event driven or Custom code (Python/Node.js)
    * Conditional branching and loops
    * Error handling and retries
    * Integration with external systems
  </Step>

  <Step title="Format Response">
    Define how results are returned to the agent.

    Response formatting considerations:

    * Structured data for easy LLM processing
    * Clear labeling of results
    * Error information when needed
    * Context for result interpretation
    * Performance metrics if relevant
  </Step>

  <Step title="Test and Debug">
    Validate the tool functions correctly in isolation.

    Testing approaches include:

    * Manual execution with sample inputs
    * Monitoring in the Activity view
    * Error case simulation
    * Performance testing
    * Integration testing with agents
  </Step>
</Steps>

## Example: Web Browsing Tool Implementation

Let's examine the implementation of a Web Browsing tool:

<Accordion title="Tool Definition">
  The tool is defined with clear parameters and description:

  ```yaml theme={null}
  slug: Web-browsing
  name: AIK/Tools/Web browsing
  description: Return list of web browsing results.
  when:
    endpoint: true
  output:
    type: tool_result
    output: '{{output}}'
  labels:
    - tools
  ```

  This definition includes:

  * A unique identifier (`slug`)
  * A descriptive name for organization
  * A clear description for LLM understanding
  * The trigger type (endpoint)
  * Output format specification
  * Categorizing labels
</Accordion>

<Accordion title="Input Schema">
  The parameter schema defines what the agent needs to provide:

  ```yaml theme={null}
  validateArguments: true
  arguments:
    body:
      type: object
      properties:
        arguments:
          type: object
          properties:
            type:
              type: string
              enum:
                - search
                - news
                - images
                - videos
                - places
                - reviews
                - scholar
                - patents
                - shopping
            query:
              type: string
              title: User query
            country:
              type: string
              title: Country
            lg:
              type: string
              title: lg
            location:
              type: string
              title: location
            tbs:
              title: Date range
              type: string
              enum:
                - ''
                - qdr:h
                - qdr:d
                - qdr:w
                - qdr:m
                - qdr:y
              enumNames:
                - Any time
                - Past hours
                - Past 24 hours
                - Past week
                - Past month
                - Past year
  ```

  This schema:

  * Defines the required structure of input data
  * Sets constraints on parameter values (e.g., enums)
  * Provides descriptive titles for parameters
  * Includes options for different search types
  * Specifies format validation requirements
</Accordion>

<Accordion title="Logic Implementation">
  The tool's execution logic handles authentication, processing, and error cases:

  ```yaml theme={null}
  do:
    - conditions:
        '{{body.projectId}} != {{config.agentCredentials.projectId}} || !{{run.sourceWorkspaceId}} || {{run.sourceWorkspaceId}} != {{global.workspacesRegistry[''ai-knowledge''].id}}':
          - set:
              name: output
              value:
                error: Forbidden
          - break: {}
    - Serper.run:
        type: '{{body.arguments.type}}'
        q: '{{body.arguments.query}}'
        ql: '{{body.arguments.country}}'
        location: '{{body.arguments.location}}'
        num: 20
        output: search
        hl: '{{body.arguments.lg}}'
        tbs: '{{body.arguments.tbs}}'
    - set:
        name: currentDate
        value: '{% date({{run.date}}).iso %}'
    - set:
        name: output
        value:
          value: '{{search}}'
          description: List of search results
  ```

  This implementation:

  * Validates permissions and authentication
  * Handles security constraints
  * Calls an external service (Serper)
  * Processes the results
  * Formats the output for the agent
</Accordion>

## Common Tool Integration Patterns

<CardGroup cols="2">
  <Card title="API Integration" icon="plug">
    Connect to RESTful services and endpoints

    **Implementation**:

    ```yaml theme={null}
    do:
      - fetch:
          url: https://api.example.com/data
          method: GET
          headers:
            Authorization: Bearer {{config.apiKey}}
          output: apiResponse
      - set:
          name: output
          value:
            value: '{{apiResponse.body}}'
            description: Data retrieved from API
    ```

    This pattern is useful for integrating with external services that provide RESTful APIs.
  </Card>

  <Card title="Database Query" icon="database">
    Retrieve information from databases

    **Implementation**:

    ```yaml theme={null}
    do:
      - DB.query:
          connection: '{{config.dbConnection}}'
          query: 'SELECT * FROM products WHERE category = {{body.arguments.category}}'
          output: queryResults
      - set:
          name: output
          value:
            value: '{{queryResults}}'
            description: Product data from database
    ```

    This pattern enables agents to access structured data stored in databases.
  </Card>

  <Card title="Conditional Processing" icon="code-branch">
    Handle different scenarios based on conditions

    **Implementation**:

    ```yaml theme={null}
    do:
      - conditions:
          '{{body.arguments.type}} == "detailed"':
            - set:
                name: fields
                value: "id,name,description,price,specifications,reviews"
          '{{body.arguments.type}} == "summary"':
            - set:
                name: fields
                value: "id,name,price"
      - fetch:
          url: https://api.example.com/products/{{body.arguments.productId}}
          method: GET
          query:
            fields: '{{fields}}'
          output: productData
      - set:
          name: output
          value:
            value: '{{productData.body}}'
            description: Product information
    ```

    This pattern allows different processing paths based on input parameters or other conditions.
  </Card>

  <Card title="Multi-System Orchestration" icon="diagram-project">
    Coordinate actions across multiple systems

    **Implementation**:

    ```yaml theme={null}
    do:
      - CRM.getCustomer:
          customerId: '{{body.arguments.customerId}}'
          output: customer
      - Inventory.checkAvailability:
          productId: '{{body.arguments.productId}}'
          output: availability
      - conditions:
          '{{availability.inStock}}':
            - Orders.createOrder:
                customerId: '{{customer.id}}'
                productId: '{{body.arguments.productId}}'
                quantity: '{{body.arguments.quantity}}'
                output: orderResult
            - set:
                name: output
                value:
                  value: '{{orderResult}}'
                  description: Order created successfully
          default:
            - set:
                name: output
                value:
                  value:
                    error: 'Product not available'
                    estimatedRestock: '{{availability.estimatedRestock}}'
                  description: Product availability information
    ```

    This pattern enables complex workflows that span multiple systems and include conditional logic.
  </Card>
</CardGroup>

## Best Practices for Tool Integration

<Accordion title="Clear Tool Descriptions">
  The tool description is critical for the LLM to understand when and how to use the tool.

  **Good Example**:

  ```yaml theme={null}
  description: Search the web for current information based on a user query. Returns a list of search results including titles, snippets, and URLs. Best used for finding recent information not available in internal knowledge bases.
  ```

  **Poor Example**:

  ```yaml theme={null}
  description: Web search tool
  ```

  The good example clearly explains:

  * What the tool does
  * What it returns
  * When it should be used

  This helps the agent make appropriate decisions about tool selection and use.
</Accordion>

<Accordion title="Well-Structured Parameter Schemas">
  Parameter schemas should be clear, descriptive, and properly constrained.

  **Good Example**:

  ```yaml theme={null}
  properties:
    query:
      type: string
      title: Search query
      description: The specific information to search for on the web
    resultCount:
      type: integer
      title: Number of results
      description: How many search results to return
      minimum: 1
      maximum: 20
      default: 5
  ```

  **Poor Example**:

  ```yaml theme={null}
  properties:
    q:
      type: string
    n:
      type: integer
  ```

  The good example includes:

  * Descriptive titles and descriptions
  * Clear constraints (min/max)
  * Default values where appropriate
  * Self-documenting parameter names
</Accordion>

<Accordion title="Comprehensive Error Handling">
  Tools should handle errors gracefully and provide useful information for recovery.

  **Good Example**:

  ```yaml theme={null}
  do:
    - try:
        do:
          - fetch:
              url: https://api.example.com/data
              method: GET
              output: apiResponse
        catch:
          - conditions:
              '{{error.statusCode}} == 401':
                - set:
                    name: output
                    value:
                      error: 'Authentication failed. Please check API credentials.'
              '{{error.statusCode}} == 404':
                - set:
                    name: output
                    value:
                      error: 'Requested resource not found. Please verify parameters.'
              default:
                - set:
                    name: output
                    value:
                      error: 'An error occurred: {{error.message}}'
  ```

  This approach:

  * Handles specific error cases differently
  * Provides clear, actionable error messages
  * Includes context about what went wrong
  * Enables the agent to respond appropriately
</Accordion>

<Accordion title="Proper Authentication Management">
  Secure handling of credentials and authentication is essential.

  **Good Example**:

  ```yaml theme={null}
  do:
    - fetch:
        url: https://api.example.com/data
        method: GET
        headers:
          Authorization: Bearer {{config.apiKey}}
        output: apiResponse
  ```

  Key practices:

  * Store sensitive credentials in configuration, not hardcoded
  * Use appropriate authentication mechanisms for each service
  * Handle token expiration and refresh when needed
  * Implement proper error handling for authentication failures
</Accordion>

<Accordion title="Efficient Performance">
  Tools should be optimized for quick execution whenever possible.

  **Recommendations**:

  * Request only needed data (e.g., specific fields, limit result counts)
  * Use caching where appropriate for frequently accessed data
  * Implement timeouts to prevent long-running operations
  * Monitor and optimize query performance
  * Consider asynchronous patterns for long-running operations
</Accordion>

## Integration with AI Knowledge

Once you've created tools in AI Builder, you can make them available to agents in AI Knowledge:

<Steps>
  <Step title="Register the Tool">
    Make your automation available as a tool.

    This typically involves:

    * Adding appropriate labels (e.g., 'tools')
    * Ensuring the automation has an endpoint trigger
    * Verifying the description is LLM-friendly
    * Checking the parameter schema is complete
  </Step>

  <Step title="Configure in AI Knowledge">
    Add the tool to your AI Knowledge agent.

    In AI Knowledge:

    * Navigate to the Tools section
    * Select "Add Custom Tool"
    * Choose your AI Builder automation
    * Configure any additional settings
  </Step>

  <Step title="Create Usage Instructions">
    Add specific guidance for when and how to use the tool.

    Effective instructions include:

    * Clear criteria for when to use the tool
    * Guidance on parameter formatting
    * Examples of successful usage
    * Error handling recommendations
  </Step>

  <Step title="Test in Context">
    Verify the tool works properly within the agent context.

    Testing should include:

    * Typical usage scenarios
    * Edge cases and error conditions
    * Performance under load
    * Integration with other agent capabilities
  </Step>
</Steps>

## Monitoring and Debugging Tool Execution

AI Builder's Activity view provides comprehensive visibility into tool execution:

This view allows you to:

* See all events in chronological order
* Filter by event type, status, or date range
* View detailed execution information
* Diagnose errors and performance issues
* Track tool usage patterns

<Note>
  The Activity view is invaluable for debugging tool issues, as it shows the complete execution flow including parameter values, intermediate states, and error conditions.
</Note>

## Security Considerations

When integrating tools, consider these security best practices:

<CardGroup cols="2">
  <Card title="Authentication Management" icon="key">
    * Store credentials securely in configuration
    * Use appropriate auth mechanisms (OAuth, API keys, etc.)
    * Implement proper token management
    * Follow the principle of least privilege
  </Card>

  <Card title="Access Control" icon="lock">
    * Limit tool access to appropriate users
    * Validate permissions before execution
    * Implement proper tenant isolation
    * Audit tool usage regularly
  </Card>

  <Card title="Data Handling" icon="shield-halved">
    * Minimize sensitive data exposure
    * Implement proper data sanitization
    * Follow data retention policies
    * Handle PII according to regulations
  </Card>

  <Card title="Input Validation" icon="filter">
    * Validate all parameters before use
    * Implement strict schema validation
    * Protect against injection attacks
    * Handle unexpected inputs gracefully
  </Card>
</CardGroup>

## Advanced Integration Techniques

<Accordion title="Multi-Step Tool Orchestration">
  For complex workflows, implement multi-step orchestration patterns.

  **Example**:

  ```yaml theme={null}
  do:
    - set:
        name: workflowState
        value:
          status: 'initiated'
          step: 1
          data: {}
    - emit:
        event: workflow.started
        data:
          workflowId: '{{run.id}}'
    - DB.query:
        query: 'SELECT * FROM customers WHERE id = {{body.arguments.customerId}}'
        output: customer
    - set:
        name: workflowState.data.customer
        value: '{{customer}}'
    - set:
        name: workflowState.step
        value: 2
    - emit:
        event: workflow.customer.loaded
        data:
          workflowId: '{{run.id}}'
          customer: '{{customer}}'
    # Continue with additional steps...
  ```

  This approach:

  * Maintains workflow state throughout execution
  * Emits events at key points for monitoring
  * Breaks complex processes into manageable steps
  * Creates an audit trail of actions
</Accordion>

<Accordion title="Hybrid RAG and Tool Usage">
  Combine knowledge retrieval with tool execution for powerful capabilities.

  **Implementation Strategy**:

  1. Configure both RAG and tools in AI Knowledge
  2. Provide clear instruction on when to use each capability
  3. Create tools that supplement knowledge gaps
  4. Implement tools that can act on retrieved information

  **Example Instruction**:

  ```
  First check our internal knowledge base for product information. If you find basic details but pricing is missing or outdated, use the ProductPricing tool to retrieve current pricing. If the product isn't found in our knowledge base, use the ProductLookup tool to search our catalog API.
  ```
</Accordion>

<Accordion title="Dynamic Tool Selection">
  Implement logic to choose appropriate tools based on context.

  **Example**:

  ```yaml theme={null}
  do:
    - conditions:
        '{{body.arguments.dataSource}} == "internal"':
          - InternalDB.query:
              query: '{{body.arguments.query}}'
              output: results
        '{{body.arguments.dataSource}} == "partner"':
          - PartnerAPI.fetch:
              endpoint: /data
              query: '{{body.arguments.query}}'
              output: results
        '{{body.arguments.dataSource}} == "public"':
          - PublicData.search:
              query: '{{body.arguments.query}}'
              output: results
        default:
          - InternalDB.query:
              query: '{{body.arguments.query}}'
              output: internalResults
          - conditions:
              '{{internalResults.length}} > 0':
                - set:
                    name: results
                    value: '{{internalResults}}'
              default:
                - PublicData.search:
                    query: '{{body.arguments.query}}'
                    output: results
    - set:
        name: output
        value:
          value: '{{results}}'
          description: 'Query results'
  ```

  This pattern:

  * Allows explicit source selection
  * Implements fallback strategies
  * Optimizes data access paths
  * Provides consistent result formatting
</Accordion>

## Next Steps

Ready to implement tool integration for your agents? Continue your journey with these resources:

<CardGroup cols="2">
  <Card title="Tool Selection" icon="hand-pointer" href="/create-agents/tool-agents/tool-selection">
    Learn how to implement effective tool selection logic
  </Card>

  <Card title="Memory Management" icon="brain" href="/create-agents/tool-agents/memory">
    Understand state management across tool interactions
  </Card>

  <Card title="Execution & Activity" icon="bolt" href="/create-agents/tool-agents/execution-activity">
    Master monitoring and debugging tool execution
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/create-agents/tool-agents/error-handling">
    Implement robust error management for tools
  </Card>
</CardGroup>
