The Strongly.AI Python Package

Empower Your AI Projects with LLM Governance and Productivity Tools

May 8, 2024 11 min read

The Challenge of AI Integration in Python Projects

As AI becomes increasingly central to software development, Python developers face a critical challenge: How can they effectively integrate powerful AI capabilities into their projects while maintaining security, efficiency, and alignment with organizational goals? The complexity of working with various AI models and managing prompts can often lead to increased development time and potential inconsistencies.

Introducing the Strongly.AI Python Package

At Strongly.AI, we understand the importance of seamless AI integration in Python workflows. That's why we've developed our comprehensive Python package, designed to simplify AI development and maximize performance in your projects.

Key Features:

  • Easy integration with multiple AI models
  • Streamlined session management
  • Built-in text guardrails & filtering capabilities
  • Efficient token usage monitoring
  • Secure user authentication
  • Advanced prompt optimization tools

Why Use the Strongly.AI Python Package?

Our Python package offers several compelling benefits:

  1. Simplified AI Integration: Easily incorporate AI capabilities into your Python projects with minimal setup and configuration.
  2. Enhanced Security: Leverage our built-in security features to ensure your AI interactions are protected and compliant.
  3. Optimized Performance: Take advantage of our prompt optimization tools to get the best results from your AI models.
  4. Efficient Resource Management: Monitor and control token usage to optimize costs and performance.
  5. Flexibility and Scalability: Our package grows with your needs, supporting everything from simple scripts to complex applications.

Comprehensive Demo of the Strongly.AI Python Package

Let's walk through a complete example that demonstrates the key features of the Strongly.AI Python package:

1. Installation

First, install the Strongly.AI package using pip:

pip install strongly

2. Setup and Authentication

Import the necessary modules and set up authentication:

import os
from strongly import APIClient
from strongly.exceptions import APIError, AuthenticationError

# Set up your API credentials (ideally, store these securely in environment variables)
os.environ['API_HOST'] = 'https://your-api-host.com'
os.environ['API_KEY'] = 'your-api-key-here'

# Initialize the client
client = APIClient()

3. Get Available Models

Fetch the list of available AI models:

try:
    models_data = client.get_models()
    print("Available Models:")
    for model in models_data['models']:
        print(f"- {model['label']}")
except Exception as e:
    print(f"An error occurred while fetching models: {str(e)}")

4. Create a Session

Create a new chat session:

try:
    session_data = client.create_session("Demo Chat Session")
    session_id = session_data['sessionId']
    print(f"New session created with ID: {session_id}")
except Exception as e:
    print(f"An error occurred while creating a session: {str(e)}")

5. Send Prompt Examples

Let's send two different prompts to the AI model:

def send_prompt(prompt, session_id):
    # First, filter the text
    try:
        filter_response = client.filter_text(prompt, session_id)
        print("Filter response:")
        print(filter_response['filter'])
    except APIError as e:
        print(f"Error filtering text: {str(e)}")
        return

    # Prepare the model, prompt, and filter data
    model = {
        'model': 'gpt-3.5-turbo',
        'modelLabel': 'ChatGPT 3.5-turbo',
        'messageId': filter_response['messageId'],
        'session': {'sessionId': session_id, 'sessionName': 'Demo Chat Session'},
        'temperature': 0.7,
        'max_tokens': 1024
    }
    prompt = {
        'system': 'You are a helpful assistant.',
        'assistant': '',
        'contextPrompts': [],
        'message': filter_response['filteredText']
    }

    # Send the message
    try:
        response = client.submit_message(model, prompt, filter_response['filter'])
        print(f"Sent message: {prompt}")
        print(f"Received response: {response['content']}")
        print("--------------------")
    except APIError as e:
        print(f"Error sending message: {str(e)}")

# Example prompts
send_prompt("What is the capital of France?", session_id)
send_prompt("Can you explain the concept of machine learning in simple terms?", session_id)

6. Retrieving Session Messages

Finally, let's retrieve and display all the messages from this session:

try:
    messages = client.get_session_messages("1d425217afcb2745ddf751e8")
    print("Session Messages:")
    for msg in messages:
        promptText = msg.get('promptText', 'Unknown')
        response = msg.get('response', 'No content')
        print(f"{promptText}: {response['choices'][0]['message']['content']}\n")
except Exception as e:
    print(f"An error occurred while retrieving session messages: {str(e)}")

Complete Demo Script

Here's the complete script that puts all these steps together:

import os
from strongly import APIClient
from strongly.exceptions import APIError, AuthenticationError

# Set up your API credentials (ideally, store these securely in environment variables)
os.environ['API_HOST'] = 'https://your-api-host.com'
os.environ['API_KEY'] = 'your-api-key-here'

# Initialize the client
client = APIClient()

# Get Available Models
try:
    models_data = client.get_models()
    print("Available Models:")
    for model in models_data['models']:
        print(f"- {model['label']}")
except Exception as e:
    print(f"An error occurred while fetching models: {str(e)}")

# Create a Session
try:
    session_data = client.create_session("Test Session")
    session_id = session_data['sessionId']
    print(f"New session created with ID: {session_id}")
except Exception as e:
    print(f"An error occurred while creating a session: {str(e)}")

# Function to send prompts
def send_prompt(prompt, session_id):
    # First, filter the text
    try:
        filter_response = client.filter_text(prompt, session_id)
        print("Filter response:")
        print(filter_response['filter'])
    except APIError as e:
        print(f"Error filtering text: {str(e)}")
        return

    # Prepare the model, prompt, and filter data
    model = {
        'model': models_data['models'][8]['model'],
        'modelLabel': models_data['models'][8]['label'],
        'messageId': filter_response['messageId'],
        'session': {'sessionId': session_id, 'sessionName': 'Test Session'},
        'temperature': 0.7,
        'max_tokens': 1024
    }
    prompt = {
        'system': 'You are a helpful assistant.',
        'assistant': '',
        'contextPrompts': [],
        'message': filter_response['filteredText']
    }

    # Send the message
    try:
        response = client.submit_message(model, prompt, filter_response['filter'])
        print(f"Sent message: {prompt}")
        print(f"Received response: {response['content']}")
        print("--------------------")
    except APIError as e:
        print(f"Error sending message: {str(e)}")

# Send Prompt Examples
send_prompt("What is the capital of France?", session_id)
send_prompt("Can you explain the concept of machine learning in simple terms?", session_id)

# Retrieve Session Messages
try:
    messages = client.get_session_messages(session_id)
    print("Session Messages:")
    for msg in messages:
        promptText = msg.get('promptText', 'Unknown')
        response = msg.get('response', 'No content')
        print(f"{promptText}: {response['choices'][0]['message']['content']}\n")
except Exception as e:
    print(f"An error occurred while retrieving session messages: {str(e)}")


# Don't forget to clean up by deleting the session when you're done
client.delete_session(session_id)
print("Session deleted.")

This comprehensive demo showcases the main features of the Strongly.AI Python package, including installation, authentication, model listing, session creation, prompt sending, and message retrieval. It provides a practical example of how to use the package in a real-world scenario.

The PromptOptimizer uses advanced techniques to refine your prompts, potentially leading to more accurate and relevant AI responses.

Real-World Use Case: AI-Powered Customer Support Chatbot

Let's walk through a practical example of using the Strongly.AI Python package to create a simple customer support chatbot:

import os
from strongly import APIClient
from strongly.exceptions import APIError, AuthenticationError

# Set up your API credentials (ideally, store these securely in environment variables)
os.environ['API_HOST'] = 'https://your-api-host.com'
os.environ['API_KEY'] = 'your-api-key-here'

# Initialize the client
client = APIClient()

# Get Available Models
try:
    models_data = client.get_models()
    print("Available Models:")
    for model in models_data['models']:
        print(f"- {model['label']}")
except Exception as e:
    print(f"An error occurred while fetching models: {str(e)}")

# Create a Session
try:
    session_data = client.create_session("Chatbot Session")
    session_id = session_data['sessionId']
    print(f"New session created with ID: {session_id}")
except Exception as e:
    print(f"An error occurred while creating a session: {str(e)}")

# Function to send prompts
def send_prompt(prompt, session_id):
    # First, filter the text
    try:
        filter_response = client.filter_text(prompt, session_id)
        print("Filter response:")
        print(filter_response['filter'])
    except APIError as e:
        print(f"Error filtering text: {str(e)}")
        return

    # Prepare the model, prompt, and filter data
    model = {
        'model': models_data['models'][8]['model'],
        'modelLabel': models_data['models'][8]['label'],
        'messageId': filter_response['messageId'],
        'session': {'sessionId': session_id, 'sessionName': 'Chatbot Session'},
        'temperature': 0.7,
        'max_tokens': 1024
    }
    prompt = {
        'system': """You are a helpful rental car assistant for 'DriveEase Car Rentals'.
        Your role is to assist customers with car rentals, answering questions about vehicle
        types, pricing, policies, and booking procedures. Always be polite, informative,
        and strive to provide the best customer service. If you don't have specific information,
        guide the customer to contact our customer service for more details.""",
        'assistant': '',
        'contextPrompts': [],
        'message': filter_response['filteredText']
    }

    # Send the message
    try:
        response = client.submit_message(model, prompt, filter_response['filter'])
        print(f"Human: {prompt['message']}")
        print(f"AI: {response['content']}")
        print("--------------------")
    except APIError as e:
        print(f"Error sending message: {str(e)}")

# Chatbot main loop
print("Welcome to the Strongly.AI Chatbot!")
print("Type 'exit' to end the conversation.")
while True:
    user_input = input("Human: ")
    if user_input.lower() == 'exit':
        break
    send_prompt(user_input, session_id)

# Retrieve Session Messages
try:
    messages = client.get_session_messages(session_id)
    print("\nConversation History:")
    for msg in messages:
        promptText = msg.get('promptText', 'Unknown')
        response = msg.get('response', 'No content')
        print(f"User: {promptText}")
        print(f"AI: {response['choices'][0]['message']['content']}\n")
except Exception as e:
    print(f"An error occurred while retrieving session messages: {str(e)}")

# Clean up by deleting the session
client.delete_session(session_id)
print("Session deleted. Thank you for using the Strongly.AI Chatbot!")

This example demonstrates how to create a basic chatbot using the Strongly.AI package, incorporating session management, text filtering, and interaction with AI models.

Conclusion: Empowering Python Developers with AI

The Strongly.AI Python package is more than just a library—it's a comprehensive toolkit that empowers Python developers to harness the full potential of AI in their projects. By providing a streamlined, secure, and efficient way to integrate AI capabilities, we're enabling you to push the boundaries of what's possible with Python and AI.

Whether you're building chatbots, developing data analysis tools, or creating cutting-edge AI applications, our Python package ensures you're always leveraging the best AI capabilities while maintaining control and alignment with your goals.

Ready to elevate your Python projects with advanced AI capabilities? Download the Strongly.AI Python package today and start exploring the possibilities. For any questions or support, don't hesitate to contact our team.