Spaces:
Runtime error
Runtime error
Commit
·
fceaadb
1
Parent(s):
de1ac8c
Upload 3 files
Browse files- app.py +97 -0
- requirements.txt +3 -0
- utils.py +46 -0
app.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import openai
|
3 |
+
import json
|
4 |
+
import time
|
5 |
+
from utils import ask_datorama
|
6 |
+
import os
|
7 |
+
|
8 |
+
openai.api_key = os.environ["OPENAI_API_KEY"]
|
9 |
+
|
10 |
+
# Tu función get_trip aquí
|
11 |
+
|
12 |
+
context = [{'role': 'system', 'content': """
|
13 |
+
Eres NateevoGPT, un servicio automatizado para ayudar a los usuarios a responder cualquier pregunta sobre su información de Marketing hecho por Nateevo.
|
14 |
+
Nateevo es la mejor compañía de consultoría de Marketing Digital que opera en todo el mundo, experta en Salesforce Marketing Cloud Intelligence, Salesforce Marketing Cloud Engagement, Salesforce Data Cloud, Google Analytics, Adobe Analytics, etc...
|
15 |
+
Primero, saludas al usuario diciendo tu nombre, luego le solicitas que haga una pregunta para iniciar la conversación.
|
16 |
+
Te aseguras de que la pregunta sea suficientemente clara para que puedas responderla. Si la pregunta es ambigua le pides al usuario más claridad.
|
17 |
+
Respondes en un estilo amigable, conversacional y breve. \
|
18 |
+
"""}]
|
19 |
+
|
20 |
+
|
21 |
+
def get_completion_from_messages(messages, temperature=0.1):
|
22 |
+
functions = [{
|
23 |
+
"name": "ask_datorama",
|
24 |
+
"description": "Responde a una pregunta sobre los datos de marketing del cliente que están almacenados en Salesforce Marketing Cloud Intelligence.",
|
25 |
+
"parameters": {
|
26 |
+
"type": "object",
|
27 |
+
"properties": {
|
28 |
+
"question": {
|
29 |
+
"type": "string",
|
30 |
+
"description": "La pregunta que tiene el usuario sobre sus datos de marketing.",
|
31 |
+
}
|
32 |
+
},
|
33 |
+
"required": ["question"],
|
34 |
+
}
|
35 |
+
}]
|
36 |
+
|
37 |
+
response = openai.ChatCompletion.create(
|
38 |
+
model="gpt-4-0613",
|
39 |
+
messages=messages,
|
40 |
+
functions=functions,
|
41 |
+
function_call="auto",
|
42 |
+
)
|
43 |
+
response_message = response["choices"][0]["message"]
|
44 |
+
|
45 |
+
if response_message.get("function_call"):
|
46 |
+
available_functions = {
|
47 |
+
"ask_datorama": ask_datorama,
|
48 |
+
}
|
49 |
+
function_name = response_message["function_call"]["name"]
|
50 |
+
function_to_call = available_functions[function_name]
|
51 |
+
function_args = json.loads(
|
52 |
+
response_message["function_call"]["arguments"])
|
53 |
+
function_response = function_to_call(
|
54 |
+
question=function_args.get("question")
|
55 |
+
)
|
56 |
+
|
57 |
+
messages.append(response_message)
|
58 |
+
messages.append(
|
59 |
+
{
|
60 |
+
"role": "function",
|
61 |
+
"name": function_name,
|
62 |
+
"content": function_response,
|
63 |
+
}
|
64 |
+
)
|
65 |
+
second_response = openai.ChatCompletion.create(
|
66 |
+
model="gpt-4-0613",
|
67 |
+
messages=messages
|
68 |
+
)
|
69 |
+
|
70 |
+
if 'second_response' not in locals():
|
71 |
+
messages.append(response_message)
|
72 |
+
second_response = openai.ChatCompletion.create(
|
73 |
+
model="gpt-4-0613",
|
74 |
+
messages=messages
|
75 |
+
)
|
76 |
+
return second_response.choices[0].message["content"]
|
77 |
+
|
78 |
+
|
79 |
+
def respuesta_chatbot(message, chat_history):
|
80 |
+
context.append({'role': 'user', 'content': f"{message}"})
|
81 |
+
response = get_completion_from_messages(context)
|
82 |
+
context.append({'role': 'assistant', 'content': f"{response}"})
|
83 |
+
chat_history.append((message, response))
|
84 |
+
time.sleep(2)
|
85 |
+
return "", chat_history
|
86 |
+
|
87 |
+
|
88 |
+
with gr.Blocks() as demo:
|
89 |
+
title_and_desc = gr.Markdown(
|
90 |
+
"# NateevoGPT \n Nateevo GPT es un servicio automatizado para responder una pregunta de tus datos de marketing usando la información de Salesforce Marketing Cloud Intelligence.")
|
91 |
+
chatbot = gr.Chatbot()
|
92 |
+
msg = gr.Textbox()
|
93 |
+
clear = gr.ClearButton([msg, chatbot])
|
94 |
+
|
95 |
+
msg.submit(respuesta_chatbot, [msg, chatbot], [msg, chatbot])
|
96 |
+
|
97 |
+
demo.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
openai==0.27.8
|
2 |
+
requests==2.28.0
|
3 |
+
pandas==1.4.2
|
utils.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import openai
|
2 |
+
import json
|
3 |
+
import requests
|
4 |
+
import pandas as pd
|
5 |
+
|
6 |
+
|
7 |
+
def ask_datorama(question):
|
8 |
+
|
9 |
+
payload_formation = openai.ChatCompletion.create(
|
10 |
+
model="gpt-4",
|
11 |
+
messages=[{"role": "system", "content": "Given an input question in any language, respond with the relevant dimensions, metrics, and filters. Be creative but the response must be in the correct JSON format. You can only use dimensions called \"Campaign Name\", \"Campaign Category\", \"Media Buy Name\", \"Day\", \"Weekday\",\"Month\", \"Creative Name\", \"Media Buy Size\". You can only use measurements called \"Impressions\", \"Clicks\", \"Revenue\", \"CTR\", \"CPM\", \"Media Cost\", \"Conversion CPA\", \"Total Conversions\", \"Conversion Rate\", \"Conversion ROAS\". The dateRange variable can be one of the following: \"CUSTOM\",\"CUSTOM_ON_GOING\", \"YESTERDAY\", \"WEEK_TO_DATE\", \"BI_WEEK_TO_DATE\", \"MONTH_TO_DATE\", \"QUARTER_TO_DATE\", \"YEAR_TO_DATE\", \"WEEK_TO_DATE_CUSTOM\", \"BI_WEEK_TO_DATE_CUSTOM\", \"MONTH_TO_DATE_CUSTOM\", \"QUARTER_TO_DATE_CUSTOM\", \"YEAR_TO_DATE_CUSTOM\", \"PREV_WEEK\", \"PREV_BI_WEEK\", \"PREV_MONTH\", \"PREV_QUARTER\", \"PREV_YEAR\", \"PREV_WEEK_CUSTOM\", \"PREV_BI_WEEK_CUSTOM\", \"PREV_MONTH_CUSTOM\", \"PREV_QUARTER_CUSTOM\", \"PREV_YEAR_CUSTOM\", \"LAST_WEEK\", \"LAST_BI_WEEK\", \"LAST_MONTH\", \"LAST_3_MONTHS\", \"THIS_WEEK\", \"THIS_BI_WEEK\", \"THIS_MONTH\", \"THIS_QUARTER\", \"THIS_YEAR\", \"THIS_WEEK_CUSTOM\", \"THIS_BI_WEEK_CUSTOM\", \"THIS_MONTH_CUSTOM\", \"THIS_QUARTER_CUSTOM\", \"THIS_YEAR_CUSTOM\".\n\nInput: \"What is the day that had more than 1000 impressions with the most clicks of 2021?\"\nOutput: {\n \"workspaceId\": 77283,\n \"dateRange\": \"CUSTOM\",\n \"startDate\": \"2021-01-01\",\n \"endDate\": \"2021-12-31\",\n \"measurements\": [\n {\n \"name\": \"Clicks\"\n },\n {\n \"name\": \"Impressions\"\n }\n ],\n \"dimensions\": [\n \"Day\"\n ],\n \"numberMeasurementFilter\": [\n {\n \"fieldName\": \"Impressions\",\n \"operator\": \"GREATER\",\n \"val\": 1000\n }\n ],\n \"sortConfig\": [\n {\n \"sortBy\": \"Clicks\",\n \"sortOrder\": \"DESC\"\n }\n ],\n \"topResults\": \"1\",\n \"groupOthers\": false,\n \"topPerDimension\": true,\n \"totalDimensions\": []\n}\n\nInput: \"Cuál es la campaña con el mayor número de impresiones del último mes?\"\nOutput: {\n \"workspaceId\": 77283,\n \"dateRange\": \"LAST_MONTH\",\n \"measurements\": [\n {\n \"name\": \"Impressions\"\n }\n ],\n \"dimensions\": [\n \"Campaign Name\"\n ],\n \"sortConfig\": [\n {\n \"sortBy\": \"Impressions\",\n \"sortOrder\": \"DESC\"\n }\n ],\n \"topResults\": \"1\",\n \"groupOthers\": false,\n \"topPerDimension\": true,\n \"totalDimensions\": []\n}"},
|
12 |
+
{"role": "user", "content": question}],
|
13 |
+
temperature=0.2
|
14 |
+
)
|
15 |
+
print(question)
|
16 |
+
print(payload_formation.choices[0].message["content"])
|
17 |
+
|
18 |
+
url = "https://api.datorama.com/v1/query"
|
19 |
+
|
20 |
+
payload = payload_formation.choices[0].message["content"]
|
21 |
+
headers = {
|
22 |
+
'Authorization': 'dato-api-c7637555-2d5c-410c-818f-84bf8125db4c',
|
23 |
+
'Content-Type': 'application/json'
|
24 |
+
}
|
25 |
+
|
26 |
+
response = requests.request("POST", url, headers=headers, data=payload)
|
27 |
+
data = json.loads(response.text)
|
28 |
+
|
29 |
+
print(data)
|
30 |
+
|
31 |
+
columns = [dct for dct in data['queryResponseData']['headers']]
|
32 |
+
df = pd.DataFrame(data['queryResponseData']['rows'], columns=columns)
|
33 |
+
x = df.to_string(index=False).split('\n')
|
34 |
+
vals = ['|'.join(ele.split()) for ele in x]
|
35 |
+
vals = '\n'.join(str(item) for item in vals)
|
36 |
+
|
37 |
+
answer = openai.ChatCompletion.create(
|
38 |
+
model="gpt-4",
|
39 |
+
messages=[{"role": "system", "content": "Answer the question in long form for any given language using the pipe-separated dataframe."},
|
40 |
+
{"role": "user", "content": "What was the campaign that generated the most impressions during last month?\nCampaign Name|Impressions\nCampaignA|12345"},
|
41 |
+
{"role": "assistant", "content": "The campaign that generated the most impressions during last month was Campaign A with 12345 impressions."},
|
42 |
+
{"role": "user", "content": question+"\n"+vals}],
|
43 |
+
temperature=0.4
|
44 |
+
)
|
45 |
+
|
46 |
+
return answer.choices[0].message["content"]
|