Skip to content

Instantly share code, notes, and snippets.

@ben-vargas
Created October 6, 2025 20:33
Show Gist options
  • Select an option

  • Save ben-vargas/ad207cdb3ac4a66363940d4b7e860db4 to your computer and use it in GitHub Desktop.

Select an option

Save ben-vargas/ad207cdb3ac4a66363940d4b7e860db4 to your computer and use it in GitHub Desktop.
OpenAI Agent Builder - Agent SDK Output
import { OpenAI } from "openai";
import { runGuardrails } from "@openai/guardrails";
import { z } from "zod";
import { Agent, AgentInputItem, Runner } from "@openai/agents";
// Shared client for guardrails and file search
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// Guardrails definitions
const guardrailsConfig = {
guardrails: [
{
name: "Moderation",
config: {
categories: [
"sexual",
"sexual/minors",
"hate",
"hate/threatening",
"harassment",
"harassment/threatening",
"self-harm",
"self-harm/intent",
"self-harm/instructions",
"violence",
"violence/graphic",
"illicit",
"illicit/violent"
]
}
}
]
};
const context = { guardrailLlm: client };
// Guardrails utils
function guardrailsHasTripwire(results) {
return (results ?? []).some((r) => r?.tripwireTriggered === true);
}
function getGuardrailSafeText(results, fallbackText) {
// Prefer checked_text as the generic safe/processed text
for (const r of results ?? []) {
if (r?.info && ("checked_text" in r.info)) {
return r.info.checked_text ?? fallbackText;
}
}
// Fall back to PII-specific anonymized_text if present
const pii = (results ?? []).find((r) => r?.info && "anonymized_text" in r.info);
return pii?.info?.anonymized_text ?? fallbackText;
}
function buildGuardrailFailOutput(results) {
const get = (name) => (results ?? []).find((r) => {
const info = r?.info ?? {};
const n = (info?.guardrail_name ?? info?.guardrailName);
return n === name;
}),
pii = get("Contains PII"),
mod = get("Moderation"),
jb = get("Jailbreak"),
hal = get("Hallucination Detection"),
piiCounts = Object.entries(pii?.info?.detected_entities ?? {})
.filter(([, v]) => Array.isArray(v))
.map(([k, v]) => k + ":" + v.length),
thr = jb?.info?.threshold,
conf = jb?.info?.confidence;
return {
pii: {
failed: (piiCounts.length > 0) || pii?.tripwireTriggered === true,
...(piiCounts.length ? { detected_counts: piiCounts } : {}),
...(pii?.executionFailed && pii?.info?.error ? { error: pii.info.error } : {}),
},
moderation: {
failed: mod?.tripwireTriggered === true || ((mod?.info?.flagged_categories ?? []).length > 0),
...(mod?.info?.flagged_categories ? { flagged_categories: mod.info.flagged_categories } : {}),
...(mod?.executionFailed && mod?.info?.error ? { error: mod.info.error } : {}),
},
jailbreak: {
// Rely on runtime-provided tripwire; don't recompute thresholds
failed: jb?.tripwireTriggered === true,
...(jb?.executionFailed && jb?.info?.error ? { error: jb.info.error } : {}),
},
hallucination: {
// Rely on runtime-provided tripwire; don't recompute
failed: hal?.tripwireTriggered === true,
...(hal?.info?.reasoning ? { reasoning: hal.info.reasoning } : {}),
...(hal?.info?.hallucination_type ? { hallucination_type: hal.info.hallucination_type } : {}),
...(hal?.info?.hallucinated_statements ? { hallucinated_statements: hal.info.hallucinated_statements } : {}),
...(hal?.info?.verified_statements ? { verified_statements: hal.info.verified_statements } : {}),
...(hal?.executionFailed && hal?.info?.error ? { error: hal.info.error } : {}),
},
};
}
const SelectDomainSchema = z.object({ domain: z.enum(["commerce", "personnel", "other"]) });
const selectDomain = new Agent({
name: "Select domain",
instructions: `You classify a user’s natural language question into a domain. Choose exactly one: \"commerce\" | \"personnel\" | \"other\".
Domains:
• commerce — Retail/transactions about shoppers and purchases. Sample tables: customer (country_code, age_bracket, gender), merchant (merchant_category), payment_method (payment_type), date (date), purchase (status, total_amount_usd, gross_amount, discount_amount, tax_amount, channel, event_ts). Typical query intents: GMV/revenue/orders/AOV; countries, merchant categories, payment types (BNPL/wallet/card); time ranges (“last 30 days”); refunds/chargebacks.
• personnel — HR/finance about employees, compensation, benefits, and attendance. Sample tables: employee (employment_status, pay_type, flsa_status, base_salary_amount), department (department_name), job (job_title, job_level), location (country_code), date (date), payroll (hours_overtime, base_pay_amount, bonus_amount, employer_benefit_cost_amount), benefits_enrollment (benefit_type, coverage_tier, employer_premium_amount). Typical query intents: headcount, overtime costs, payroll/benefits spend, absences by department.
If the query does not fit either domain, select \"other\". `,
model: "gpt-5",
outputType: SelectDomainSchema,
modelSettings: {
reasoning: {
effort: "minimal",
summary: "auto"
},
store: true
}
});
const createCommerceQuery = new Agent({
name: "Create commerce query",
instructions: `You are a translator between natural language and domain-specific language for queries related to commerce (customers and products).
Your role is to transform a natural-language analytics request into a single, correct, executable domain query using only what is declared in the provided full_ontology. The full_ontology is YAML that defines entities, columns, foreign keys, measures, semantic_layer metrics/dimensions, reference_views, and validation_rules.
You should follow these steps: (1) resolve the user's intent and map the query to specific metrics/dimensions/time, (2) select the right tables and (minimal) joins required to support the query, (3) construct validated SQL/DSL with safe defaults.
Do not invent schema - follow the explicit schema defined below.
<full_ontology>
version: 1.0
namespace: commerce_ontology
enums:
gender: [male, female, non_binary, unspecified, prefer_not_to_say]
payment_type: [card, wallet, bank_transfer, bnpl, cash, gift_card, other]
card_network: [visa, mastercard, amex, discover, unionpay, jcb, other]
merchant_category:
- grocery
- restaurant
- apparel
- electronics
- fuel
- travel
- marketplace
- subscription
- digital_goods
- services
purchase_status: [authorized, captured, refunded, chargeback, voided, failed]
age_bracket: [\"<18\",\"18-24\",\"25-34\",\"35-44\",\"45-54\",\"55-64\",\"65+\",\"unknown\"]
income_bracket_usd: [\"<25k\",\"25k-50k\",\"50k-75k\",\"75k-100k\",\"100k-150k\",\"150k-250k\",\">250k\",\"unknown\"]
customer_segment: [new, active, lapsing, churned, vip, employee, test]
entities:
customer:
grain: one_row_per_customer_version
table: dim.customer
keys:
primary: customer_sk
natural: customer_id_nk
scd2:
valid_from_ts: valid_from_ts
valid_to_ts: valid_to_ts
is_current: is_current
columns:
customer_sk: {type: BIGINT, nullable: false}
customer_id_nk: {type: STRING, nullable: false}
created_ts: {type: TIMESTAMP, nullable: false}
valid_from_ts: {type: TIMESTAMP, nullable: false}
valid_to_ts: {type: TIMESTAMP, nullable: true}
is_current: {type: BOOLEAN, nullable: false}
first_name: {type: STRING}
last_name: {type: STRING}
full_name: {type: STRING, generated: \"concat_ws(' ', first_name, last_name)\"}
email: {type: STRING}
phone_e164: {type: STRING}
date_of_birth: {type: DATE}
gender: {type: ENUM(gender)}
address_line1: {type: STRING}
address_line2: {type: STRING}
city: {type: STRING}
region_code: {type: STRING}
postal_code: {type: STRING}
country_code: {type: STRING(2)}
latitude: {type: DECIMAL(9,6)}
longitude: {type: DECIMAL(9,6)}
demographic_profile_json: {type: JSON}
age_bracket: {type: ENUM(age_bracket), generated: \"bucket_from_dob(date_of_birth)\"}
household_income_bracket: {type: ENUM(income_bracket_usd)}
preferred_currency: {type: STRING(3), default: \"USD\"}
segment: {type: ENUM(customer_segment)}
consent_marketing: {type: BOOLEAN}
consent_personalization: {type: BOOLEAN}
consent_updated_ts: {type: TIMESTAMP}
acquisition_channel: {type: STRING}
acquisition_campaign_id: {type: STRING}
referrer_customer_id_nk: {type: STRING}
lifecycle_stage: {type: STRING}
deletion_requested_ts: {type: TIMESTAMP, nullable: true}
gdpr_erasure_ts: {type: TIMESTAMP, nullable: true}
indexes:
- [customer_id_nk]
- [email]
- [country_code, region_code]
lineage:
sources: [crm.customers, auth.users, marketing.consent_logs]
merchant:
grain: one_row_per_merchant
table: dim.merchant
keys:
primary: merchant_sk
natural: merchant_id_nk
columns:
merchant_sk: {type: BIGINT, nullable: false}
merchant_id_nk: {type: STRING, nullable: false}
merchant_name: {type: STRING}
merchant_domain: {type: STRING}
merchant_category: {type: ENUM(merchant_category)}
mcc: {type: STRING(4)}
country_code: {type: STRING(2)}
region_code: {type: STRING}
marketplace_flag: {type: BOOLEAN}
indexes:
- [merchant_id_nk]
- [merchant_category]
payment_method:
grain: one_row_per_customer_payment_profile
table: dim.payment_method
keys:
primary: payment_method_sk
natural: payment_method_id_nk
columns:
payment_method_sk: {type: BIGINT, nullable: false}
payment_method_id_nk: {type: STRING, nullable: false}
customer_sk_fk: {type: BIGINT, ref: dim.customer.customer_sk}
payment_type: {type: ENUM(payment_type)}
card_network: {type: ENUM(card_network), nullable: true}
card_last4: {type: STRING(4)}
issuer_country_code: {type: STRING(2)}
wallet_provider: {type: STRING, nullable: true}
bnpl_provider: {type: STRING, nullable: true}
activated_ts: {type: TIMESTAMP}
deactivated_ts: {type: TIMESTAMP}
is_active: {type: BOOLEAN}
indexes:
- [customer_sk_fk, is_active]
date:
grain: one_row_per_date
table: dim.date
keys: {primary: date_sk}
columns:
date_sk: {type: INT}
date: {type: DATE}
day_of_week: {type: TINYINT}
week: {type: TINYINT}
month: {type: TINYINT}
quarter: {type: TINYINT}
year: {type: SMALLINT}
is_weekend: {type: BOOLEAN}
iso_week_year: {type: SMALLINT}
iso_week: {type: TINYINT}
fact_purchase:
grain: one_row_per_purchase_event
table: fact.purchase
keys:
primary: purchase_sk
natural: purchase_id_nk
foreign_keys:
customer_sk_fk: dim.customer.customer_sk
merchant_sk_fk: dim.merchant.merchant_sk
payment_method_sk_fk: dim.payment_method.payment_method_sk
purchase_date_sk_fk: dim.date.date_sk
columns:
purchase_sk: {type: BIGINT, nullable: false}
purchase_id_nk: {type: STRING, nullable: false}
event_ts: {type: TIMESTAMP, nullable: false}
purchase_date_sk_fk: {type: INT, nullable: false}
customer_sk_fk: {type: BIGINT, nullable: false}
merchant_sk_fk: {type: BIGINT, nullable: false}
payment_method_sk_fk: {type: BIGINT, nullable: true}
status: {type: ENUM(purchase_status), nullable: false}
line_count: {type: INT, default: 1}
gross_amount: {type: DECIMAL(38,6), nullable: false}
tax_amount: {type: DECIMAL(38,6), nullable: true}
discount_amount: {type: DECIMAL(38,6), nullable: true}
shipping_amount: {type: DECIMAL(38,6), nullable: true}
total_amount: {type: DECIMAL(38,6), nullable: false, definition: \"gross - discount + tax + shipping\"}
currency: {type: STRING(3), nullable: false}
total_amount_usd: {type: DECIMAL(38,6), nullable: false, definition: \"fx_convert(total_amount, currency, 'USD', event_ts)\"}
item_category: {type: STRING, nullable: true}
is_subscription: {type: BOOLEAN, default: false}
subscription_id_nk: {type: STRING, nullable: true}
auth_ts: {type: TIMESTAMP, nullable: true}
capture_ts: {type: TIMESTAMP, nullable: true}
refund_ts: {type: TIMESTAMP, nullable: true}
chargeback_ts: {type: TIMESTAMP, nullable: true}
merchant_order_id: {type: STRING, nullable: true}
device_type: {type: STRING, nullable: true}
channel: {type: STRING, nullable: true}
country_code_snapshot: {type: STRING(2)}
measures:
gmv: {expr: \"CASE WHEN status IN ('captured','refunded','chargeback') THEN total_amount_usd ELSE 0 END\", type: DECIMAL}
net_revenue: {expr: \"CASE WHEN status='captured' THEN total_amount_usd WHEN status='refunded' THEN -ABS(total_amount_usd) ELSE 0 END\", type: DECIMAL}
orders: {expr: \"CASE WHEN status IN ('captured','refunded','chargeback') THEN 1 ELSE 0 END\", type: BIGINT}
indexes:
- [customer_sk_fk, event_ts]
- [merchant_sk_fk, event_ts]
- [status, event_ts]
</full_ontology>`,
model: "gpt-5",
modelSettings: {
reasoning: {
effort: "low",
summary: "auto"
},
store: true
}
});
const executeCommerceQuery = new Agent({
name: "Execute commerce query",
instructions: `Your role is to return dummy data relating to a query about shoppers and purchases. For the dummy data, assume an e-commerce company with thousands of customers that make purchase across common retailers such as department stores, grocery stores, and gas stations.
Based on the input query, return structured data representing the fictitious query results. Your results can be in any format.
Double check that the results are not null or empty. You should return results for any query input.`,
model: "gpt-5",
modelSettings: {
reasoning: {
effort: "low",
summary: "auto"
},
store: true
}
});
const createPersonnelQuery = new Agent({
name: "Create personnel query",
instructions: `You are a translator between natural language and domain-specific language for queries related to personnel (employees, compensation, benefits, and attendance).
Your role is to transform a natural-language analytics request into a single, correct, executable domain query using only what is declared in the provided full_ontology. The full_ontology is YAML that defines entities, columns, foreign keys, measures, semantic_layer metrics/dimensions, reference_views, and validation_rules.
You should follow these steps: (1) resolve the user's intent and map the query to specific metrics/dimensions/time, (2) select the right tables and (minimal) joins required to support the query, (3) construct validated SQL/DSL with safe defaults.
Do not invent schema - follow the explicit schema defined below.
<full_ontology>
version: 1.0
namespace: hr_finance_ontology
enums:
gender: [male, female, non_binary, unspecified, prefer_not_to_say]
employment_status: [active, leave, terminated, retired, contractor, intern]
pay_type: [salary, hourly, contractor, intern, stipend]
pay_frequency: [weekly, biweekly, semimonthly, monthly, adhoc]
flsa_status: [exempt, non_exempt]
benefit_type: [medical, dental, vision, life, disability, retirement, commuter, wellness, other]
coverage_tier: [employee_only, employee_spouse, employee_children, family, opt_out]
attendance_event: [work, overtime, leave_paid, leave_unpaid, holiday, training]
leave_type: [pto, sick, parental, bereavement, jury_duty, unpaid, other]
headcount_event_type: [hire, termination, transfer, promotion, demotion, salary_change, department_change]
currency: [USD, EUR, GBP, CAD, AUD, JPY, INR, CNY, MXN, BRL, other]
entities:
employee:
grain: one_row_per_employee_version
table: dim.employee
keys:
primary: employee_sk
natural: employee_id_nk
scd2:
valid_from_ts: valid_from_ts
valid_to_ts: valid_to_ts
is_current: is_current
columns:
employee_sk: {type: BIGINT, nullable: false}
employee_id_nk: {type: STRING, nullable: false}
created_ts: {type: TIMESTAMP, nullable: false}
valid_from_ts: {type: TIMESTAMP, nullable: false}
valid_to_ts: {type: TIMESTAMP, nullable: true}
is_current: {type: BOOLEAN, nullable: false}
first_name: {type: STRING}
last_name: {type: STRING}
full_name: {type: STRING, generated: \"concat_ws(' ', first_name, last_name)\"}
email: {type: STRING}
date_of_birth: {type: DATE}
gender: {type: ENUM(gender)}
employment_status: {type: ENUM(employment_status)}
hire_date: {type: DATE}
termination_date: {type: DATE, nullable: true}
pay_type: {type: ENUM(pay_type)}
pay_frequency: {type: ENUM(pay_frequency)}
flsa_status: {type: ENUM(flsa_status)}
base_salary_amount: {type: DECIMAL(38,6), nullable: true}
base_salary_currency: {type: ENUM(currency), nullable: true}
base_salary_amount_usd: {type: DECIMAL(38,6), nullable: true}
manager_employee_id_nk: {type: STRING, nullable: true}
department_sk_fk: {type: BIGINT}
job_sk_fk: {type: BIGINT}
location_sk_fk: {type: BIGINT}
cost_center_code: {type: STRING}
union_member_flag: {type: BOOLEAN}
remote_flag: {type: BOOLEAN}
indexes:
- [employee_id_nk]
- [department_sk_fk, employment_status]
lineage:
sources: [hris.employees, ats.hires, it.directory]
department:
grain: one_row_per_department
table: dim.department
keys:
primary: department_sk
natural: department_id_nk
columns:
department_sk: {type: BIGINT, nullable: false}
department_id_nk: {type: STRING, nullable: false}
department_name: {type: STRING}
division_name: {type: STRING}
cost_center_code: {type: STRING}
parent_department_id_nk: {type: STRING, nullable: true}
indexes:
- [department_id_nk]
- [division_name]
job:
grain: one_row_per_job
table: dim.job
keys:
primary: job_sk
natural: job_code_nk
columns:
job_sk: {type: BIGINT, nullable: false}
job_code_nk: {type: STRING, nullable: false}
job_title: {type: STRING}
job_family: {type: STRING}
job_level: {type: STRING}
grade: {type: STRING}
standard_hours_per_week: {type: DECIMAL(10,2)}
indexes:
- [job_code_nk]
- [job_family, job_level]
location:
grain: one_row_per_location
table: dim.location
keys:
primary: location_sk
natural: location_code_nk
columns:
location_sk: {type: BIGINT, nullable: false}
location_code_nk: {type: STRING, nullable: false}
site_name: {type: STRING}
country_code: {type: STRING(2)}
region_code: {type: STRING}
city: {type: STRING}
postal_code: {type: STRING}
timezone: {type: STRING}
onsite_flag: {type: BOOLEAN}
indexes:
- [country_code, region_code]
benefits_plan:
grain: one_row_per_benefit_plan
table: dim.benefits_plan
keys:
primary: benefits_plan_sk
natural: benefits_plan_id_nk
columns:
benefits_plan_sk: {type: BIGINT, nullable: false}
benefits_plan_id_nk: {type: STRING, nullable: false}
benefit_type: {type: ENUM(benefit_type)}
plan_name: {type: STRING}
coverage_tier: {type: ENUM(coverage_tier)}
provider_name: {type: STRING}
employer_contrib_pct: {type: DECIMAL(10,4), nullable: true}
employee_contrib_pct: {type: DECIMAL(10,4), nullable: true}
date:
grain: one_row_per_date
table: dim.date
keys: {primary: date_sk}
columns:
date_sk: {type: INT}
date: {type: DATE}
day_of_week: {type: TINYINT}
week: {type: TINYINT}
month: {type: TINYINT}
quarter: {type: TINYINT}
year: {type: SMALLINT}
is_weekend: {type: BOOLEAN}
iso_week_year: {type: SMALLINT}
iso_week: {type: TINYINT}
fact_payroll:
grain: one_row_per_employee_pay_period
table: fact.payroll
keys:
primary: payroll_sk
natural: payroll_run_id_nk
foreign_keys:
employee_sk_fk: dim.employee.employee_sk
department_sk_fk: dim.department.department_sk
job_sk_fk: dim.job.job_sk
location_sk_fk: dim.location.location_sk
pay_period_start_date_sk_fk: dim.date.date_sk
pay_period_end_date_sk_fk: dim.date.date_sk
pay_date_sk_fk: dim.date.date_sk
columns:
payroll_sk: {type: BIGINT, nullable: false}
payroll_run_id_nk: {type: STRING, nullable: false}
employee_sk_fk: {type: BIGINT, nullable: false}
department_sk_fk: {type: BIGINT, nullable: false}
job_sk_fk: {type: BIGINT, nullable: false}
location_sk_fk: {type: BIGINT, nullable: false}
pay_period_start_date_sk_fk: {type: INT, nullable: false}
pay_period_end_date_sk_fk: {type: INT, nullable: false}
pay_date_sk_fk: {type: INT, nullable: false}
hours_regular: {type: DECIMAL(10,2), nullable: true}
hours_overtime: {type: DECIMAL(10,2), nullable: true}
overtime_multiplier: {type: DECIMAL(10,4), nullable: true}
base_pay_amount: {type: DECIMAL(38,6), nullable: true}
overtime_pay_amount: {type: DECIMAL(38,6), nullable: true}
bonus_amount: {type: DECIMAL(38,6), nullable: true}
commission_amount: {type: DECIMAL(38,6), nullable: true}
employer_tax_amount: {type: DECIMAL(38,6), nullable: true}
employer_benefit_cost_amount: {type: DECIMAL(38,6), nullable: true}
employee_deduction_amount: {type: DECIMAL(38,6), nullable: true}
gross_pay_amount: {type: DECIMAL(38,6), nullable: true}
net_pay_amount: {type: DECIMAL(38,6), nullable: true}
currency: {type: ENUM(currency), nullable: false}
total_cost_amount_usd: {type: DECIMAL(38,6), definition: \"base_pay_amount + overtime_pay_amount + bonus_amount + commission_amount + employer_tax_amount + employer_benefit_cost_amount (FX→USD)\"}
overtime_cost_amount_usd: {type: DECIMAL(38,6), definition: \"overtime_pay_amount (FX→USD)\"}
measures:
payroll_cost_usd: {expr: \"COALESCE(total_cost_amount_usd,0)\", type: DECIMAL}
overtime_cost_usd: {expr: \"COALESCE(overtime_cost_amount_usd,0)\", type: DECIMAL}
base_pay_usd: {expr: \"COALESCE(base_pay_amount,0)\", type: DECIMAL}
bonus_usd: {expr: \"COALESCE(bonus_amount,0)\", type: DECIMAL}
commission_usd: {expr: \"COALESCE(commission_amount,0)\", type: DECIMAL}
employer_benefits_usd: {expr: \"COALESCE(employer_benefit_cost_amount,0)\", type: DECIMAL}
hours_regular: {expr: \"COALESCE(hours_regular,0)\", type: DECIMAL}
hours_overtime: {expr: \"COALESCE(hours_overtime,0)\", type: DECIMAL}
indexes:
- [employee_sk_fk, pay_date_sk_fk]
- [department_sk_fk, pay_date_sk_fk]
fact_time_attendance:
grain: one_row_per_employee_per_day
table: fact.time_attendance
keys:
primary: attendance_sk
natural: attendance_id_nk
foreign_keys:
employee_sk_fk: dim.employee.employee_sk
department_sk_fk: dim.department.department_sk
job_sk_fk: dim.job.job_sk
location_sk_fk: dim.location.location_sk
work_date_sk_fk: dim.date.date_sk
columns:
attendance_sk: {type: BIGINT, nullable: false}
attendance_id_nk: {type: STRING, nullable: false}
employee_sk_fk: {type: BIGINT, nullable: false}
department_sk_fk: {type: BIGINT, nullable: false}
job_sk_fk: {type: BIGINT, nullable: false}
location_sk_fk: {type: BIGINT, nullable: false}
work_date_sk_fk: {type: INT, nullable: false}
event_type: {type: ENUM(attendance_event), nullable: false}
leave_type: {type: ENUM(leave_type), nullable: true}
scheduled_hours: {type: DECIMAL(10,2), nullable: true}
worked_hours: {type: DECIMAL(10,2), nullable: true}
overtime_hours: {type: DECIMAL(10,2), nullable: true}
oncall_hours: {type: DECIMAL(10,2), nullable: true}
absence_flag: {type: BOOLEAN, default: false}
tardy_minutes: {type: INT, nullable: true}
measures:
days_present: {expr: \"CASE WHEN event_type IN ('work','overtime','training') AND worked_hours>0 THEN 1 ELSE 0 END\", type: BIGINT}
days_absent: {expr: \"CASE WHEN absence_flag THEN 1 ELSE 0 END\", type: BIGINT}
overtime_hours: {expr: \"COALESCE(overtime_hours,0)\", type: DECIMAL}
indexes:
- [employee_sk_fk, work_date_sk_fk]
- [department_sk_fk, work_date_sk_fk]
fact_benefits_enrollment:
grain: one_row_per_employee_plan_period
table: fact.benefits_enrollment
keys:
primary: enrollment_sk
natural: enrollment_id_nk
foreign_keys:
employee_sk_fk: dim.employee.employee_sk
benefits_plan_sk_fk: dim.benefits_plan.benefits_plan_sk
coverage_start_date_sk_fk: dim.date.date_sk
coverage_end_date_sk_fk: dim.date.date_sk
columns:
enrollment_sk: {type: BIGINT, nullable: false}
enrollment_id_nk: {type: STRING, nullable: false}
employee_sk_fk: {type: BIGINT, nullable: false}
benefits_plan_sk_fk: {type: BIGINT, nullable: false}
coverage_start_date_sk_fk: {type: INT, nullable: false}
coverage_end_date_sk_fk: {type: INT, nullable: true}
benefit_type: {type: ENUM(benefit_type), nullable: false}
coverage_tier: {type: ENUM(coverage_tier), nullable: false}
employee_premium_amount: {type: DECIMAL(38,6), nullable: true}
employer_premium_amount: {type: DECIMAL(38,6), nullable: true}
currency: {type: ENUM(currency), nullable: false}
employee_premium_amount_usd: {type: DECIMAL(38,6)}
employer_premium_amount_usd: {type: DECIMAL(38,6)}
measures:
employee_premium_usd: {expr: \"COALESCE(employee_premium_amount_usd,0)\", type: DECIMAL}
employer_premium_usd: {expr: \"COALESCE(employer_premium_amount_usd,0)\", type: DECIMAL}
indexes:
- [employee_sk_fk, benefits_plan_sk_fk, coverage_start_date_sk_fk]
fact_headcount_event:
grain: one_row_per_employee_event
table: fact.headcount_event
keys:
primary: hc_event_sk
natural: hc_event_id_nk
foreign_keys:
employee_sk_fk: dim.employee.employee_sk
department_sk_fk: dim.department.department_sk
job_sk_fk: dim.job.job_sk
location_sk_fk: dim.location.location_sk
event_date_sk_fk: dim.date.date_sk
columns:
hc_event_sk: {type: BIGINT, nullable: false}
hc_event_id_nk: {type: STRING, nullable: false}
employee_sk_fk: {type: BIGINT, nullable: false}
department_sk_fk: {type: BIGINT, nullable: false}
job_sk_fk: {type: BIGINT, nullable: false}
location_sk_fk: {type: BIGINT, nullable: false}
event_date_sk_fk: {type: INT, nullable: false}
event_type: {type: ENUM(headcount_event_type), nullable: false}
old_department_sk_fk: {type: BIGINT, nullable: true}
new_department_sk_fk: {type: BIGINT, nullable: true}
old_job_sk_fk: {type: BIGINT, nullable: true}
new_job_sk_fk: {type: BIGINT, nullable: true}
comp_change_amount_usd: {type: DECIMAL(38,6), nullable: true}
measures:
hires: {expr: \"CASE WHEN event_type='hire' THEN 1 ELSE 0 END\", type: BIGINT}
terminations: {expr: \"CASE WHEN event_type='termination' THEN 1 ELSE 0 END\", type: BIGINT}
indexes:
- [department_sk_fk, event_date_sk_fk]
- [event_type, event_date_sk_fk]
</full_ontology>
Based on the input query, return structured data representing the fictitious query results. Your results can be in any format.
Double check that the results are not null or empty. You should return results for any query input.`,
model: "gpt-5",
modelSettings: {
reasoning: {
effort: "low",
summary: "auto"
},
store: true
}
});
const executePersonnelQuery = new Agent({
name: "Execute personnel query",
instructions: `Your role is to return dummy data relating to a query about personnel (employees, compensation, benefits, and attendance). For the dummy data, assume a medium-sized company with several hundred employees, organized across different geographies, departments, job functions, seniority levels.
Based on the input query, return structured data representing the fictitious query results. Your results can be in any format.
Double check that the results are not null or empty. You should return results for any query input.
Based on the input query, return structured data representing the fictitious query results. Your results can be in any format.
Double check that the results are not null or empty. You should return results for any query input.`,
model: "gpt-5",
modelSettings: {
reasoning: {
effort: "low",
summary: "auto"
},
store: true
}
});
type WorkflowInput = { input_as_text: string };
// Main code entrypoint
export const runWorkflow = async (workflow: WorkflowInput) => {
const state = {
};
const conversationHistory: AgentInputItem[] = [
{
role: "user",
content: [
{
type: "input_text",
text: workflow.input_as_text
}
]
}
];
const runner = new Runner({
traceMetadata: {
__trace_source__: "agent-builder",
workflow_id: "wf_68e413495af4819081930e706a75bd5f0cdd9fe2a5058229"
}
});
const guardrailsInputtext = workflow.input_as_text;
const guardrailsResult = await runGuardrails(guardrailsInputtext, guardrailsConfig, context);
const guardrailsHastripwire = guardrailsHasTripwire(guardrailsResult);
const guardrailsAnonymizedtext = getGuardrailSafeText(guardrailsResult, guardrailsInputtext);
const guardrailsOutput = (guardrailsHastripwire ? buildGuardrailFailOutput(guardrailsResult ?? []) : { safe_text: (guardrailsAnonymizedtext ?? guardrailsInputtext) });
if (guardrailsHastripwire) {
return guardrailsOutput;
} else {
const selectDomainResultTemp = await runner.run(
selectDomain,
[
...conversationHistory
]
);
conversationHistory.push(...selectDomainResultTemp.newItems.map((item) => item.rawItem));
if (!selectDomainResultTemp.finalOutput) {
throw new Error("Agent result is undefined");
}
const selectDomainResult = {
output_text: JSON.stringify(selectDomainResultTemp.finalOutput),
output_parsed: selectDomainResultTemp.finalOutput
};
if (selectDomainResult.output_parsed.domain == "commerce") {
const createCommerceQueryResultTemp = await runner.run(
createCommerceQuery,
[
...conversationHistory
]
);
conversationHistory.push(...createCommerceQueryResultTemp.newItems.map((item) => item.rawItem));
if (!createCommerceQueryResultTemp.finalOutput) {
throw new Error("Agent result is undefined");
}
const createCommerceQueryResult = {
output_text: createCommerceQueryResultTemp.finalOutput ?? ""
};
const executeCommerceQueryResultTemp = await runner.run(
executeCommerceQuery,
[
...conversationHistory
]
);
conversationHistory.push(...executeCommerceQueryResultTemp.newItems.map((item) => item.rawItem));
if (!executeCommerceQueryResultTemp.finalOutput) {
throw new Error("Agent result is undefined");
}
const executeCommerceQueryResult = {
output_text: executeCommerceQueryResultTemp.finalOutput ?? ""
};
} else if (selectDomainResult.output_parsed.domain == "personnel") {
const createPersonnelQueryResultTemp = await runner.run(
createPersonnelQuery,
[
...conversationHistory
]
);
conversationHistory.push(...createPersonnelQueryResultTemp.newItems.map((item) => item.rawItem));
if (!createPersonnelQueryResultTemp.finalOutput) {
throw new Error("Agent result is undefined");
}
const createPersonnelQueryResult = {
output_text: createPersonnelQueryResultTemp.finalOutput ?? ""
};
const executePersonnelQueryResultTemp = await runner.run(
executePersonnelQuery,
[
...conversationHistory
]
);
conversationHistory.push(...executePersonnelQueryResultTemp.newItems.map((item) => item.rawItem));
if (!executePersonnelQueryResultTemp.finalOutput) {
throw new Error("Agent result is undefined");
}
const executePersonnelQueryResult = {
output_text: executePersonnelQueryResultTemp.finalOutput ?? ""
};
} else {
return selectDomainResult;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment