import os
from dotenv import load_dotenv
import openai
import langchain
import azure.cognitiveservices.speech as speechsdk
import elevenlabs
import json
import requests

from langchain.agents.agent_toolkits import SQLDatabaseToolkit
from langchain.sql_database import SQLDatabase
from langchain.agents import AgentExecutor
from langchain.agents import create_sql_agent
from langchain import LLMMathChain, OpenAI, SQLDatabase, SerpAPIWrapper
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
from langchain.callbacks.streaming_stdout_final_only import (
    FinalStreamingStdOutCallbackHandler,
)

os.environ["OPENAI_API_KEY"] =""
os.environ["SQL_SERVER_USERNAME"] = "" 
os.environ["SQL_SERVER_ENDPOINT"] = ""
os.environ["SQL_SERVER_PASSWORD"] = ""  
os.environ["SQL_SERVER_DATABASE"] = ""
os.environ["SERPAPI_API_KEY"] =""

speech_key, service_region = "", "eastus"
speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config)

from sqlalchemy import create_engine
from sqlalchemy.engine.url import URL


db_config = {  
    'drivername': 'mssql+pyodbc',  
    'username': os.environ["SQL_SERVER_USERNAME"] + '@' + os.environ["SQL_SERVER_ENDPOINT"],  
    'password': os.environ["SQL_SERVER_PASSWORD"],  
    'host': os.environ["SQL_SERVER_ENDPOINT"],  
    'port': 1433,  
    'database': os.environ["SQL_SERVER_DATABASE"],  
    'query': {'driver': 'ODBC Driver 17 for SQL Server'}  
} 

from langchain.agents import create_sql_agent


llm = OpenAI(streaming=True,temperature=0)
search = SerpAPIWrapper()
db_url = URL.create(**db_config)
db = SQLDatabase.from_uri(db_url)
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
toolkit = SQLDatabaseToolkit(db=db, llm=llm)
db_chain = create_sql_agent(
    llm=llm,
    toolkit=toolkit,
    verbose=True,
    agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
)
tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events. You should ask targeted questions"
    ),
    Tool(
        name="FooBar-DB",
        func=db_chain.run,
        description="useful to answer questions about John in the database"
    )
]

while True:
    print("Talk now")
    result = speech_recognizer.recognize_once()
    print("Recognized: {}".format(result.text))
    message = format(result.text)
    agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True,)
    response = agent(
    {
        "input": result.text
    }
)
    response["output"]
    print(response["output"])
    audio_stream = elevenlabs.generate(text=response["output"],voice="Matthew", stream=True)
    output = elevenlabs.stream(audio_stream)


langchain.agents.initialize_agent langchain.agents.agent_toolkits.SQLDatabaseToolkit langchain.agents.create_sql_agent langchain.chat_models.ChatOpenAI langchain.SerpAPIWrapper langchain.agents.Tool langchain.SQLDatabase.from_uri langchain.OpenAI
[((968, 1038), 'azure.cognitiveservices.speech.SpeechConfig', 'speechsdk.SpeechConfig', ([], {'subscription': 'speech_key', 'region': 'service_region'}), '(subscription=speech_key, region=service_region)\n', (990, 1038), True, 'import azure.cognitiveservices.speech as speechsdk\n'), ((1059, 1114), 'azure.cognitiveservices.speech.SpeechRecognizer', 'speechsdk.SpeechRecognizer', ([], {'speech_config': 'speech_config'}), '(speech_config=speech_config)\n', (1085, 1114), True, 'import azure.cognitiveservices.speech as speechsdk\n'), ((1632, 1669), 'langchain.OpenAI', 'OpenAI', ([], {'streaming': '(True)', 'temperature': '(0)'}), '(streaming=True, temperature=0)\n', (1638, 1669), False, 'from langchain import LLMMathChain, OpenAI, SQLDatabase, SerpAPIWrapper\n'), ((1678, 1694), 'langchain.SerpAPIWrapper', 'SerpAPIWrapper', ([], {}), '()\n', (1692, 1694), False, 'from langchain import LLMMathChain, OpenAI, SQLDatabase, SerpAPIWrapper\n'), ((1704, 1727), 'sqlalchemy.engine.url.URL.create', 'URL.create', ([], {}), '(**db_config)\n', (1714, 1727), False, 'from sqlalchemy.engine.url import URL\n'), ((1733, 1761), 'langchain.SQLDatabase.from_uri', 'SQLDatabase.from_uri', (['db_url'], {}), '(db_url)\n', (1753, 1761), False, 'from langchain import LLMMathChain, OpenAI, SQLDatabase, SerpAPIWrapper\n'), ((1768, 1821), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'temperature': '(0)', 'model': '"""gpt-3.5-turbo-0613"""'}), "(temperature=0, model='gpt-3.5-turbo-0613')\n", (1778, 1821), False, 'from langchain.chat_models import ChatOpenAI\n'), ((1832, 1866), 'langchain.agents.agent_toolkits.SQLDatabaseToolkit', 'SQLDatabaseToolkit', ([], {'db': 'db', 'llm': 'llm'}), '(db=db, llm=llm)\n', (1850, 1866), False, 'from langchain.agents.agent_toolkits import SQLDatabaseToolkit\n'), ((1878, 1989), 'langchain.agents.create_sql_agent', 'create_sql_agent', ([], {'llm': 'llm', 'toolkit': 'toolkit', 'verbose': '(True)', 'agent_type': 'AgentType.ZERO_SHOT_REACT_DESCRIPTION'}), '(llm=llm, toolkit=toolkit, verbose=True, agent_type=\n    AgentType.ZERO_SHOT_REACT_DESCRIPTION)\n', (1894, 1989), False, 'from langchain.agents import create_sql_agent\n'), ((2018, 2180), 'langchain.agents.Tool', 'Tool', ([], {'name': '"""Search"""', 'func': 'search.run', 'description': '"""useful for when you need to answer questions about current events. You should ask targeted questions"""'}), "(name='Search', func=search.run, description=\n    'useful for when you need to answer questions about current events. You should ask targeted questions'\n    )\n", (2022, 2180), False, 'from langchain.agents import initialize_agent, Tool\n'), ((2208, 2323), 'langchain.agents.Tool', 'Tool', ([], {'name': '"""FooBar-DB"""', 'func': 'db_chain.run', 'description': '"""useful to answer questions about John in the database"""'}), "(name='FooBar-DB', func=db_chain.run, description=\n    'useful to answer questions about John in the database')\n", (2212, 2323), False, 'from langchain.agents import initialize_agent, Tool\n'), ((2528, 2604), 'langchain.agents.initialize_agent', 'initialize_agent', (['tools', 'llm'], {'agent': 'AgentType.OPENAI_FUNCTIONS', 'verbose': '(True)'}), '(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True)\n', (2544, 2604), False, 'from langchain.agents import initialize_agent, Tool\n'), ((2743, 2817), 'elevenlabs.generate', 'elevenlabs.generate', ([], {'text': "response['output']", 'voice': '"""Matthew"""', 'stream': '(True)'}), "(text=response['output'], voice='Matthew', stream=True)\n", (2762, 2817), False, 'import elevenlabs\n'), ((2830, 2861), 'elevenlabs.stream', 'elevenlabs.stream', (['audio_stream'], {}), '(audio_stream)\n', (2847, 2861), False, 'import elevenlabs\n')]