AI Agent

Objective

An AI Agent system provides intelligent prospect qualification and lead generation through a multi-step, orchestrated workflow using multiple specialized deployments. This architecture demonstrates how to build a comprehensive lead generation pipeline where different AI agents handle specific stages: conversation, qualification, and CRM insertion. Each deployment is optimized for its specific task while working together to create a seamless prospect experience.

Use Case

AI Agent is ideal for applications that need:

  • Multi-Stage Lead Processing: Break down prospect qualification into specialized steps handled by different agents
  • Automated Prospect Qualification: Systematically collect prospect information and score leads based on qualification criteria
  • CRM Integration: Automatically insert qualified leads directly into your sales pipeline
  • Intelligent Routing: Route prospects through different workflows based on their responses and qualification level
  • Sales Process Automation: Reduce manual lead processing while maintaining high-quality prospect data

Prerequisite

Before configuring an AI Agent, ensure you have:

  • Orq.ai Account: Active workspace in the Orq.ai Studio.
  • API Access: Valid API key from Workspace Settings > API Keys.
  • Model Access: At least one text generation model enabled in the Model Garden, such as gpt-4, claude-3-sonnet, or gpt-3.5-turbo.
  • CRM API: Access to your CRM system API (Salesforce, HubSpot, Pipedrive, etc.) with authentication credentials for inserting new leads.

Multi-Agent Workflow Architecture

flowchart LR
    A["👤 Prospect Responses"] --> B["📞 INGESTION<br/>Collect Information"] 
    B --> C["🔍 QUALIFICATION<br/>Analyze & Score"]
    C --> D["💾 INSERTION<br/>Insert to CRM"]
    
    B1["• Loop through responses<br/>• Build conversation history<br/>• Engage naturally"] 
    C1["• Score prospect (1-100)<br/>• Determine status<br/>• Format for CRM"]
    D1["• Validate data quality<br/>• Execute crminsert tool<br/>• Confirm completion"]
    
    B --- B1
    C --- C1  
    D --- D1
    
    style A fill:#1e293b,stroke:#3b82f6,stroke-width:3px,color:#ffffff
    style B fill:#3b82f6,color:#ffffff,stroke:#1e40af,stroke-width:2px
    style C fill:#8b5cf6,color:#ffffff,stroke:#7c3aed,stroke-width:2px
    style D fill:#10b981,color:#ffffff,stroke:#059669,stroke-width:2px
    style B1 fill:#1e293b,stroke:#3b82f6,stroke-width:2px,color:#e2e8f0
    style C1 fill:#1e293b,stroke:#8b5cf6,stroke-width:2px,color:#e2e8f0
    style D1 fill:#1e293b,stroke:#10b981,stroke-width:2px,color:#e2e8f0

Three Specialized Agents:

AgentPurposeTools
📞 IngestionNatural conversation & data collectionNone
🔍 QualificationAnalyze conversation & score prospectNone
💾 InsertionValidate data & insert into CRMcrminsert

Creating a CRM Insert Tool

First, create a tool for adding prospects to your CRM system. Head to the Orq.ai Studio:

  • Choose a Project and Folder and select the + button.
  • Choose Tool.
  • Create a crminsert tool for adding prospects to your CRM

CRM Insert Tool Configuration

Configure the CRM tool with JSON schema for function calling:

{
  "type": "object",
  "properties": {
    "company_name": {"type": "string", "description": "Name of the prospect's company"},
    "contact_name": {"type": "string", "description": "Full name of the primary contact"},
    "contact_email": {"type": "string", "description": "Email address of the primary contact"},
    "contact_phone": {"type": "string", "description": "Phone number of the primary contact"},
    "company_size": {"type": "string", "enum": ["1-10", "11-50", "51-200", "201-1000", "1000+"], "description": "Number of employees in the company"},
    "industry": {"type": "string", "description": "Industry or sector the company operates in"},
    "use_case": {"type": "string", "description": "Specific use case or problem they want to solve"},
    "timeline": {"type": "string", "enum": ["Immediate", "1-3 months", "3-6 months", "6+ months"], "description": "Timeline for implementation"},
    "budget_range": {"type": "string", "enum": ["Under $10k", "$10k-$50k", "$50k-$100k", "$100k+"], "description": "Approximate budget range"},
    "lead_score": {"type": "integer", "minimum": 1, "maximum": 100, "description": "Qualification score (1-100)"},
    "qualification_status": {"type": "string", "enum": ["qualified", "nurture", "disqualified"], "description": "Lead qualification status"},
    "lead_source": {"type": "string", "default": "AI Agent Qualification"},
    "notes": {"type": "string", "description": "Additional notes from the qualification conversation"}
  },
  "required": ["company_name", "contact_name", "contact_email", "use_case", "lead_score", "qualification_status"]
}

The tool configuration defines the function signature that the AI model will call. Your Python code needs to handle the actual execution of this function and make the appropriate CRM API calls when the tool is invoked.

📘

To learn more about Tools, see Creating a Tool.

Configuring Three Agent Deployments

Create three specialized deployments for the streamlined workflow:

1. Ingestion Agent Deployment

Create the conversation and ingestion agent:

  • Choose Deployment → Name: ingestionAgent
  • Select your preferred Model
  • No tools required (conversation only)
  • Configure System message:
You are a friendly AI conversation agent responsible for engaging prospects and collecting their information through natural conversation. Your role is to have engaging conversations while systematically gathering all the information needed for qualification.

Your conversation goals:
1. Create a warm, welcoming first impression
2. Understand their business needs and use case
3. Collect complete contact and company information
4. Gather budget, timeline, and decision authority details
5. Build rapport throughout the entire conversation

Information to collect:
- Company name, size, and industry
- Contact name, email, phone, job title
- Specific use case and pain points
- Budget range and timeline
- Decision-making authority
- Any additional relevant context

Conversation Guidelines:
- Be conversational and helpful, not pushy
- Ask follow-up questions to get complete information
- Keep the conversation flowing naturally
- Don't rush - build trust while collecting data
- Continue until you have comprehensive prospect information
- Signal when ready for handoff: "Thank you for sharing all that information. Let me review everything and connect you with the next step."

Your role is to be the complete conversation interface - engage, collect, and prepare for qualification.

2. Qualification Agent Deployment

Create the qualification and formatting agent:

  • Choose Deployment → Name: qualificationAgent
  • Select your preferred Model
  • No tools required (analysis only)
  • Configure System message:
You are a lead qualification specialist that processes conversation data and prepares it for CRM insertion. You receive complete prospect conversations and your role is to analyze, score, qualify, and format the data.

Your qualification process:
1. Analyze all collected prospect information from the conversation
2. Score the lead based on fit and qualification criteria  
3. Determine qualification status (qualified/nurture/disqualified)
4. Prepare complete CRM insertion payload with all formatted data
5. Output your analysis and routing decision

Scoring Criteria (1-100 scale):
- Company Size (20 pts): 1-10 employees=5pts, 11-50=10pts, 51-200=15pts, 201-1000=18pts, 1000+=20pts
- Budget Alignment (25 pts): Under $10k=5pts, $10k-$50k=15pts, $50k-$100k=20pts, $100k+=25pts
- Timeline (20 pts): Immediate=20pts, 1-3 months=18pts, 3-6 months=15pts, 6+ months=10pts
- Decision Authority (20 pts): Final decision maker=20pts, Influences=15pts, Recommends=10pts, Researching=5pts
- Use Case Fit (15 pts): Perfect fit=15pts, Good fit=12pts, Some fit=8pts, Poor fit=3pts

Qualification Status:
- Qualified: Score 70+ (route to insertion)
- Nurture: Score 40-69 (route to nurturing sequence)  
- Disqualified: Score <40 (no further action)

Provide a detailed analysis with the complete CRM data payload including lead score and qualification status. Format your response as a clear recommendation for the next step.

3. Insertion Agent Deployment

Create the CRM insertion agent:

  • Choose Deployment → Name: insertionAgent
  • Select your preferred Model
  • Add crminsert tool
  • Configure System message:
You are a CRM insertion specialist responsible for final data validation and inserting qualified prospects into the CRM system. You receive formatted prospect data and handle the final insertion step.

Your insertion process:
1. Validate the formatted prospect data for completeness
2. Perform final data quality checks
3. Insert prospect into CRM with proper formatting
4. Trigger sales team notifications
5. Confirm successful completion

Available Tools:
- CRM Insert: {{crminsert}} - Insert qualified prospects into CRM

Final Validation Checks:
- Business email validation (no personal domains)
- Complete required fields present
- Data quality standards met
- Qualification score threshold met (70+)

Only insert high-quality, validated prospect records. If data fails validation, report the issues rather than inserting incomplete records.

After successful insertion, provide confirmation with next steps for the sales team.

CRM Agent ready


Test your AI Agent in the Test tab by simulating prospect conversations that lead to CRM insertion.

📘

Learn more about tool configuration in Creating a Tool, and deployment setup in Setting Up a Deployment.

👍

When ready with your Deployment choose Deploy, learn more about Deployment Versioning.

Integrating with the SDK

Choose your preferred programming language and install the corresponding SDK:

pip install orq-ai-sdk
npm install @orq-ai/node

Get your integration ready by initializing the SDK as follows:

import os
from orq_ai_sdk import Orq

client = Orq(
    api_key=os.environ.get("ORQ_API_KEY", "__API_KEY__"),
    environment="production",
    contact_id="prospect_agent" # optional
)
import { Orq } from "@orq-ai/node";

const client = new Orq({
    apiKey: process.env.ORQ_API_KEY || "__API_KEY__",
    environment: "production",
    contactId: "prospect_agent" // optional
});

To implement the simplified 3-agent prospect qualification system:

import os
from orq_ai_sdk import Orq
import json

class SimpleProspectSystem:
    def __init__(self, client: Orq):
        self.client = client
        
        # Agent deployment keys
        self.agents = {
            "ingestion": "ingestionAgent",
            "qualification": "qualificationAgent", 
            "insertion": "insertionAgent"
        }
    
    def run_prospect_qualification(self, prospect_responses: list) -> dict:
        """Run complete prospect qualification workflow"""
        print("🚀 Starting 3-Agent Prospect Qualification")
        print("=" * 50)
        
        # Step 1: Ingestion Loop
        conversation = []
        print("📞 INGESTION PHASE")
        print("-" * 30)
        
        for i, user_message in enumerate(prospect_responses):
            print(f"👤 Prospect: {user_message}")
            
            # Add user message to conversation
            conversation.append({"role": "user", "content": user_message})
            
            # Call ingestion agent
            response = self.client.deployments.invoke(
                key=self.agents["ingestion"],
                messages=conversation
            )
            
            agent_response = response.choices[0].message.content
            conversation.append({"role": "assistant", "content": agent_response})
            
            print(f"🤖 Ingestion Agent: {agent_response}")
            print("-" * 30)
        
        print("\n🔍 QUALIFICATION PHASE")
        print("-" * 30)
        
        # Step 2: Explicit Qualification Call  
        qualification_prompt = f"""
        Analyze this complete prospect conversation and provide qualification analysis:
        
        Conversation: {json.dumps(conversation, indent=2)}
        
        Provide your analysis including lead score and qualification status.
        """
        
        qualification_response = self.client.deployments.invoke(
            key=self.agents["qualification"],
            messages=[{"role": "user", "content": qualification_prompt}]
        )
        
        qualification_analysis = qualification_response.choices[0].message.content
        print(f"🤖 Qualification Agent: {qualification_analysis}")
        print("-" * 30)
        
        print("\n💾 INSERTION PHASE")
        print("-" * 30)
        
        # Step 3: Explicit Insertion Call
        insertion_prompt = f"""
        Based on this conversation and qualification analysis, extract the prospect data and insert into CRM:
        
        Conversation: {json.dumps(conversation, indent=2)}
        
        Qualification Analysis: {qualification_analysis}
        
        Use the crminsert tool to add this prospect to the CRM system.
        """
        
        insertion_response = self.client.deployments.invoke(
            key=self.agents["insertion"],
            messages=[{"role": "user", "content": insertion_prompt}]
        )
        
        insertion_result = insertion_response.choices[0].message.content
        print(f"🤖 Insertion Agent: {insertion_result}")
        
        # Step 4: Extract and Print Insertion Payload
        tool_calls = getattr(insertion_response.choices[0].message, 'tool_calls', [])
        insertion_payload = None
        
        for tool_call in tool_calls:
            if tool_call.function.name == 'crminsert':
                insertion_payload = json.loads(tool_call.function.arguments)
                break
        
        print("\n🎯 FINAL INSERTION PAYLOAD")
        print("=" * 50)
        if insertion_payload:
            print(json.dumps(insertion_payload, indent=2))
        else:
            print("No CRM insertion payload found")
        
        return {
            "conversation": conversation,
            "qualification_analysis": qualification_analysis,
            "insertion_result": insertion_result,
            "insertion_payload": insertion_payload
        }

# Initialize the system
client = Orq(
    api_key=os.environ.get("ORQ_API_KEY", "__API_KEY__"),
    environment="production"
)

prospect_system = SimpleProspectSystem(client)

# Example prospect responses for the ingestion loop
prospect_responses = [
    "Hi, I'm exploring AI solutions for our customer support team.",
    "We're TechCorp, a B2B SaaS company with about 200 employees in the healthcare tech space.",
    "I'm Sarah Johnson, VP of Customer Success. You can reach me at [email protected] or 555-0123.",
    "We're handling 1000+ support tickets daily and our team is overwhelmed. We need AI to handle tier-1 inquiries automatically and escalate complex issues to human agents.",
    "We're looking to implement within 3 months and have allocated $75,000 annually for this type of solution.",
    "Yes, I'm the final decision maker for customer success tools under $100k.",
    "We currently use Zendesk and have a team of 12 support agents. Our main pain point is response time - currently averaging 4 hours."
]

# Run the complete workflow
result = prospect_system.run_prospect_qualification(prospect_responses)
import { Orq } from "@orq-ai/node";

class SimpleProspectSystem {
    constructor(client) {
        this.client = client;
        
        // Agent deployment keys
        this.agents = {
            ingestion: "ingestionAgent",
            qualification: "qualificationAgent", 
            insertion: "insertionAgent"
        };
    }
    
    async runProspectQualification(prospectResponses) {
        console.log("🚀 Starting 3-Agent Prospect Qualification");
        console.log("=".repeat(50));
        
        // Step 1: Ingestion Loop
        const conversation = [];
        console.log("📞 INGESTION PHASE");
        console.log("-".repeat(30));
        
        for (const userMessage of prospectResponses) {
            console.log(`👤 Prospect: ${userMessage}`);
            
            // Add user message to conversation
            conversation.push({ role: "user", content: userMessage });
            
            // Call ingestion agent
            const response = await this.client.deployments.invoke({
                key: this.agents.ingestion,
                messages: conversation
            });
            
            const agentResponse = response.choices[0].message.content;
            conversation.push({ role: "assistant", content: agentResponse });
            
            console.log(`🤖 Ingestion Agent: ${agentResponse}`);
            console.log("-".repeat(30));
        }
        
        console.log("\n🔍 QUALIFICATION PHASE");
        console.log("-".repeat(30));
        
        // Step 2: Explicit Qualification Call  
        const qualificationPrompt = `
        Analyze this complete prospect conversation and provide qualification analysis:
        
        Conversation: ${JSON.stringify(conversation, null, 2)}
        
        Provide your analysis including lead score and qualification status.
        `;
        
        const qualificationResponse = await this.client.deployments.invoke({
            key: this.agents.qualification,
            messages: [{ role: "user", content: qualificationPrompt }]
        });
        
        const qualificationAnalysis = qualificationResponse.choices[0].message.content;
        console.log(`🤖 Qualification Agent: ${qualificationAnalysis}`);
        console.log("-".repeat(30));
        
        console.log("\n💾 INSERTION PHASE");
        console.log("-".repeat(30));
        
        // Step 3: Explicit Insertion Call
        const insertionPrompt = `
        Based on this conversation and qualification analysis, extract the prospect data and insert into CRM:
        
        Conversation: ${JSON.stringify(conversation, null, 2)}
        
        Qualification Analysis: ${qualificationAnalysis}
        
        Use the crminsert tool to add this prospect to the CRM system.
        `;
        
        const insertionResponse = await this.client.deployments.invoke({
            key: this.agents.insertion,
            messages: [{ role: "user", content: insertionPrompt }]
        });
        
        const insertionResult = insertionResponse.choices[0].message.content;
        console.log(`🤖 Insertion Agent: ${insertionResult}`);
        
        // Step 4: Extract and Print Insertion Payload
        const toolCalls = insertionResponse.choices[0].message.tool_calls || [];
        let insertionPayload = null;
        
        for (const toolCall of toolCalls) {
            if (toolCall.function.name === 'crminsert') {
                insertionPayload = JSON.parse(toolCall.function.arguments);
                break;
            }
        }
        
        console.log("\n🎯 FINAL INSERTION PAYLOAD");
        console.log("=".repeat(50));
        if (insertionPayload) {
            console.log(JSON.stringify(insertionPayload, null, 2));
        } else {
            console.log("No CRM insertion payload found");
        }
        
        return {
            conversation,
            qualificationAnalysis,
            insertionResult,
            insertionPayload
        };
    }
}

// Initialize the system
const client = new Orq({
    apiKey: process.env.ORQ_API_KEY || "__API_KEY__",
    environment: "production"
});

const prospectSystem = new SimpleProspectSystem(client);

// Example prospect responses for the ingestion loop
const prospectResponses = [
    "Hi, I'm exploring AI solutions for our customer support team.",
    "We're TechCorp, a B2B SaaS company with about 200 employees in the healthcare tech space.",
    "I'm Sarah Johnson, VP of Customer Success. You can reach me at [email protected] or 555-0123.",
    "We're handling 1000+ support tickets daily and our team is overwhelmed. We need AI to handle tier-1 inquiries automatically and escalate complex issues to human agents.",
    "We're looking to implement within 3 months and have allocated $75,000 annually for this type of solution.",
    "Yes, I'm the final decision maker for customer success tools under $100k.",
    "We currently use Zendesk and have a team of 12 support agents. Our main pain point is response time - currently averaging 4 hours."
];

// Run the complete workflow
const result = await prospectSystem.runProspectQualification(prospectResponses);

Output

When going through the process, you'll see the 3 agents at work:

  • The ingestion agent is progressively ingesting the conversation.
  • The qualifying agent transforms and validates all the conversation.
  • The insertion agent generates the correct payload.

Extract of the output at qualification and insertion time:

## Recommendation: **ROUTE TO IMMEDIATE SALES ENGAGEMENT**

This is a high-quality lead that should be prioritized for immediate sales engagement. Sarah has the authority, budget, timeline, and clear pain points that align perfectly with an AI customer support solution. The next step should be scheduling a product demonstration focused on:

1. Zendesk integration capabilities
2. ROI calculation based on reducing response time from 4 hours
3. Healthcare compliance features
4. Implementation timeline to meet their 3-month requirement

The sales team should be prepared to discuss specific tier-1 automation scenarios and provide case studies from similar B2B SaaS companies in the healthcare space.
------------------------------

💾 INSERTION PHASE
------------------------------
🤖 Insertion Agent: I'll validate and insert this high-quality prospect into the CRM system. Let me process the data from the conversation and qualification analysis.

🎯 FINAL INSERTION PAYLOAD
==================================================
{
  "company_name": "TechCorp",
  "contact_name": "Sarah Johnson",
  "contact_email": "[email protected]",
  "contact_phone": "555-0123",
  "industry": "B2B SaaS - Healthcare Technology",
  "company_size": "201-1000",
  "use_case": "AI-powered tier-1 customer support automation to handle 1000+ daily tickets and reduce 4-hour average response time",
  "budget_range": "$50k-$100k",
  "timeline": "1-3 months",
  "lead_score": 88,
  "qualification_status": "qualified",
  "lead_source": "Inbound conversation",
  "notes": "VP of Customer Success with final decision authority for tools under $100k. TechCorp has 12 support agents overwhelmed with 1000+ daily tickets (85+ per agent). Current 4-hour response time needs improvement. Uses Zendesk for ticketing. Healthcare tech SaaS company requiring compliance considerations. Strong ROI potential with clear pain points and immediate implementation need within 3 months. Annual budget of $75,000 allocated. Recommend immediate product demo focusing on Zendesk integration and healthcare compliance features."
}

Viewing Logs

Going back to the Deployment pages, you can view the calls made through your 3-agent prospect qualification system. Each agent deployment provides separate logs that you can analyze individually or collectively to understand the complete pipeline performance.

You can view details for a single log by clicking on a log line. This opens a panel containing all the details for the log, including context, requests, and parameters sent to your Deployment.

Logs for the qualifying agent


📘

To learn more about logs see Logs.

Key Benefits

  • Simple: Linear 3-phase workflow (conversation → analysis → CRM)
  • Efficient: Only 1 tool call across entire pipeline
  • Scalable: Independent agents can be optimized separately
  • Cost-effective: Minimal deployments and orchestration overhead
👍

Next Steps: Learn about Logs and Tool Usage to monitor your pipeline.