Spaces:
Paused
Paused
from flask import Flask, request, render_template | |
from twilio.twiml.voice_response import VoiceResponse, Gather | |
import openai | |
import csv | |
import os | |
import requests | |
from simple_salesforce import Salesforce | |
from langchain import OpenAI | |
from langchain.chat_models import ChatOpenAI | |
from langchain.chains import LLMChain, ConversationChain | |
from langchain import PromptTemplate | |
from langchain import HuggingFaceHub | |
from langchain.chains.conversation.memory import (ConversationBufferMemory, | |
ConversationSummaryMemory, | |
ConversationBufferWindowMemory, | |
ConversationKGMemory,ConversationSummaryBufferMemory) | |
app = Flask(__name__) | |
os.environ['OPENAI_API_KEY'] = os.environ.get("OPENAI_KEY") | |
openai.api_key = os.environ.get("OPENAI_KEY") | |
# Set up the LangChain | |
template = """Answer the question based on the context below. | |
Context: You are Lisa, a loyal helpful service agent, appointed for SuperFoods Petcare Company. | |
No introduction required. | |
Your goal ask one question at a time and provide a friendly conversational responses to the customer. | |
For Product Complaint: Ask questions about product they purchased, when they bought it, what issue occured with it. Query for any adverse reaction happened to his pet due to the product. | |
For Returns: Ask for the cause of return, if not asked aready, then tell him about the 10-day return policy, after which it's non-returnable. | |
For Refunds: Ask about the product issues and the mode of refund he wants, clarify him the refunds will happen within 2-3 business days. | |
A case for will be created for all scenarios, and the caller will be notified over Email or WhatsApp. | |
Do not answer anything outside your role, and apologize for any unknown questions. | |
Past Conversations: {chat_history} | |
Human: {input} | |
AI: | |
""" | |
prompt = PromptTemplate( | |
input_variables=["chat_history", "input"], | |
template=template | |
) | |
llm35 = ChatOpenAI( | |
temperature=0, | |
model_name='gpt-3.5-turbo', | |
max_tokens=128 | |
) | |
llm30 = OpenAI( | |
temperature=0, | |
max_tokens=128 | |
) | |
memory = ConversationBufferMemory(memory_key="chat_history") | |
conversations = ConversationChain( | |
prompt=prompt, | |
llm=llm30, | |
memory=memory, | |
verbose=False | |
) | |
# Set up the Salesforce API | |
#sf_user = os.environ.get("SF_USER") | |
#sf_pwd = os.environ.get("SF_PWD") | |
#sf_token = os.environ.get("SF_TOKEN") | |
#sf_instance = os.environ.get("SF_INSTANCE") | |
#sf = Salesforce(username=sf_user, password=sf_pwd, security_token=sf_token,instance_url=sf_instance) | |
#print(sf.headers) | |
#print("Successfully Connected to Salesforce") | |
conversation_id = '' | |
# Define a function to handle incoming calls | |
def handle_incoming_call(): | |
response = VoiceResponse() | |
gather = Gather(input='speech', speechTimeout='auto', action='/process_input') | |
gather.say("Welcome to the SuperFood Customer Services !") | |
gather.pause(length=1) | |
gather.say("Hi, I am Lisa, from customer desk") | |
gather.pause(length=0) | |
gather.say("May i know who i am talking to?") | |
response.append(gather) | |
return str(response) | |
# Define a route to handle incoming calls | |
def incoming_call(): | |
return handle_incoming_call() | |
# Define a route to handle user input | |
def process_input(): | |
user_input = request.form['SpeechResult'] | |
print("Rob : " +user_input) | |
conversation_id = request.form['CallSid'] | |
#print("Conversation Id: " + conversation_id) | |
if user_input.lower() in ['thank you', 'thanks.', 'bye.', 'goodbye.','no thanks.','no, thank you.','i m good.','no, i m good.','same to you.','no, thanks.','thank you.']: | |
response = VoiceResponse() | |
response.say("Thank you for using our service. Goodbye!") | |
response.hangup() | |
print("Hanged-up") | |
create_case(conversations.memory.buffer,conversation_id) | |
print("Case created successfully !!") | |
else: | |
response = VoiceResponse() | |
ai_response=conversations.predict(input=user_input) | |
response.say(ai_response) | |
print("Bot: " + ai_response) | |
gather = Gather(input='speech', speechTimeout='auto', action='/process_input') | |
response.append(gather) | |
return str(response) | |
# For Case Summary and Subject | |
def get_case_summary(conv_detail): | |
#chatresponse_desc = openai.ChatCompletion.create( | |
#model="gpt-3.5-turbo", | |
#temperature=0, | |
#max_tokens=128, | |
#messages=[ | |
# {"role": "system", "content": "You are an Text Summarizer."}, | |
# {"role": "user", "content": "You need to summarise the conversation between an agent and customer mentioned below. Remember to keep the Product Name, Customer Tone and other key elements from the convsersation"}, | |
# {"role": "user", "content": conv_detail} | |
#] | |
#) | |
#case_desc = chatresponse_desc.choices[0].message.content | |
chatresponse_desc = completion.create( | |
model = 'text-davinci-003', | |
prompt = 'Summarise the conversation between an agent and customer.Remember to keep the Product Name, Customer Tone and other key elements from the convsersation.Here is the conversation: ' + conv_detail, | |
temperature = 0, | |
top_p =1, | |
best_of=1, | |
max_tokens=256 | |
) | |
case_desc = chatresponse_desc.choices[0].text.strip() | |
return case_desc | |
def get_case_subject(conv_detail): | |
#chatresponse_subj = openai.ChatCompletion.create( | |
#model="gpt-3.5-turbo", | |
#temperature=0, | |
#max_tokens=32, | |
#messages=[ | |
# {"role": "system", "content": "You are an Text Summarizer."}, | |
# {"role": "user", "content": "You need to summarise the conversation between an agent and customer in 15 words mentioned below for case subject."}, | |
# {"role": "user", "content": conv_detail} | |
#] | |
#) | |
#case_subj = chatresponse_subj.choices[0].message.content | |
chatresponse_subj = completion.create( | |
model = 'text-davinci-003', | |
prompt = 'Summarise the conversation between an agent and customer in 15 words mentioned below for Case Subject. Here is the conversation: ' + conv_detail, | |
temperature = 0, | |
top_p =1, | |
best_of=1, | |
max_tokens=256 | |
) | |
case_subj = chatresponse_subj.choices[0].text.strip() | |
return case_subj | |
# Define a function to create a case record in Salesforce | |
def create_case(conv_hist,conv_id): | |
sf_user = os.environ.get("SF_USER") | |
sf_pwd = os.environ.get("SF_PWD") | |
sf_token = os.environ.get("SF_TOKEN") | |
sf_instance = os.environ.get("SF_INSTANCE") | |
session = requests.Session() | |
sf = Salesforce(username=sf_user, password=sf_pwd, security_token=sf_token,instance_url=sf_instance,session=session) | |
desc = get_case_summary(conv_hist) | |
subj = get_case_subject(conv_hist) | |
case_data = { | |
'Subject': 'Voice Bot Case: ' + subj , | |
'Description': desc, | |
'Status': 'New', | |
'Origin': 'Voice Bot', | |
'Voice_Call_Conversation__c': conv_hist , | |
'Voice_Call_Id__c': conv_id, | |
'ContactId': '003B000000NLHQ1IAP' | |
} | |
sf.Case.create(case_data) | |
def index(): | |
return """Flask Server running with Twilio Voice & ChatGPT integrated with Salesforce for Case Creation. Call +1-320-313-9061 to talk to the AI Voice Bot.""" | |
if __name__ == '__main__': | |
app.run(debug=False,host='0.0.0.0',port=5050) | |
uvicorn.run(app,host='0.0.0.0', port=5050) |