File size: 5,168 Bytes
6bd6d10
 
 
 
 
 
fd4d0c5
6bd6d10
fd4d0c5
6bd6d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd4d0c5
6bd6d10
 
 
 
 
 
fd4d0c5
6bd6d10
 
 
 
 
fd4d0c5
6bd6d10
fd4d0c5
6bd6d10
 
 
 
 
fd4d0c5
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

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__)

# 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 by one questions and remember over the phone and provide a friendly conversational responses.
For Product Complaint: Ask questions about product they purchased, when they bought it, what issue occurred, and query for any adverse reaction happened 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. 
Once you collect all the information, summarize it at the end and repeat it back to the caller.

{chat_history}
Human: {input}
AI: 

"""

prompt = PromptTemplate(
    input_variables=["chat_history", "input"],
    template=template
)

llm35 = ChatOpenAI(
    temperature=0.2, 
    openai_api_key='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',
    model_name='gpt-3.5-turbo',
    max_tokens=128
)

llm30 = OpenAI(
    temperature=0.1, 
    openai_api_key='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',
    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 = Salesforce(username='[email protected]', password='April-2023', security_token='1nic31g1YZ2V3dQRhCzXheAa',instance_url='https://marketing-comm.lightning.force.com')
#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("User : " +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("Agent: " + ai_response)
        gather = Gather(input='speech', speechTimeout='auto', action='/process_input')
        response.append(gather)
   
    return str(response)



# Define a function to create a case record in Salesforce
def create_case(conv_hist):
        case_data = {
            'Subject': 'Voice Bot Case',
            #'Description': 'Conversation with voice bot',
            'Status': 'New',
            'Origin': 'Voice Bot',
            'Description': conv_hist
            #'Conversation_History__c': ''
        }   
        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)