# Botpress

Botpress is an open-source platform for building AI-powered chatbots and conversational agents with a visual workflow builder.

## Prerequisites

* A Botpress Cloud account ([app.botpress.cloud](https://app.botpress.cloud))
* Your Tensorix API key from [app.tensorix.ai](https://app.tensorix.ai)

## Configuration

Botpress uses the **Execute Code** card to make HTTP requests to external APIs like Tensorix. This method gives you full control over the API integration.

{% hint style="info" %}
Botpress has built-in AI models, but you can use the Execute Code card to integrate custom OpenAI-compatible providers like Tensorix.
{% endhint %}

## Method: Execute Code Card

### Step 1: Create a Workflow

1. Open your bot in Botpress Studio
2. Create a new workflow or open an existing one
3. Add a node where you want to call the AI

### Step 2: Add Execute Code Card

1. Click **+** to add a new card
2. Select **Execute Code**
3. This opens the code editor

### Step 3: Write the API Call

```javascript
const response = await axios.post(
  'https://api.tensorix.ai/v1/chat/completions',
  {
    model: 'deepseek/deepseek-chat-v3.1',
    messages: [
      {
        role: 'system',
        content: 'You are a helpful customer service assistant.'
      },
      {
        role: 'user',
        content: event.preview // The user's message
      }
    ],
    temperature: 0.7,
    max_tokens: 500
  },
  {
    headers: {
      'Authorization': `Bearer ${env.TENSORIX_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

// Store the response in a workflow variable
workflow.aiResponse = response.data.choices[0].message.content;
```

### Step 4: Set Environment Variable

1. Go to **Chatbot Settings** → **Variables**
2. Add a new **Secret** variable named `TENSORIX_API_KEY`
3. Paste your Tensorix API key

### Step 5: Display the Response

After the Execute Code card:

1. Add a **Text** card
2. Set the content to: `{{workflow.aiResponse}}`

## Building a Complete Chatbot

### Basic AI Chatbot Flow

```
Start → Capture User Input → Execute Code (Tensorix) → Display Response → End
```

1. **Start Node**: Entry point of the conversation
2. **Capture**: Stores user message in `event.preview`
3. **Execute Code**: Calls Tensorix API
4. **Text Card**: Shows the AI response

### Multi-Turn Conversation

For conversations with memory:

```javascript
// Initialize conversation history if needed
if (!workflow.conversationHistory) {
  workflow.conversationHistory = [];
}

// Add user message to history
workflow.conversationHistory.push({
  role: 'user',
  content: event.preview
});

// Call Tensorix API
const response = await axios.post(
  'https://api.tensorix.ai/v1/chat/completions',
  {
    model: 'deepseek/deepseek-chat-v3.1',
    messages: [
      {
        role: 'system',
        content: 'You are a helpful assistant. Maintain context from previous messages.'
      },
      ...workflow.conversationHistory
    ],
    temperature: 0.7,
    max_tokens: 500
  },
  {
    headers: {
      'Authorization': `Bearer ${env.TENSORIX_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

const assistantMessage = response.data.choices[0].message.content;

// Add assistant response to history
workflow.conversationHistory.push({
  role: 'assistant',
  content: assistantMessage
});

// Store for display
workflow.aiResponse = assistantMessage;
```

## Example Implementations

### Customer Support Bot

```javascript
const response = await axios.post(
  'https://api.tensorix.ai/v1/chat/completions',
  {
    model: 'z-ai/glm-5.1',
    messages: [
      {
        role: 'system',
        content: `You are a customer support agent for Acme Corp.
        
        Guidelines:
        - Be helpful and professional
        - If you can't answer, suggest contacting support@acme.com
        - Keep responses concise
        
        Products: Widget Pro ($99), Widget Basic ($49), Widget Enterprise (contact sales)`
      },
      {
        role: 'user',
        content: event.preview
      }
    ],
    temperature: 0.5,
    max_tokens: 300
  },
  {
    headers: {
      'Authorization': `Bearer ${env.TENSORIX_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

workflow.aiResponse = response.data.choices[0].message.content;
```

### Intent Classifier

Use AI to classify user intent:

```javascript
const response = await axios.post(
  'https://api.tensorix.ai/v1/chat/completions',
  {
    model: 'z-ai/glm-5.1',
    messages: [
      {
        role: 'system',
        content: `Classify the user's intent into one of these categories:
        - pricing: Questions about costs, plans, pricing
        - support: Technical issues, problems, bugs
        - sales: Interest in buying, demos, trials
        - general: Everything else
        
        Respond with only the category name, nothing else.`
      },
      {
        role: 'user',
        content: event.preview
      }
    ],
    temperature: 0.1,
    max_tokens: 20
  },
  {
    headers: {
      'Authorization': `Bearer ${env.TENSORIX_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

workflow.userIntent = response.data.choices[0].message.content.trim().toLowerCase();
```

Then use **Expression** transitions to route based on `workflow.userIntent`.

### FAQ Bot with Knowledge Base

```javascript
// Assuming you have FAQ content in a knowledge base variable
const faqContent = `
Q: What are your hours?
A: We're open Monday-Friday, 9am-5pm EST.

Q: How do I reset my password?
A: Click "Forgot Password" on the login page.

Q: What's your refund policy?
A: 30-day money-back guarantee on all products.
`;

const response = await axios.post(
  'https://api.tensorix.ai/v1/chat/completions',
  {
    model: 'deepseek/deepseek-chat-v3.1',
    messages: [
      {
        role: 'system',
        content: `You are a helpful FAQ assistant. Answer based on this knowledge base:

${faqContent}

If the question isn't covered, say "I don't have that information, but you can contact support@company.com"`
      },
      {
        role: 'user',
        content: event.preview
      }
    ],
    temperature: 0.3,
    max_tokens: 200
  },
  {
    headers: {
      'Authorization': `Bearer ${env.TENSORIX_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

workflow.aiResponse = response.data.choices[0].message.content;
```

## Recommended Models

{% hint style="info" %}
**For Coding Tasks:**

* `z-ai/glm-5.1` - Best for tool calling and structured outputs
* `minimax/minimax-m2.5` - Best for complex reasoning tasks
  {% endhint %}

| Model ID                      | Best For                                 |
| ----------------------------- | ---------------------------------------- |
| `deepseek/deepseek-chat-v3.1` | General conversation                     |
| `z-ai/glm-5.1`                | Intent classification, structured output |
| `minimax/minimax-m2.5`        | Complex reasoning                        |
| `moonshotai/kimi-k2.5`        | Vision, long context                     |

## Error Handling

Add try-catch for robust error handling:

```javascript
try {
  const response = await axios.post(
    'https://api.tensorix.ai/v1/chat/completions',
    {
      model: 'deepseek/deepseek-chat-v3.1',
      messages: [
        { role: 'user', content: event.preview }
      ],
      temperature: 0.7,
      max_tokens: 500
    },
    {
      headers: {
        'Authorization': `Bearer ${env.TENSORIX_API_KEY}`,
        'Content-Type': 'application/json'
      },
      timeout: 30000 // 30 second timeout
    }
  );
  
  workflow.aiResponse = response.data.choices[0].message.content;
  workflow.aiError = null;
  
} catch (error) {
  console.error('Tensorix API error:', error.message);
  workflow.aiResponse = "I'm sorry, I'm having trouble processing your request right now.";
  workflow.aiError = error.message;
}
```

## Best Practices

### 1. Use Environment Variables

Never hardcode API keys. Use Botpress secrets:

* `env.TENSORIX_API_KEY`

### 2. Set Appropriate Timeouts

AI responses can take a few seconds. Set reasonable timeouts:

```javascript
{ timeout: 30000 } // 30 seconds
```

### 3. Limit Conversation History

For multi-turn conversations, limit history to prevent token overflow:

```javascript
// Keep only last 10 messages
if (workflow.conversationHistory.length > 10) {
  workflow.conversationHistory = workflow.conversationHistory.slice(-10);
}
```

### 4. Handle Edge Cases

* Empty user messages
* Very long messages
* API failures

## Troubleshooting

### "axios is not defined"

Axios is available globally in Botpress Execute Code. If you get this error:

* Check for typos in `axios`
* Ensure you're using `await` for the API call

### API Key Not Working

* Verify the secret variable name matches: `env.TENSORIX_API_KEY`
* Check the key at [app.tensorix.ai](https://app.tensorix.ai)
* Ensure there are no extra spaces

### Timeout Errors

* Increase timeout value
* Use a faster model
* Reduce max\_tokens for quicker responses

### Response Not Displaying

* Check the variable name: `workflow.aiResponse`
* Ensure the Text card references `{{workflow.aiResponse}}`
* Debug by logging: `console.log(response.data)`

## Support

Need help? Contact us at <support@tensorix.ai>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.tensorix.ai/automation-platforms/botpress.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
