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='soumyabrata.das2@cognizant.com.sandbox1', 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)