Spaces:
Paused
Paused
File size: 6,369 Bytes
6bd6d10 fd4d0c5 6bd6d10 fd4d0c5 6bd6d10 46d4994 6bd6d10 fd89d01 6bd6d10 fd89d01 6bd6d10 fd4d0c5 6bd6d10 fd4d0c5 6bd6d10 46d4994 6bd6d10 fd4d0c5 6bd6d10 fd4d0c5 6bd6d10 fd4d0c5 6bd6d10 46d4994 6bd6d10 fd89d01 6bd6d10 2008ddc 6bd6d10 fd89d01 6bd6d10 fd89d01 46d4994 fd89d01 6bd6d10 fd89d01 6bd6d10 fd89d01 7936edc 6bd6d10 7936edc 6bd6d10 fd4d0c5 6bd6d10 fd4d0c5 6bd6d10 1dda4f2 5080028 |
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 165 166 167 168 169 170 171 172 |
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) |