Conversational Optimization Tutorial

Create optimization problems through natural language conversation with an AI agent. Perfect for users who want to optimize but aren't familiar with technical concepts.

What You'll Learn

Start Conversations

Describe problems in natural language

Interactive Guidance

Agent asks questions to collect parameters

Automatic Validation

Inputs validated in real-time

Execute Optimization

Complete and run optimization automatically

Step 1: Start a Conversation

Begin by describing your optimization problem in natural language. The agent will analyze your description and start collecting the required parameters.

Starting a conversation
from sematryx.client.sdk import SematryxClient

client = SematryxClient(api_key="YOUR_API_KEY")

# Start conversation with natural language description
result = client.start_conversational_optimization(
    description="I want to optimize my marketing budget across Google, Facebook, and LinkedIn to maximize ROI"
)

conversation_id = result["conversation_id"]
print(f"βœ… Conversation started: {conversation_id}")

Example: "I want to optimize my marketing budget across Google, Facebook, and LinkedIn to maximize ROI"

Step 2: Check Conversation Status

Poll the status endpoint to see if the agent has questions ready. The status will be "processing" while the agent analyzes, then "waiting_for_input" when a question is ready.

Checking conversation status
import time

# Check conversation status
status = client.get_conversation_status(conversation_id)

if status["status"] == "waiting_for_input":
    print(f"πŸ€– Agent: {status.get('question')}")
    print(f"πŸ’‘ Examples: {', '.join(status.get('examples', []))}")
elif status["status"] == "ready_to_optimize":
    print("βœ… All parameters collected! Ready to optimize.")
elif status["status"] == "processing":
    print("⏳ Agent is still processing...")
    time.sleep(2)  # Wait and check again

Step 3: Continue the Conversation

When the agent asks a question, provide your response. The agent will validate your input and continue collecting parameters until all required information is gathered.

Responding to agent questions
# Respond to agent's question
response = "$50000"  # User's answer
result = client.continue_conversation(conversation_id, response)
print(f"βœ… Response accepted: {result.get('accepted', False)}")

Example Conversation Flow

User: "I want to optimize my marketing budget for maximum ROI"
Agent: "I understand you want to optimize your marketing budget. 
What is your total marketing budget?"
User: "$50000"
Agent: "Thank you! I've recorded budget as 50000.0.
Which marketing channels would you like to optimize across?"
User: "Google, Facebook, LinkedIn"
Agent: "Great! I've recorded channels as ['Google', 'Facebook', 'LinkedIn'].
To calculate ROI, I need some performance data. 
What's the average cost per acquisition (CPA) for each channel?"
User: "Google: $25, Facebook: $30, LinkedIn: $45"
Agent: "Perfect! And what's the average revenue per customer?"
User: "$150"
Agent: "Excellent! I have all the information I need. 
Starting optimization now... This may take a few moments."
[Optimization running...]
Agent: "πŸŽ‰ Optimization complete! Here are your results:
πŸ“Š **Optimal Budget Allocation:**
   β€’ Google: $28,500 (57.0%) - Best ROI channel
   β€’ Facebook: $15,000 (30.0%) - Strong performance
   β€’ LinkedIn: $6,500 (13.0%) - Lower efficiency, minimal allocation
πŸ’° **Expected Performance:**
   β€’ Total Conversions: 1,140 customers
   β€’ Total Revenue: $171,000
   β€’ Average ROI: 242% (2.42x return)
   β€’ Total Profit: $121,000
πŸ’‘ **Key Insights:**
   Google delivers the best ROI at 300% due to lower CPA.
   I've allocated 57% of your budget there to maximize returns.
   Facebook gets 30% as it's your second-best performer.
   LinkedIn gets minimal allocation (13%) due to higher CPA.
Would you like me to explain any of these results in more detail?"
User: "Yes, why didn't you put all the budget in Google since it has the highest ROI?"
Agent: "Great question! While Google has the highest ROI, I applied risk diversification constraints to protect your marketing strategy:
πŸ›‘οΈ **Risk Management:**
   β€’ **Diminishing Returns**: As spend increases on a single channel, marginal ROI decreases. 
     Google's ROI drops from 300% at low spend to ~250% at high spend due to ad saturation.
   
   β€’ **Channel Diversification**: Allocating 30% to Facebook maintains your presence there, 
     preventing competitors from dominating that channel and protecting future opportunities.
   
   β€’ **Minimum Viable Presence**: LinkedIn gets 13% to maintain brand visibility in the 
     professional network, which is important for B2B credibility even if direct ROI is lower.
   β€’ **Risk Mitigation**: If Google's performance suddenly drops (algorithm changes, competition, etc.), 
     you're not left with zero marketing presence. Diversification reduces portfolio risk.
πŸ“ˆ **The Math:**
   β€’ 100% Google: Would yield ~$165,000 revenue (diminishing returns)
   β€’ Diversified (57/30/13): Yields $171,000 revenue (optimal balance)
   
   The diversified approach actually generates $6,000 more revenue while reducing risk!
Would you like to adjust these constraints, or explore what happens with different risk tolerance levels?"

Complete Example

Here's a complete example showing the full conversational optimization flow:

Complete conversational optimization flow
from sematryx.client.sdk import SematryxClient
import time

client = SematryxClient(api_key="YOUR_API_KEY")

# Step 1: Start conversation
result = client.start_conversational_optimization(
    description="I want to optimize my marketing budget for maximum ROI"
)
conversation_id = result["conversation_id"]

# Step 2: Interactive loop
while True:
    status = client.get_conversation_status(conversation_id)
    
    if status["status"] == "waiting_for_input":
        # Agent has a question
        print(f"\nπŸ€– Agent: {status.get('question')}")
        
        # Get user response (in production, from user input)
        user_response = input("You: ")
        
        # Continue conversation
        client.continue_conversation(conversation_id, user_response)
        
    elif status["status"] == "ready_to_optimize":
        print("\nβœ… All parameters collected! Ready to optimize.")
        break
        
    elif status["status"] == "processing":
        print("⏳ Processing...")
        time.sleep(2)
    else:
        break

# Step 3: Complete and optimize
result = client.complete_conversational_optimization(
    conversation_id,
    max_evaluations=2000,
    mode="balanced"
)

optimization_id = result['optimization_id']
print(f"\nπŸš€ Optimization started!")
print(f"πŸ“Š Optimization ID: {optimization_id}")

# Step 4: Poll for results
print("\n⏳ Waiting for optimization to complete...")
while True:
    opt_status = client.get_optimization_status(optimization_id)
    
    if opt_status["status"] == "completed":
        print("\nπŸŽ‰ Optimization complete!")
        
        # Get detailed results
        results = client.get_optimization_results(optimization_id)
        
        # Display results in a user-friendly format
        print(f"\nπŸ“Š Optimal Budget Allocation:")
        solution = results.get("solution", {})
        for channel, allocation in solution.items():
            dollar_sign = "$"
            formatted_amount = f"{dollar_sign}{allocation:,.0f}"
            print(f"   β€’ {channel}: {formatted_amount}")
        
        print(f"\nπŸ’° Performance Metrics:")
        print(f"   β€’ Total ROI: {results.get('roi', 0):.1%}")
        revenue = results.get('revenue', 0)
        dollar_sign = "$"
        formatted_revenue = f"{dollar_sign}{revenue:,.0f}"
        print(f"   β€’ Expected Revenue: {formatted_revenue}")
        print(f"   β€’ Total Conversions: {results.get('conversions', 0):,.0f}")
        
        # Agent can also provide insights
        if "insights" in results:
            print(f"\nπŸ’‘ Key Insights:")
            for insight in results["insights"]:
                print(f"   β€’ {insight}")
        
        break
    elif opt_status["status"] == "failed":
        print(f"\n❌ Optimization failed: {opt_status.get('error')}")
        break
    else:
        time.sleep(2)  # Poll every 2 seconds

Key Features

Natural Language Understanding

The agent uses LLM to understand your problem description and extract key components like domain, objective, and required parameters.

Progressive Parameter Collection

The agent asks one question at a time, ensuring you understand what's needed and providing examples when helpful.

Domain Extension Building

If no existing domain matches your problem, the agent can offer to create a custom domain extension on the fly.

Next Steps