Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
refactor: don't rely on handoffs if possible between agents
Brad Barbin7cb730c54468
diff --git a/apps/erp/app/components/Chat/ChatInterface.tsx b/apps/erp/app/components/Chat/ChatInterface.tsxindex 00f3043809..dca493539f 100644--- a/apps/erp/app/components/Chat/ChatInterface.tsx+++ b/apps/erp/app/components/Chat/ChatInterface.tsx@@ -100,14 +100,14 @@ export function ChatInterface({ geo }: Props) {}),});+ console.log({ messages });+const { agentStatus, currentToolCall } = useChatStatus(messages, status);const { artifacts } = useArtifacts();const hasArtifacts = artifacts && artifacts.length > 0;const hasMessages = messages.length > 0;- console.log({ messages });-const [suggestions] = useDataPart<{ prompts: string[] }>("suggestions");const hasSuggestions = suggestions?.prompts && suggestions.prompts.length > 0;diff --git a/apps/erp/app/components/Chat/Markdown/Markdown.tsx b/apps/erp/app/components/Chat/Markdown/Markdown.tsxindex fbbdd76ef6..c07deaf675 100644--- a/apps/erp/app/components/Chat/Markdown/Markdown.tsx+++ b/apps/erp/app/components/Chat/Markdown/Markdown.tsx@@ -1,4 +1,6 @@+import { getAppUrl } from "@carbon/auth";import { CodeBlock } from "@carbon/react";+import { Link } from "@remix-run/react";import { memo, useMemo } from "react";import type { Components } from "react-markdown";import ReactMarkdown from "react-markdown";@@ -14,6 +16,42 @@ export const Markdown = memo(({ children, html = false, limitedMarkdown = false }: MarkdownProps) => {const components = useMemo(() => {return {+ a: (props) => {+ const { children, node, href, ...rest } = props;+ if (href?.startsWith("/")) {+ return (+ <Link+ {...rest}+ to={href}+ className="text-blue-700 dark:text-blue-400 font-bold underline"+ >+ {children}+ </Link>+ );+ }++ if (href?.startsWith(getAppUrl())) {+ return (+ <Link+ {...rest}+ to={href?.replace(getAppUrl(), "")}+ className="text-blue-700 dark:text-blue-400 font-bold underline"+ >+ {children}+ </Link>+ );+ }++ return (+ <a+ {...rest}+ className="text-blue-700 dark:text-blue-400 font-bold underline"+ >+ {children}+ </a>+ );+ },+pre: (props) => {const { children, node, ...rest } = props;@@ -26,7 +64,7 @@ export const Markdown = memo(firstChild.children?.[0]?.type === "text") {// @ts-ignore- const { className, ...rest } = firstChild.properties;+ const { className } = firstChild.properties;const [, language = "plaintext"] =/language-(\w+)/.exec(String(className) || "") ?? [];diff --git a/apps/erp/app/components/Chat/lib/agent.tsx b/apps/erp/app/components/Chat/lib/agent.tsxindex 6fc2b44816..1b1fa136fc 100644--- a/apps/erp/app/components/Chat/lib/agent.tsx+++ b/apps/erp/app/components/Chat/lib/agent.tsx@@ -15,10 +15,11 @@ export const getStatusMessage = (status?: AgentStatus | null) => {if (state === "executing") {const messages: Record<AgentStatus["agent"], string> = {triage: "Thinking...",+general: "Searching the web...",- purchasing: "Purchasing...",- parts: "Parts...",- suppliers: "Suppliers...",+ purchasing: "Calling the purchasing agent...",+ parts: "Calling the parts agent...",+ suppliers: "Calling the suppliers agent...",};return messages[agent];diff --git a/apps/erp/app/components/Chat/lib/types.ts b/apps/erp/app/components/Chat/lib/types.tsindex 8bb983155e..6014837d86 100644--- a/apps/erp/app/components/Chat/lib/types.ts+++ b/apps/erp/app/components/Chat/lib/types.ts@@ -26,20 +26,12 @@ export type UIChatMessage = UIMessage<UITools>;--/*** Extended agent status type with application-specific agent names*/export type AgentStatus = {status: "routing" | "executing" | "completing";- agent:- | "triage"- | "orchestrator"- | "purchasing"- | "parts"- | "suppliers"- | "general";+ agent: "triage" | "purchasing" | "parts" | "suppliers" | "general";};/*** Extended data parts interface with application-specific datadiff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/orchestration-agent.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/orchestration-agent.tsindex 741e080715..565ca6dfb2 100644--- a/apps/erp/app/routes/api+/ai+/chat+/agents/orchestration-agent.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/agents/orchestration-agent.ts@@ -1,24 +1,12 @@import { openai } from "@ai-sdk/openai";-import {- partsAgent,- configurePartsAgentHandoffs,-} from "./parts-agent";import { purchasingAgent } from "./purchasing-agent";import { searchAgent } from "./search-agent";import { createAgent } from "./shared/agent";import { formatContextForLLM } from "./shared/prompts";-import {- supplierAgent,- configureSupplierAgentHandoffs,-} from "./supplier-agent";--// Configure handoffs between agents after they're all defined-configurePartsAgentHandoffs(supplierAgent, purchasingAgent);-configureSupplierAgentHandoffs(partsAgent, purchasingAgent);export const orchestrationAgent = createAgent({name: "triage",- model: openai("gpt-4o-mini"),+ model: openai("gpt-4o"),temperature: 0.1,modelSettings: {toolChoice: {@@ -38,6 +26,6 @@ suppliers: Search for suppliers, find suppliers for partspurchasing: creating purchase orders or getting quotes from suppliers</agent-capabilities></background-data>`,- handoffs: [purchasingAgent, searchAgent, partsAgent, supplierAgent],+ handoffs: [purchasingAgent, searchAgent],maxTurns: 1,});diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/parts-agent.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/parts-agent.tsdeleted file mode 100644index 5fb7ed4ffe..0000000000--- a/apps/erp/app/routes/api+/ai+/chat+/agents/parts-agent.ts+++ /dev/null@@ -1,51 +0,0 @@-import { openai } from "@ai-sdk/openai";-import type { Agent } from "@ai-sdk-tools/agents";-import { getPartTool } from "../tools/part-tools";-import { createAgent } from "./shared/agent";-import type { ChatContext } from "./shared/context";-import { COMMON_AGENT_RULES, formatContextForLLM } from "./shared/prompts";--export const partsAgent: Agent<ChatContext> = createAgent({- name: "parts",- model: openai("gpt-4o-mini"),- temperature: 0.3,- instructions: (ctx) => `You are a parts specialist for ${- ctx.companyName- }. Search for parts by description or readable ID.--Key capabilities:-- Look up parts by readable ID or description-- Provide part details including ID, name, and description-- Help identify the correct part when multiple matches exist--When handling part requests:-1. Use the getPart tool to search by readable ID or description-2. If multiple parts are found, present options to the user-3. If no parts are found, inform the user and ask for clarification-4. If a supplier is needed for a part, hand off to supplierAgent-5. If a purchase order needs to be created, hand off to purchasingAgent--<background-data>-${formatContextForLLM(ctx)}-</background-data>--${COMMON_AGENT_RULES}--<guidelines>-- For direct queries: lead with results, add context-- Always confirm the correct part when multiple matches exist-</guidelines>`,- tools: {- getPart: getPartTool,- },- handoffs: [],- maxTurns: 10,-});--// Configure handoffs after all agents are defined-export function configurePartsAgentHandoffs(- supplierAgent: Agent<ChatContext>,- purchasingAgent: Agent<ChatContext>-) {- (partsAgent as any).handoffs = [supplierAgent, purchasingAgent];-}diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/purchasing-agent.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/purchasing-agent.tsindex 73e2ef09dd..a73db5198b 100644--- a/apps/erp/app/routes/api+/ai+/chat+/agents/purchasing-agent.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/agents/purchasing-agent.ts@@ -1,13 +1,16 @@import { openai } from "@ai-sdk/openai";+import { getPartTool } from "../tools/part-tools";import { createPurchaseOrderTool } from "../tools/purchasing-tools";-import { partsAgent } from "./parts-agent";+import {+ getSupplierForPartsTool,+ getSupplierTool,+} from "../tools/supplier-tools";import { createAgent } from "./shared/agent";import { COMMON_AGENT_RULES, formatContextForLLM } from "./shared/prompts";-import { supplierAgent } from "./supplier-agent";export const purchasingAgent = createAgent({name: "purchasing",- model: openai("gpt-4o-mini"),+ model: openai("gpt-4o"),temperature: 0.3,instructions: (ctx) => `You are a purchasing specialist for ${ctx.companyName@@ -15,21 +18,24 @@ export const purchasingAgent = createAgent({When handling purchase order requests:1. First identify the part details (including quantities and measurements)-2. Use partAgent to look up the part ID+2. Use getPart to look up the part ID3. If no supplier is explicitly specified in the prompt:- - Use supplierAgent to get recommended suppliers+ - Use getSupplierForParts to get recommended suppliers- Ask the user to confirm which supplier they want to use-4. Only proceed with createPurchaseOrder tool when both part and supplier are confirmed+4. Only proceed with createPurchaseOrder when both part and supplier are confirmed5. If there are multiple options for a part or supplier, ask the user to confirm which one they want to use6. If there are no options, ask the user for clarificationFor example:- If user says "create a purchase order for 5lb of 1/4" steel":1. First look up the part ID for "1/4" steel"- 2. Then use supplierAgent to get recommended suppliers2. Then ask user to specify a supplier, potentially offering suggestions3. Only create the PO once supplier is confirmed- 4. Use createPurchaseOrder tool to create the purchase order++- If user says "create a purchase order for 5lb of 1/4" steel from MetalCorp":+ 1. Look up part ID for "1/4" steel"+ 2. Look up supplier ID for "MetalCorp"+ 3. Create the PO with both IDsKey capabilities:- Create and update purchase orders@@ -49,8 +55,11 @@ ${COMMON_AGENT_RULES}- For direct queries: lead with results, add context</guidelines>`,tools: {+ getPart: getPartTool,+ getSupplierForParts: getSupplierForPartsTool,+ getSupplier: getSupplierTool,createPurchaseOrder: createPurchaseOrderTool,},- handoffs: [partsAgent, supplierAgent],+ handoffs: [],maxTurns: 10,});diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.tsindex 510afce4b4..d07a491326 100644--- a/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts@@ -26,7 +26,7 @@ export const createAgent = (config: AgentConfig<ChatContext>) => {limit: 10,},workingMemory: {- enabled: true,+ enabled: false, // Disabled to prevent multiple system messages in multi-agent handoffstemplate: PROFILE_PROMPT,scope: "user",},diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/supplier-agent.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/supplier-agent.tsdeleted file mode 100644index 6ee594af3b..0000000000--- a/apps/erp/app/routes/api+/ai+/chat+/agents/supplier-agent.ts+++ /dev/null@@ -1,58 +0,0 @@-import type { Agent } from "@ai-sdk-tools/agents";-import { openai } from "@ai-sdk/openai";-import {- getSupplierForPartsTool,- getSupplierTool,-} from "../tools/supplier-tools";-import { createAgent } from "./shared/agent";-import type { ChatContext } from "./shared/context";-import { COMMON_AGENT_RULES, formatContextForLLM } from "./shared/prompts";--export const supplierAgent: Agent<ChatContext> = createAgent({- name: "suppliers",- model: openai("gpt-4o-mini"),- temperature: 0.3,- instructions: (ctx) => `You are a supplier specialist for ${- ctx.companyName- }. Search for suppliers and recommend suppliers for parts.--Key capabilities:-- Look up suppliers by ID, name, or description-- Find suppliers for specific parts-- Recommend suppliers based on part requirements-- Provide supplier details and pricing information--When handling supplier requests:-1. Use getSupplier to search by ID, name, description, or part IDs-2. Use getSupplierForParts to get recommended suppliers for a list of parts-3. If multiple suppliers are found, present options to the user-4. If no suppliers are found, inform the user and ask for clarification-5. If part information is needed, hand off to partsAgent-6. If a purchase order needs to be created, hand off to purchasingAgent--<background-data>-${formatContextForLLM(ctx)}-</background-data>--${COMMON_AGENT_RULES}--<guidelines>-- For direct queries: lead with results, add context-- Always confirm the correct supplier when multiple matches exist-- Prioritize preferred suppliers when available-</guidelines>`,- tools: {- getSupplier: getSupplierTool,- getSupplierForParts: getSupplierForPartsTool,- },- handoffs: [],- maxTurns: 10,-});--// Configure handoffs after all agents are defined-export function configureSupplierAgentHandoffs(- partsAgent: Agent<ChatContext>,- purchasingAgent: Agent<ChatContext>-) {- (supplierAgent as any).handoffs = [partsAgent, purchasingAgent];-}diff --git a/apps/erp/app/routes/api+/ai+/chat+/tools/part-tools.ts b/apps/erp/app/routes/api+/ai+/chat+/tools/part-tools.tsindex 3e4d112f60..e9d7ea134b 100644--- a/apps/erp/app/routes/api+/ai+/chat+/tools/part-tools.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/tools/part-tools.ts@@ -27,7 +27,7 @@ export const getPartTool = tool({const [part, supplierPart] = await Promise.all([context.client.from("item")- .select("*")+ .select("id, name, description, revision").or(`readableId.eq.${readableId},readableIdWithRevision.eq.${readableId}`)@@ -36,7 +36,7 @@ export const getPartTool = tool({.limit(1),context.client.from("supplierPart")- .select("*, item(*)")+ .select("*, item(id, name, description, revision)").eq("supplierPartId", readableId).eq("companyId", context.companyId).single(),@@ -85,7 +85,7 @@ export const getPartTool = tool({if (description) {console.log("[getPartTool] Searching by description:", description);- const embedding = await generateEmbedding(client, description);+ const embedding = await generateEmbedding(context.client, description);console.log("[getPartTool] Generated embedding for description");const search = await context.client.rpc("items_search", {diff --git a/apps/erp/app/routes/api+/ai+/chat+/tools/purchasing-tools.ts b/apps/erp/app/routes/api+/ai+/chat+/tools/purchasing-tools.tsindex a1388b4a69..c3e8d0398d 100644--- a/apps/erp/app/routes/api+/ai+/chat+/tools/purchasing-tools.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/tools/purchasing-tools.ts@@ -9,8 +9,9 @@ import {insertSupplierInteraction,} from "~/modules/purchasing/purchasing.service";-import { getCarbonServiceRole } from "@carbon/auth";+import { getAppUrl, getCarbonServiceRole } from "@carbon/auth";import { getNextSequence } from "~/modules/settings";+import { path } from "~/utils/path";import type { ChatContext } from "../agents/shared/context";export const createPurchaseOrderSchema = z.object({@@ -28,6 +29,12 @@ export const createPurchaseOrderTool = tool({inputSchema: createPurchaseOrderSchema,execute: async function (args, executionOptions) {const context = executionOptions.experimental_context as ChatContext;++ console.log(+ "[createPurchaseOrderTool] Starting purchase order creation with args:",+ args+ );+const [nextSequence,supplierInteraction,@@ -52,23 +59,46 @@ export const createPurchaseOrderTool = tool({// getEmployeeJob(client, context.userId, context.companyId),]);+ console.log("[createPurchaseOrderTool] Retrieved data:", {+ nextSequence: nextSequence.data,+ supplierInteraction: !!supplierInteraction.data,+ supplier: !!supplier.data,+ supplierPayment: !!supplierPayment.data,+ supplierShipping: !!supplierShipping.data,+ });+if (!supplierInteraction.data) {+ console.log(+ "[createPurchaseOrderTool] Failed to create supplier interaction"+ );return {error: "Failed to create supplier interaction",};}if (!supplier.data) {+ console.log(+ "[createPurchaseOrderTool] Supplier not found:",+ args.supplierId+ );return {error: "Supplier not found",};}if (!supplierPayment.data) {+ console.log(+ "[createPurchaseOrderTool] Supplier payment not found for supplier:",+ args.supplierId+ );return {error: "Supplier payment not found",};}if (!supplierShipping.data) {+ console.log(+ "[createPurchaseOrderTool] Supplier shipping not found for supplier:",+ args.supplierId+ );return {error: "Supplier shipping not found",};@@ -84,6 +114,11 @@ export const createPurchaseOrderTool = tool({createdBy: context.userId,};+ console.log(+ "[createPurchaseOrderTool] Initial purchase order data:",+ purchaseOrder+ );+const {paymentTermId,invoiceSupplierId,@@ -94,23 +129,35 @@ export const createPurchaseOrderTool = tool({const { shippingMethodId, shippingTermId } = supplierShipping.data;if (supplier.data?.currencyCode) {+ console.log(+ "[createPurchaseOrderTool] Getting currency for code:",+ supplier.data.currencyCode+ );const currency = await getCurrencyByCode(context.client,context.companyId,supplier.data?.currencyCode ?? "");if (currency.data) {+ console.log(+ "[createPurchaseOrderTool] Updated exchange rate:",+ currency.data.exchangeRate+ );purchaseOrder.exchangeRate = currency.data.exchangeRate ?? 1;purchaseOrder.exchangeRateUpdatedAt = new Date().toISOString();}}+ console.log("[createPurchaseOrderTool] Creating purchase order...");const order = await context.client.from("purchaseOrder").insert(purchaseOrder).select("id, purchaseOrderId");if (!order) {+ console.log(+ "[createPurchaseOrderTool] Failed to create purchase order - no order returned"+ );return {error: "Failed to create purchase order",};@@ -119,13 +166,24 @@ export const createPurchaseOrderTool = tool({const purchaseOrderId = order.data?.[0]?.id ?? "";const locationId = null; // TODO+ console.log(+ "[createPurchaseOrderTool] Created purchase order with ID:",+ purchaseOrderId+ );+if (!purchaseOrderId) {+ console.log(+ "[createPurchaseOrderTool] Failed to create purchase order - no ID returned"+ );return {error: "Failed to create purchase order",};}try {+ console.log(+ "[createPurchaseOrderTool] Creating purchase order delivery and payment records..."+ );await Promise.all([context.client.from("purchaseOrderDelivery")@@ -152,9 +210,21 @@ export const createPurchaseOrderTool = tool({.single(),]);+ console.log(+ "[createPurchaseOrderTool] Creating purchase order lines for",+ args.parts.length,+ "parts..."+ );// Create purchase order lines for each partawait Promise.all(args.parts.map(async (part: { partId: string; quantity: number }) => {+ console.log(+ "[createPurchaseOrderTool] Processing part:",+ part.partId,+ "quantity:",+ part.quantity+ );+// Get item detailsconst [item, supplierPart] = await Promise.all([context.client@@ -172,7 +242,24 @@ export const createPurchaseOrderTool = tool({.single(),]);+ console.log(+ "[createPurchaseOrderTool] Retrieved item data for part:",+ part.partId,+ "found:",+ !!item.data+ );+ console.log(+ "[createPurchaseOrderTool] Retrieved supplier part data for part:",+ part.partId,+ "found:",+ !!supplierPart.data+ );+if (!item.data) {+ console.log(+ "[createPurchaseOrderTool] Item not found:",+ part.partId+ );throw new Error(`Item not found: ${part.partId}`);}@@ -192,44 +279,72 @@ export const createPurchaseOrderTool = tool({.single(),]);+ console.log(+ "[createPurchaseOrderTool] Retrieved cost and replenishment data for part:",+ part.partId+ );++ const lineData = {+ purchaseOrderId: purchaseOrderId,+ itemId: part.partId,+ description: item.data?.name,+ purchaseOrderLineType: item.data?.type,+ purchaseQuantity: part.quantity,+ supplierUnitPrice:+ (supplierPart?.data?.unitPrice ?? itemCost?.data?.unitCost ?? 0) /+ purchaseOrder.exchangeRate,+ supplierShippingCost: 0,+ purchaseUnitOfMeasureCode:+ supplierPart?.data?.supplierUnitOfMeasureCode ??+ itemReplenishment?.data?.purchasingUnitOfMeasureCode ??+ item.data?.unitOfMeasureCode ??+ "EA",+ inventoryUnitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",+ conversionFactor:+ supplierPart?.data?.conversionFactor ??+ itemReplenishment?.data?.conversionFactor ??+ 1,+ locationId: locationId,+ shelfId: null,+ supplierTaxAmount: 0,+ companyId: context.companyId,+ createdBy: context.userId,+ };++ console.log(+ "[createPurchaseOrderTool] Creating purchase order line for part:",+ part.partId,+ "with data:",+ lineData+ );+// Create the purchase order linereturn context.client.from("purchaseOrderLine")- .insert({- purchaseOrderId: purchaseOrderId,- itemId: part.partId,- description: item.data?.name,- purchaseOrderLineType: item.data?.type,- purchaseQuantity: part.quantity,- supplierUnitPrice:- (supplierPart?.data?.unitPrice ??- itemCost?.data?.unitCost ??- 0) / purchaseOrder.exchangeRate,- supplierShippingCost: 0,- purchaseUnitOfMeasureCode:- supplierPart?.data?.supplierUnitOfMeasureCode ??- itemReplenishment?.data?.purchasingUnitOfMeasureCode ??- item.data?.unitOfMeasureCode ??- "EA",- inventoryUnitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",- conversionFactor:- supplierPart?.data?.conversionFactor ??- itemReplenishment?.data?.conversionFactor ??- 1,- locationId: locationId,- shelfId: null,- supplierTaxAmount: 0,- companyId: context.companyId,- createdBy: context.userId,- })+ .insert(lineData).select("id").single();}));- return order.data;+ console.log(+ "[createPurchaseOrderTool] Successfully created purchase order:",+ order.data+ );+ return {+ ...order.data,+ link: `${getAppUrl()}${path.to.purchaseOrder(purchaseOrderId)}`,+ };} catch (error) {+ console.log(+ "[createPurchaseOrderTool] Error creating purchase order details:",+ error+ );if (purchaseOrderId) {+ console.log(+ "[createPurchaseOrderTool] Cleaning up purchase order:",+ purchaseOrderId+ );await deletePurchaseOrder(context.client, purchaseOrderId);}return {diff --git a/apps/erp/app/routes/api+/ai+/chat+/tools/supplier-tools.ts b/apps/erp/app/routes/api+/ai+/chat+/tools/supplier-tools.tsindex 8c17d65578..fbf2564993 100644--- a/apps/erp/app/routes/api+/ai+/chat+/tools/supplier-tools.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/tools/supplier-tools.ts@@ -1,8 +1,10 @@+import { getAppUrl } from "@carbon/auth";import type { Database } from "@carbon/database";import type { SupabaseClient } from "@supabase/supabase-js";import { tool } from "ai";import { z } from "zod";import { generateEmbedding } from "~/modules/shared/shared.service";+import { path } from "~/utils/path";import type { ChatContext } from "../agents/shared/context";export const getSupplierSchema = z@@ -10,10 +12,10 @@ export const getSupplierSchema = zid: z.string().optional(),name: z.string().optional(),description: z.string().optional(),- partIds: z.array(z.string()).optional(),+ itemIds: z.array(z.string()).optional(),})- .refine((data) => data.id || data.name || data.description || data.partIds, {- message: "Either id, name, description, or partIds must be provided",+ .refine((data) => data.id || data.name || data.description || data.itemIds, {+ message: "Either id, name, description, or itemIds must be provided",});export const getSupplierTool = tool({@@ -22,46 +24,78 @@ export const getSupplierTool = tool({inputSchema: getSupplierSchema,execute: async function (args, executionOptions) {const context = executionOptions.experimental_context as ChatContext;- let { name, description, partIds } = args;+ let { name, description, itemIds } = args;++ console.log("[getSupplierTool] Starting supplier search with args:", args);if (args.id) {+ console.log("[getSupplierTool] Searching by id:", args.id);const supplier = await context.client.from("supplier").select("*").eq("id", args.id).eq("companyId", context.companyId).single();++ console.log(+ "[getSupplierTool] Supplier by id query result:",+ supplier.data+ );+if (supplier.data) {+ console.log(+ "[getSupplierTool] Found supplier by id, returning:",+ supplier.data.id+ );return {+ link: `${getAppUrl()}${path.to.supplier(supplier.data.id)}`,id: supplier.data.id,name: supplier.data.name,};}}- if (partIds && partIds.length > 0) {- return getSuppliersForParts(context.client, partIds, context);+ if (itemIds && itemIds.length > 0) {+ console.log("[getSupplierTool] Searching suppliers for parts:", itemIds);+ return getSuppliersForParts(context.client, itemIds, context);}if (args.name) {+ console.log("[getSupplierTool] Searching by name:", args.name);const supplier = await context.client.from("supplier").select("*").eq("name", args.name).eq("companyId", context.companyId).single();++ console.log(+ "[getSupplierTool] Supplier by name query result:",+ supplier.data+ );+if (supplier.data) {+ console.log(+ "[getSupplierTool] Found supplier by name, returning:",+ supplier.data.id+ );return {id: supplier.data.id,};}if (!description) {+ console.log(+ "[getSupplierTool] No description provided, using name as description"+ );description = name;}}if (description) {- const embedding = await generateEmbedding(client, description);+ console.log("[getSupplierTool] Searching by description:", description);+ const embedding = await generateEmbedding(context.client, description);+ console.log("[getSupplierTool] Generated embedding for description");+const search = await context.client.rpc("suppliers_search", {query_embedding: JSON.stringify(embedding),match_threshold: 0.8,@@ -69,17 +103,26 @@ export const getSupplierTool = tool({p_company_id: context.companyId,});+ console.log(+ "[getSupplierTool] Search results:",+ search.data?.length || 0,+ "suppliers found"+ );+ console.log("[getSupplierTool] Search results:", search.data);+if (search.data && search.data.length > 0) {+ console.log("[getSupplierTool] Returning search results");return search.data;}}+ console.log("[getSupplierTool] No suppliers found, returning null");return null;},});export const getSupplierForPartsSchema = z.object({- partIds: z.array(z.string()),+ itemIds: z.array(z.string()),});export const getSupplierForPartsTool = tool({@@ -87,49 +130,82 @@ export const getSupplierForPartsTool = tool({inputSchema: getSupplierForPartsSchema,execute: async function (args, executionOptions) {const context = executionOptions.experimental_context as ChatContext;- return await getSuppliersForParts(context.client, args.partIds, context);+ console.log(+ "[getSupplierForPartsTool] Starting with itemIds:",+ args.itemIds+ );+ return await getSuppliersForParts(context.client, args.itemIds, context);},});async function getSuppliersForParts(client: SupabaseClient<Database>,- partIds: string[],+ itemIds: string[],context: { companyId: string }) {+ console.log("[getSuppliersForParts] Starting with itemIds:", itemIds);+// Find suppliers that provide these partsconst [supplierParts, preferredSuppliers] = await Promise.all([client.from("supplierPart").select("itemId, supplierId, unitPrice, supplierUnitOfMeasureCode")- .in("itemId", partIds)+ .in("itemId", itemIds).eq("companyId", context.companyId),client.from("itemReplenishment").select("itemId, preferredSupplierId")- .in("itemId", partIds)+ .in("itemId", itemIds).eq("companyId", context.companyId),]);- if (partIds.length === 1) {+ console.log(+ "[getSuppliersForParts] Supplier parts found:",+ supplierParts.data?.length || 0+ );+ console.log(+ "[getSuppliersForParts] Preferred suppliers found:",+ preferredSuppliers.data?.length || 0+ );++ if (itemIds.length === 1) {+ console.log(+ "[getSuppliersForParts] Single part search, looking for preferred supplier"+ );const preferredSupplier = preferredSuppliers.data?.find(- (p) => p.itemId === partIds[0]+ (p) => p.itemId === itemIds[0]);- if (preferredSupplier) {+ if (preferredSupplier && preferredSupplier.preferredSupplierId) {+ console.log(+ "[getSuppliersForParts] Found preferred supplier for single part:",+ preferredSupplier.preferredSupplierId+ );return {id: preferredSupplier.preferredSupplierId,};}+ console.log(+ "[getSuppliersForParts] No preferred supplier, looking for any supplier"+ );const firstSupplier = supplierParts.data?.find(- (p) => p.itemId === partIds[0]+ (p) => p.itemId === itemIds[0]);if (firstSupplier) {+ console.log(+ "[getSuppliersForParts] Found supplier for single part:",+ firstSupplier.supplierId+ );return {+ link: `${getAppUrl()}${path.to.supplier(firstSupplier.supplierId)}`,id: firstSupplier.supplierId,};}}+ console.log(+ "[getSuppliersForParts] Multiple parts, counting preferred supplier occurrences"+ );// Count occurrences of each supplier in preferred suppliersconst preferredSupplierCounts =preferredSuppliers.data?.reduce((counts, item) => {@@ -140,6 +216,11 @@ async function getSuppliersForParts(return counts;}, {} as Record<string, number>) || {};+ console.log(+ "[getSuppliersForParts] Preferred supplier counts:",+ preferredSupplierCounts+ );+// Find the most frequent preferred supplierlet mostFrequentPreferredSupplierId: string | null = null;let maxPreferredCount = 0;@@ -151,13 +232,30 @@ async function getSuppliersForParts(}}+ console.log(+ "[getSuppliersForParts] Most frequent preferred supplier:",+ mostFrequentPreferredSupplierId,+ "with count:",+ maxPreferredCount+ );+// If we found a preferred supplier, return itif (mostFrequentPreferredSupplierId) {+ console.log(+ "[getSuppliersForParts] Returning most frequent preferred supplier"+ );+return {+ link: `${getAppUrl()}${path.to.supplier(+ mostFrequentPreferredSupplierId+ )}`,id: mostFrequentPreferredSupplierId,};}+ console.log(+ "[getSuppliersForParts] No preferred supplier found, counting supplier part occurrences"+ );// If no preferred supplier, count occurrences in supplierPartsconst supplierPartCounts =supplierParts.data?.reduce((counts, item) => {@@ -167,6 +265,11 @@ async function getSuppliersForParts(return counts;}, {} as Record<string, number>) || {};+ console.log(+ "[getSuppliersForParts] Supplier part counts:",+ supplierPartCounts+ );+// Find the most frequent supplier from supplierPartslet mostFrequentSupplierId: string | null = null;let maxCount = 0;@@ -178,12 +281,23 @@ async function getSuppliersForParts(}}+ console.log(+ "[getSuppliersForParts] Most frequent supplier:",+ mostFrequentSupplierId,+ "with count:",+ maxCount+ );+// Return the most frequent supplier if foundif (mostFrequentSupplierId) {const supplier = supplierParts.data?.find((p) => p.supplierId === mostFrequentSupplierId);+ console.log(+ "[getSuppliersForParts] Returning most frequent supplier with details"+ );return {+ link: `${getAppUrl()}${path.to.supplier(mostFrequentSupplierId)}`,id: mostFrequentSupplierId,unitPrice: supplier?.unitPrice,supplierUnitOfMeasureCode: supplier?.supplierUnitOfMeasureCode,@@ -191,5 +305,6 @@ async function getSuppliersForParts(}// Return null if no supplier was found+ console.log("[getSuppliersForParts] No suppliers found, returning null");return null;}diff --git a/apps/erp/package.json b/apps/erp/package.jsonindex 5dd5c32515..49a2eaebd6 100644--- a/apps/erp/package.json+++ b/apps/erp/package.json@@ -8,6 +8,7 @@"@ai-sdk-tools/memory": "1.0.8","@ai-sdk-tools/agents": "1.0.8","@ai-sdk-tools/store": "1.0.8",+ "@ai-sdk/anthropic": "^2.0.41","@ai-sdk/openai": "^2.0.60","@ai-sdk/react": "^2.0.86","@carbon/auth": "*",diff --git a/package-lock.json b/package-lock.jsonindex cc9267a26b..834891e02f 100644--- a/package-lock.json+++ b/package-lock.json@@ -97,6 +97,7 @@"@ai-sdk-tools/devtools": "1.0.8","@ai-sdk-tools/memory": "1.0.8","@ai-sdk-tools/store": "1.0.8",+ "@ai-sdk/anthropic": "^2.0.41","@ai-sdk/openai": "^2.0.60","@ai-sdk/react": "^2.0.86","@carbon/auth": "*",@@ -1414,6 +1415,22 @@"zustand": ">=5.0.0"}},+ "node_modules/@ai-sdk/anthropic": {+ "version": "2.0.41",+ "resolved": "https://registry.npmjs.org/@ai-sdk/anthropic/-/anthropic-2.0.41.tgz",+ "integrity": "sha512-ZQebpyE6rM3JoeEyhJXUNDiRfVegw8ZrxT+rB8yurxI5JXDnlGpYQvSPmdR8TQfMbps4YkggfbcOwMeEZaTS+g==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/provider": "2.0.0",+ "@ai-sdk/provider-utils": "3.0.16"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "zod": "^3.25.76 || ^4.1.8"+ }+ },"node_modules/@ai-sdk/gateway": {"version": "2.0.6","resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-2.0.6.tgz",