Created
May 2, 2025 18:43
-
-
Save infoslack/36a60248ca5a292c19eac77bfc56e0c4 to your computer and use it in GitHub Desktop.
Agentes de IA eficazes (sem o hype)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from openai import OpenAI | |
from pydantic import BaseModel | |
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
class CalendarEvent(BaseModel): | |
name: str | |
date: str | |
participants: list[str] | |
response = client.responses.parse( | |
model="gpt-4o-mini", | |
input="Daniel vai gravar um podcast na sexta-feira.", | |
instructions="Extraia informações do evento.", | |
text_format=CalendarEvent, | |
) | |
event = response.output[0].content[0].parsed | |
event.name | |
event.date | |
event.participants | |
print(event.model_dump_json(indent=2)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import yfinance as yf | |
from typing import List | |
from openai import OpenAI | |
from pydantic import BaseModel, Field | |
# Inicializa o cliente OpenAI | |
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
# Modelo de dados para saída estruturada | |
class StockAnalysis(BaseModel): | |
ticker: str = Field(description="Símbolo da ação") | |
company_name: str = Field(description="Nome da empresa") | |
current_price: float = Field(description="Preço atual") | |
monthly_change: float = Field(description="Variação mensal em %") | |
outlook: str = Field(description="Perspectiva: positiva, neutra ou negativa") | |
key_points: List[str] = Field(description="Pontos principais") | |
def analyze_stock(ticker): | |
"""Analisa uma ação e retorna dados estruturados.""" | |
# Obtém dados da ação com Yahoo Finance | |
stock = yf.Ticker(ticker) | |
info = stock.info | |
history = stock.history(period="1mo") | |
# Calcula variação mensal | |
change_percent = 0 | |
if not history.empty: | |
change_percent = round( | |
( | |
(history.iloc[-1]["Close"] - history.iloc[0]["Close"]) | |
/ history.iloc[0]["Close"] | |
) | |
* 100, | |
2, | |
) | |
# Preço atual | |
price = info.get( | |
"currentPrice", history.iloc[-1]["Close"] if not history.empty else 0 | |
) | |
print(f"Analisando {ticker}: {info.get('shortName', ticker)} a ${price}") | |
# Solicita análise estruturada | |
response = client.responses.parse( | |
model="gpt-4o-mini", | |
input=f""" | |
Analise a ação {ticker}: | |
Nome: {info.get("shortName", ticker)} | |
Setor: {info.get("sector", "N/A")} | |
Preço: {price} {info.get("currency", "USD")} | |
Variação mensal: {change_percent}% | |
P/E: {info.get("trailingPE", "N/A")} | |
Dividend Yield: {info.get("dividendYield", 0) * 100 if info.get("dividendYield") else 0}% | |
""", | |
instructions="Forneça uma análise financeira estruturada desta ação.", | |
text_format=StockAnalysis, | |
) | |
# Extrai e retorna a análise | |
analysis = response.output[0].content[0].parsed | |
# Imprime um resumo | |
print(f"\n{analysis.company_name} ({analysis.ticker}) - {analysis.outlook.upper()}") | |
print(f"Preço: ${analysis.current_price} | Variação: {analysis.monthly_change}%") | |
print("\nPontos-chave:") | |
for point in analysis.key_points: | |
print(f"• {point}") | |
return analysis | |
# Exemplo de uso | |
result = analyze_stock("AAPL") | |
# Saída em JSON para uso programático | |
print("\nJSON:") | |
print(result.model_dump_json(indent=2)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import os | |
from openai import OpenAI | |
from pydantic import BaseModel, Field | |
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
def search_kb(question): | |
"""Busca respostas na base de conhecimento""" | |
with open("kb.json", "r", encoding="utf-8") as f: | |
return json.load(f) | |
tools = [ | |
{ | |
"type": "function", | |
"name": "search_kb", | |
"description": "Search the knowledge base for answers", | |
"parameters": { | |
"type": "object", | |
"properties": { | |
"question": {"type": "string", "description": "The user's question"}, | |
}, | |
"required": ["question"], | |
}, | |
} | |
] | |
# Response model | |
class KBResponse(BaseModel): | |
answer: str = Field(description="Answer to the user's question") | |
confidence: str = Field(description="Confidence level: high, medium, or low") | |
def answer_question(question): | |
system_prompt = """ | |
Você é um assistente virtual de uma loja online brasileira. | |
Responda usando apenas as informações da base de conhecimento. | |
Se a pergunta não puder ser respondida com a base, informe educadamente. | |
""" | |
# First call to check if model wants to use the tool | |
response = client.responses.create( | |
model="gpt-4o-mini", | |
input=f"{system_prompt}\n\nPergunta: {question}", | |
tools=tools, | |
) | |
# Check for function calls | |
function_calls = [ | |
output for output in response.output if output.type == "function_call" | |
] | |
if function_calls: | |
# Get KB data and generate structured response | |
function_call = function_calls[0] | |
args = json.loads(function_call.arguments) | |
kb_data = search_kb(args.get("question")) | |
final_response = client.responses.parse( | |
model="gpt-4o-mini", | |
input=f""" | |
{system_prompt} | |
Pergunta: {question} | |
Base de conhecimento: | |
{json.dumps(kb_data, ensure_ascii=False)} | |
""", | |
instructions="Provide structured answer based on KB data", | |
text_format=KBResponse, | |
) | |
return final_response.output[0].content[0].parsed | |
else: | |
# Direct answer if no tool called | |
direct_text = next( | |
(output.value for output in response.output if hasattr(output, "value")), | |
next( | |
( | |
output.content | |
for output in response.output | |
if hasattr(output, "content") | |
), | |
"", | |
), | |
) | |
return KBResponse(answer=direct_text, confidence="low") | |
# Examples | |
question1 = "Qual é a política de devoluções da loja?" | |
response1 = answer_question(question1) | |
print(f"\n----- {question1}") | |
print(f"Resposta: {response1.answer}") | |
print(f"Confiança: {response1.confidence}") | |
question2 = "Vocês entregam para o Nordeste?" | |
response2 = answer_question(question2) | |
print(f"\n----- {question2}") | |
print(f"Resposta: {response2.answer}") | |
print(f"Confiança: {response2.confidence}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"records": [ | |
{ | |
"id": 1, | |
"question": "Qual é a política de devoluções?", | |
"answer": "Produtos podem ser devolvidos em até 30 dias após a compra com a nota fiscal original. O reembolso será processado no método de pagamento original em 5-7 dias úteis." | |
}, | |
{ | |
"id": 2, | |
"question": "Vocês entregam em todo o Brasil?", | |
"answer": "Sim, realizamos entregas para todos os estados brasileiros. O prazo de entrega varia entre 3-10 dias úteis, dependendo da região. Para áreas remotas, pode haver um acréscimo no prazo." | |
}, | |
{ | |
"id": 3, | |
"question": "Quais formas de pagamento são aceitas?", | |
"answer": "Aceitamos cartões de crédito (Visa, Mastercard, Elo, American Express), Pix, boleto bancário e pagamento parcelado em até 12x sem juros para compras acima de R$300,00." | |
}, | |
{ | |
"id": 4, | |
"question": "Como faço para rastrear meu pedido?", | |
"answer": "Você pode rastrear seu pedido acessando a seção 'Meus Pedidos' na sua conta em nosso site ou usando o código de rastreio enviado por e-mail após o despacho do produto." | |
}, | |
{ | |
"id": 5, | |
"question": "Vocês oferecem garantia estendida?", | |
"answer": "Sim, oferecemos garantia estendida opcional para produtos eletrônicos. A garantia padrão é de 12 meses, mas pode ser estendida para 24 ou 36 meses com um custo adicional de 10% ou 15% do valor do produto, respectivamente." | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment