sf-voicebot / app.py
EinsteinCoder's picture
Update app.py
2008ddc
raw
history blame
6.37 kB
from flask import Flask, request, render_template
from twilio.twiml.voice_response import VoiceResponse, Gather
import openai
import csv
import os
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")
# 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 remember them 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 amd the mode of refund hw wants, clarify 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/WhatApp. Ask for image uploads for product investigations.
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.2,
model_name='gpt-3.5-turbo',
max_tokens=128
)
llm30 = OpenAI(
temperature=0.1,
max_tokens=128
)
memory = ConversationBufferMemory(memory_key="chat_history")
conversations = ConversationChain(
prompt=prompt,
llm=llm35,
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")
# 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 Voice Services !")
gather.pause(length=1)
gather.say("Hi, I am Lisa, from customer service")
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
@app.route("/incoming_call", methods=["POST"])
def incoming_call():
return handle_incoming_call()
# Define a route to handle user input
@app.route('/process_input', methods=['POST'])
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)
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
openai.api_key = os.environ.get("OPENAI_KEY")
def get_case_summary(conv_detail):
chatresponse_desc = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
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
return case_desc
def get_case_subject(conv_detail):
chatresponse_subj = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an Text Summarizer."},
{"role": "user", "content": "You need to summarise the conversation between an agent and customer in 10 words mentioned below for case subject."},
{"role": "user", "content": conv_detail}
]
)
case_subj = chatresponse_subj.choices[0].message.content
return case_subj
# Define a function to create a case record in Salesforce
def create_case(conv_hist):
desc = get_case_summary(conv_hist)
subj = get_case_subject(conv_hist)
case_data = {
'Subject': 'Voice Bot Case for Rob :' + subj ,
'Description': desc,
'Status': 'New',
'Origin': 'Voice Bot',
'Voice_Call_Conversation__c': conv_hist ,
'Voice_Call_Id__c': conversation_id,
'ContactId': '003B000000NLHQ1IAP'
}
sf.Case.create(case_data)
@app.route('/')
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)