File size: 5,525 Bytes
d53a51c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f061fb0
 
d53a51c
 
 
f061fb0
 
d53a51c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f061fb0
d53a51c
 
f061fb0
d53a51c
 
f061fb0
 
 
 
 
 
 
d53a51c
f061fb0
d53a51c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f061fb0
 
 
d53a51c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""
ElevenLabs Conversational AI Agent Integration
================================================
Module for interacting with ElevenLabs conversational AI agents.
"""

import os
from dotenv import load_dotenv
from elevenlabs.client import ElevenLabs
from elevenlabs.conversational_ai.conversation import Conversation

# Load environment variables from .env file
load_dotenv()


# =============================================================================
# CONFIGURATION - Update these values with your ElevenLabs agent settings
# =============================================================================

# Your ElevenLabs API key (stored in .env file)
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")

# Agent ID - Replace with your agent's ID from ElevenLabs dashboard
AGENT_ID = os.getenv("ELEVENLABS_AGENT_ID", "your-agent-id-here")

# Optional: Custom configuration for the agent
AGENT_CONFIG = {
    # Add any custom configuration here if needed
    # Example: language, voice settings, etc.
}


# =============================================================================
# Agent Interaction
# =============================================================================

class EULegislationAgent:
    """Wrapper class for ElevenLabs conversational agent."""
    
    def __init__(self):
        """Initialize the ElevenLabs client and conversation."""
        if not ELEVENLABS_API_KEY:
            raise ValueError(
                "ELEVENLABS_API_KEY not found. Please add it to your .env file:\n"
                "ELEVENLABS_API_KEY=your_api_key_here"
            )
        
        self.client = ElevenLabs(api_key=ELEVENLABS_API_KEY)
        self.conversation = None
    
    def start_conversation(self):
        """Start or restart a conversation with the agent."""
        try:
            self.conversation = Conversation(
                client=self.client,
                agent_id=AGENT_ID,
                requires_auth=False,  # Set to True if your agent requires authentication
                audio_interface=None,  # Set to an audio interface if using voice
                # Add any additional configuration here
                **AGENT_CONFIG
            )
            # Start the session
            self.conversation.start_session()
            return True
        except Exception as e:
            print(f"Error starting conversation: {e}")
            return False
    
    def send_message(self, message: str) -> str:
        """
        Send a message to the agent and get a response.
        
        Args:
            message: User's question or message
            
        Returns:
            str: Agent's response
        """
        try:
            # Start conversation if not already started
            if self.conversation is None:
                if not self.start_conversation():
                    return "❌ Error: Could not connect to the agent. Please check your API key and Agent ID."
            
            # Send message and get response
            response = self.conversation.send_user_message(message)
            
            # Extract text from response
            # The response might be a generator or have different formats
            if hasattr(response, 'text'):
                return response.text
            elif isinstance(response, dict):
                if 'text' in response:
                    return response['text']
                elif 'content' in response:
                    return response['content']
            elif isinstance(response, str):
                return response
            else:
                # Try to convert to string
                return str(response)
                
        except Exception as e:
            error_msg = str(e)
            
            # Provide helpful error messages
            if "agent_id" in error_msg.lower() or "not found" in error_msg.lower():
                return (
                    "❌ Error: Agent not found. Please verify your ELEVENLABS_AGENT_ID "
                    "in the .env file or in src/utils/elevenlabs_agent.py"
                )
            elif "api key" in error_msg.lower() or "unauthorized" in error_msg.lower():
                return (
                    "❌ Error: Invalid API key. Please check your ELEVENLABS_API_KEY "
                    "in the .env file."
                )
            else:
                return f"❌ Error communicating with agent: {error_msg}"
    
    def end_conversation(self):
        """End the current conversation."""
        if self.conversation:
            try:
                self.conversation.end_session()
            except Exception as e:
                print(f"Error ending conversation: {e}")
            self.conversation = None


# Global agent instance
_agent = None


def get_agent():
    """Get or create the global agent instance."""
    global _agent
    if _agent is None:
        _agent = EULegislationAgent()
    return _agent


def chat_with_agent(message: str) -> str:
    """
    Send a message to the EU Legislation agent and get a response.
    
    This is the main function to be called from the UI.
    
    Args:
        message: User's question about EU agricultural legislation
        
    Returns:
        str: Agent's response
    """
    agent = get_agent()
    return agent.send_message(message)


def reset_conversation():
    """Reset the conversation with the agent."""
    global _agent
    if _agent:
        _agent.end_conversation()
        _agent = None