ibombonato commited on
Commit
170eb66
·
verified ·
1 Parent(s): 094370f

Refactor: Pass API keys directly to Gradio app and CrewAI agents besides use ENV.

Browse files
Files changed (1) hide show
  1. app.py +24 -31
app.py CHANGED
@@ -4,30 +4,19 @@ import requests
4
  from crewai import Agent, Task, Crew, Process
5
  from crewai_tools import ScrapeWebsiteTool
6
  from crewai.tools import BaseTool
 
7
 
8
- os.environ["OPENAI_MODEL_NAME"] = "gpt-4o-mini"
9
-
10
- # --- API Key Management ---
11
- def get_api_keys():
12
- return {
13
- "OPENAI_API_KEY": os.getenv("OPENAI_API_KEY", ""),
14
- "NATURA_API_TOKEN": os.getenv("NATURA_API_TOKEN", "")
15
- }
16
-
17
- def set_api_key(openai_key: str, natura_token: str):
18
- os.environ["OPENAI_API_KEY"] = openai_key
19
- os.environ["NATURA_API_TOKEN"] = natura_token
20
- return "API keys saved successfully!"
21
 
22
  # --- CrewAI Integration ---
23
 
24
  class ShortenerTool(BaseTool):
25
  name: str = "URL Shortener Tool"
26
  description: str = "Generates a short version of a given URL using an external API."
 
27
 
28
  def _run(self, original_url: str) -> str:
29
  api_url = "https://sales-mgmt-cb-bff-apigw.prd.naturacloud.com/cb-bff-cms/cms/shortener"
30
- headers = {"authorization": f"Bearer {os.getenv('NATURA_API_TOKEN')}", "content-type": "application/json"}
31
  payload = {"url": original_url}
32
 
33
  try:
@@ -57,9 +46,11 @@ class CalculateDiscountedPriceTool(BaseTool):
57
  return round(discounted_price, 2)
58
 
59
  class SocialMediaCrew:
60
- def __init__(self):
 
 
61
  self.scrape_tool = ScrapeWebsiteTool()
62
- self.shortener_tool = ShortenerTool()
63
  self.calculate_discounted_price_tool = CalculateDiscountedPriceTool()
64
 
65
  self.product_analyst = Agent(
@@ -68,7 +59,8 @@ class SocialMediaCrew:
68
  backstory=("You are an expert in analyzing product pages and extracting the most important information. You can identify the product name, its main features, and the target audience."),
69
  verbose=True,
70
  tools=[self.scrape_tool, self.shortener_tool, self.calculate_discounted_price_tool],
71
- allow_delegation=False
 
72
  )
73
 
74
  self.social_media_copywriter = Agent(
@@ -76,7 +68,8 @@ class SocialMediaCrew:
76
  goal='Create a compelling social media post in Portuguese to sell the product',
77
  backstory=("You are a creative copywriter specialized in the beauty and fragrance market. You know how to craft posts that are engaging, persuasive, and tailored for a Portuguese-speaking audience. You are an expert in using emojis and hashtags to increase engagement."),
78
  verbose=True,
79
- allow_delegation=False
 
80
  )
81
 
82
  def run_crew(self, product_url: str, main_cupom: str, main_cupom_discount_percentage: float, cupom_1: str, cupom_2: str) -> str:
@@ -136,7 +129,8 @@ Ensure a URL is always present in the output. Include a clear call to action and
136
  crew = Crew(
137
  agents=[self.product_analyst, self.social_media_copywriter],
138
  tasks=[analyze_product_task, create_post_task],
139
- process=Process.sequential
 
140
  )
141
 
142
  print(f"Crew is kicking off for URL: {product_url}")
@@ -144,12 +138,11 @@ Ensure a URL is always present in the output. Include a clear call to action and
144
  return result
145
 
146
  # --- Gradio Interface ---
147
- def generate_ad(product_url: str, main_cupom: str, main_cupom_discount_percentage: float, cupom_1: str, cupom_2: str):
148
- api_keys = get_api_keys()
149
- if not api_keys["OPENAI_API_KEY"] or not api_keys["NATURA_API_TOKEN"]:
150
  return "Please configure your API keys in the settings section below."
151
 
152
- social_media_crew = SocialMediaCrew()
153
  result = social_media_crew.run_crew(product_url, main_cupom, main_cupom_discount_percentage, cupom_1, cupom_2)
154
 
155
  if result == "INVALID_URL":
@@ -175,13 +168,13 @@ with gr.Blocks() as demo:
175
 
176
  with gr.Tab("Settings"):
177
  gr.Markdown("### ⚙️ API Key Settings")
178
- gr.Markdown("Enter your API keys below. These will be stored as environment variables for the running application.")
179
- openai_key_input = gr.Textbox(label="OPENAI_API_KEY", type="password", value=os.getenv("OPENAI_API_KEY"))
180
- natura_token_input = gr.Textbox(label="NATURA_API_TOKEN", type="password", value=os.getenv("NATURA_API_TOKEN"))
181
- save_button = gr.Button("Save Keys")
182
- settings_message = gr.Markdown()
183
- save_button.click(set_api_key, inputs=[openai_key_input, natura_token_input], outputs=settings_message)
184
-
185
- generate_button.click(generate_ad, inputs=[url_input, main_cupom_input, main_cupom_discount_percentage_input, cupom_1_input, cupom_2_input], outputs=ad_output)
186
 
187
  demo.launch()
 
4
  from crewai import Agent, Task, Crew, Process
5
  from crewai_tools import ScrapeWebsiteTool
6
  from crewai.tools import BaseTool
7
+ from langchain_openai import ChatOpenAI
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  # --- CrewAI Integration ---
11
 
12
  class ShortenerTool(BaseTool):
13
  name: str = "URL Shortener Tool"
14
  description: str = "Generates a short version of a given URL using an external API."
15
+ natura_api_token: str
16
 
17
  def _run(self, original_url: str) -> str:
18
  api_url = "https://sales-mgmt-cb-bff-apigw.prd.naturacloud.com/cb-bff-cms/cms/shortener"
19
+ headers = {"authorization": f"Bearer {self.natura_api_token}", "content-type": "application/json"}
20
  payload = {"url": original_url}
21
 
22
  try:
 
46
  return round(discounted_price, 2)
47
 
48
  class SocialMediaCrew:
49
+ def __init__(self, openai_api_key: str, natura_api_token: str):
50
+ self.openai_api_key = openai_api_key
51
+ self.natura_api_token = natura_api_token
52
  self.scrape_tool = ScrapeWebsiteTool()
53
+ self.shortener_tool = ShortenerTool(natura_api_token=self.natura_api_token)
54
  self.calculate_discounted_price_tool = CalculateDiscountedPriceTool()
55
 
56
  self.product_analyst = Agent(
 
59
  backstory=("You are an expert in analyzing product pages and extracting the most important information. You can identify the product name, its main features, and the target audience."),
60
  verbose=True,
61
  tools=[self.scrape_tool, self.shortener_tool, self.calculate_discounted_price_tool],
62
+ allow_delegation=False,
63
+ llm=ChatOpenAI(api_key=self.openai_api_key, model="gpt-4o-mini")
64
  )
65
 
66
  self.social_media_copywriter = Agent(
 
68
  goal='Create a compelling social media post in Portuguese to sell the product',
69
  backstory=("You are a creative copywriter specialized in the beauty and fragrance market. You know how to craft posts that are engaging, persuasive, and tailored for a Portuguese-speaking audience. You are an expert in using emojis and hashtags to increase engagement."),
70
  verbose=True,
71
+ allow_delegation=False,
72
+ llm=ChatOpenAI(api_key=self.openai_api_key, model="gpt-4o-mini")
73
  )
74
 
75
  def run_crew(self, product_url: str, main_cupom: str, main_cupom_discount_percentage: float, cupom_1: str, cupom_2: str) -> str:
 
129
  crew = Crew(
130
  agents=[self.product_analyst, self.social_media_copywriter],
131
  tasks=[analyze_product_task, create_post_task],
132
+ process=Process.sequential,
133
+ openai_api_key=self.openai_api_key
134
  )
135
 
136
  print(f"Crew is kicking off for URL: {product_url}")
 
138
  return result
139
 
140
  # --- Gradio Interface ---
141
+ def generate_ad(product_url: str, main_cupom: str, main_cupom_discount_percentage: float, cupom_1: str, cupom_2: str, openai_api_key: str, natura_api_token: str):
142
+ if not openai_api_key or not natura_api_token:
 
143
  return "Please configure your API keys in the settings section below."
144
 
145
+ social_media_crew = SocialMediaCrew(openai_api_key, natura_api_token)
146
  result = social_media_crew.run_crew(product_url, main_cupom, main_cupom_discount_percentage, cupom_1, cupom_2)
147
 
148
  if result == "INVALID_URL":
 
168
 
169
  with gr.Tab("Settings"):
170
  gr.Markdown("### ⚙️ API Key Settings")
171
+ gr.Markdown("Enter your API keys below. These will be used for the current session.")
172
+ openai_key_input = gr.Textbox(label="OPENAI_API_KEY", type="password")
173
+ natura_token_input = gr.Textbox(label="NATURA_API_TOKEN", type="password")
174
+
175
+ # No save button needed as keys are passed directly
176
+ gr.Markdown("API keys are used directly from these fields when you click 'Generate Ad'. They are not saved persistently.")
177
+
178
+ generate_button.click(generate_ad, inputs=[url_input, main_cupom_input, main_cupom_discount_percentage_input, cupom_1_input, cupom_2_input, openai_key_input, natura_token_input], outputs=ad_output)
179
 
180
  demo.launch()