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: tool config to a single file
Brad Barbine0ef1e83ec17
diff --git a/apps/erp/app/components/Chat/AnimatedStatus.tsx b/apps/erp/app/components/Chat/AnimatedStatus.tsxindex 8197ed3238..1ea30f88a2 100644--- a/apps/erp/app/components/Chat/AnimatedStatus.tsx+++ b/apps/erp/app/components/Chat/AnimatedStatus.tsx@@ -1,6 +1,6 @@import { TextShimmer } from "@carbon/react";import { AnimatePresence, motion } from "framer-motion";-import type { IconComponent } from "./lib/tools";+import type { IconType } from "react-icons";interface AnimatedStatusProps {text: string | null;@@ -10,7 +10,7 @@ interface AnimatedStatusProps {/** Animation variant for status changes */variant?: "fade" | "slide" | "scale" | "blur-fade";/** Optional icon to display before the text */- icon?: IconComponent | null;+ icon?: IconType | null;}export function AnimatedStatus({diff --git a/apps/erp/app/components/Chat/ChatHeader.tsx b/apps/erp/app/components/Chat/ChatHeader.tsxindex ec7fba7204..00529a481f 100644--- a/apps/erp/app/components/Chat/ChatHeader.tsx+++ b/apps/erp/app/components/Chat/ChatHeader.tsx@@ -3,7 +3,7 @@ import { ChatTitle } from "./ChatTitle";export function ChatHeader() {return (- <div className="flex items-center justify-start pl-8 relative h-8">+ <div className="flex items-center justify-start pl-9 relative h-8"><ChatNavigation /><ChatTitle /></div>diff --git a/apps/erp/app/components/Chat/ChatInput.tsx b/apps/erp/app/components/Chat/ChatInput.tsxindex 4ead4ea43f..cbedf3f849 100644--- a/apps/erp/app/components/Chat/ChatInput.tsx+++ b/apps/erp/app/components/Chat/ChatInput.tsx@@ -3,7 +3,6 @@ import { useChatActions, useChatId, useChatStatus } from "@ai-sdk-tools/store";import { cn } from "@carbon/react";import { forwardRef, useRef } from "react";import { CommandMenu } from "./CommandMenu";-import { FollowupQuestions } from "./FollowupQuestions";import { useChatStore } from "./lib/store";import {PromptInput,@@ -19,6 +18,7 @@ import {} from "./PromptInput";import { RecordButton, type RecordButtonRef } from "./RecordButton";import { SuggestedActionsButton } from "./SuggestedActions";+import { SuggestedPrompts } from "./SuggestedPrompts";import { WebSearchButton } from "./WebSearch";export interface ChatInputMessage extends PromptInputMessage {@@ -95,9 +95,8 @@ export const ChatInput = forwardRef<RecordButtonRef, ChatInputProps>()}><div className="mx-auto w-full pt-2 relative">- <FollowupQuestions />-{/* Command Suggestions Menu */}+ <SuggestedPrompts /><CommandMenu /><PromptInput onSubmit={handleSubmit} globalDrop multiple>diff --git a/apps/erp/app/components/Chat/ChatInterface.tsx b/apps/erp/app/components/Chat/ChatInterface.tsxindex dca493539f..d11e897cec 100644--- a/apps/erp/app/components/Chat/ChatInterface.tsx+++ b/apps/erp/app/components/Chat/ChatInterface.tsx@@ -100,8 +100,6 @@ export function ChatInterface({ geo }: Props) {}),});- console.log({ messages });-const { agentStatus, currentToolCall } = useChatStatus(messages, status);const { artifacts } = useArtifacts();diff --git a/apps/erp/app/components/Chat/ChatNavigation.tsx b/apps/erp/app/components/Chat/ChatNavigation.tsxindex 288e321187..dee6090dc9 100644--- a/apps/erp/app/components/Chat/ChatNavigation.tsx+++ b/apps/erp/app/components/Chat/ChatNavigation.tsx@@ -1,5 +1,3 @@-"use client";-import { useChatActions } from "@ai-sdk-tools/store";import { IconButton } from "@carbon/react";import { useNavigate } from "@remix-run/react";diff --git a/apps/erp/app/components/Chat/ChatStatusIndicators.tsx b/apps/erp/app/components/Chat/ChatStatusIndicators.tsxindex ee4ec30c38..280add6b0e 100644--- a/apps/erp/app/components/Chat/ChatStatusIndicators.tsx+++ b/apps/erp/app/components/Chat/ChatStatusIndicators.tsx@@ -1,8 +1,9 @@import { AnimatedStatus } from "./AnimatedStatus";import { getStatusMessage, getToolMessage } from "./lib/agent";-import { getToolIcon } from "./lib/tools";+import type { AgentStatus } from "./lib/types";import { Loader } from "./Loader";+import { getToolIcon } from "./ToolCallIndicator";interface ChatStatusIndicatorsProps {agentStatus: AgentStatus | null;diff --git a/apps/erp/app/components/Chat/SuggestedPrompts.tsx b/apps/erp/app/components/Chat/SuggestedPrompts.tsxnew file mode 100644index 0000000000..db18437bc7--- /dev/null+++ b/apps/erp/app/components/Chat/SuggestedPrompts.tsx@@ -0,0 +1,67 @@+import { useChatActions, useDataPart } from "@ai-sdk-tools/store";+import { Button } from "@carbon/react";+import { AnimatePresence, motion } from "framer-motion";+import { useChatInterface } from "./hooks/useChatInterface";++type SuggestionsData = {+ prompts: string[];+};++const delay = 1;++export function SuggestedPrompts() {+ const [suggestions, clearSuggestions] =+ useDataPart<SuggestionsData>("suggestions");+ const { sendMessage } = useChatActions();+ const { isChatPage } = useChatInterface();++ const handlePromptClick = (prompt: string) => {+ clearSuggestions();+ sendMessage({ text: prompt });+ };++ if (+ !suggestions?.prompts ||+ suggestions.prompts.length === 0 ||+ !isChatPage+ ) {+ return null;+ }++ const prompts = suggestions.prompts;++ return (+ <AnimatePresence mode="wait">+ <motion.div+ initial={{ opacity: 0, y: 20 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: 10 }}+ transition={{ duration: 0.3, delay, ease: "easeOut" }}+ className="absolute bottom-full left-0 right-0 w-full z-30 flex gap-2 mb-2 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"+ >+ {prompts.map((prompt, index) => (+ <motion.div+ key={prompt}+ initial={{ opacity: 0, y: 10 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, scale: 0.95 }}+ transition={{+ duration: 0.2,+ delay: delay + index * 0.05,+ ease: "easeOut",+ }}+ >+ <Button+ variant="ghost"+ size="sm"+ onClick={() => handlePromptClick(prompt)}+ className="px-2 py-1 h-auto rounded-full text-xs font-normal border text-muted-foreground flex-shrink-0 whitespace-nowrap"+ >+ {prompt}+ </Button>+ </motion.div>+ ))}+ </motion.div>+ </AnimatePresence>+ );+}diff --git a/apps/erp/app/components/Chat/ToolCallIndicator.tsx b/apps/erp/app/components/Chat/ToolCallIndicator.tsxindex 6522dec7f7..caf59d6755 100644--- a/apps/erp/app/components/Chat/ToolCallIndicator.tsx+++ b/apps/erp/app/components/Chat/ToolCallIndicator.tsx@@ -1,29 +1,13 @@import { cn, TextShimmer } from "@carbon/react";-import { LuGlobe, LuSearch, LuShoppingCart, LuSquareStack } from "react-icons/lu";+import type { IconType } from "react-icons";-export const toolDisplayConfig = {- createPurchaseOrder: {- displayText: "Purchasing",- icon: LuShoppingCart,- },- getSupplier: {- displayText: "Getting Supplier",- icon: LuSearch,- },- getSupplierForParts: {- displayText: "Getting Supplier for Parts",- icon: LuSearch,- },- getPart: {- displayText: "Getting Part",- icon: LuSquareStack,- },- webSearch: {- displayText: "Searching the Web",- icon: LuGlobe,- },-} as const;+import { toolConfigs as toolDisplayConfig } from "~/routes/api+/ai+/chat+/config";+export interface ToolConfig {+ name: string;+ icon: IconType;+ description?: string;+}export type SupportedToolName = keyof typeof toolDisplayConfig;export interface ToolCallIndicatorProps {@@ -31,6 +15,10 @@ export interface ToolCallIndicatorProps {className?: string;}+export function getToolIcon(toolName: SupportedToolName): IconType | null {+ return toolDisplayConfig[toolName]?.icon ?? null;+}+export function ToolCallIndicator({toolName,className,@@ -47,8 +35,8 @@ export function ToolCallIndicator({<div className="flex items-center justify-center size-3.5"><config.icon size={14} /></div>- <TextShimmer className="text-xs text-[#707070]" duration={1}>- {config.displayText}+ <TextShimmer className="text-xs text-muted-foreground" duration={1}>+ {config.displayText ?? ""}</TextShimmer></div></div>diff --git a/apps/erp/app/components/Chat/lib/tools.tsx b/apps/erp/app/components/Chat/lib/tools.tsxdeleted file mode 100644index 703971e505..0000000000--- a/apps/erp/app/components/Chat/lib/tools.tsx+++ /dev/null@@ -1,78 +0,0 @@-import type { ComponentType, SVGProps } from "react";-import { LuArrowRight, LuBrain, LuSearch, LuShoppingCart, LuSquareStack } from "react-icons/lu";--export type IconComponent = ComponentType<SVGProps<SVGSVGElement>>;--export interface ToolConfig {- name: string;- icon: IconComponent;- description?: string;-}--export const TOOL_CONFIGS: Record<string, ToolConfig> = {- // Purchasing tools- createPurchaseOrder: {- name: "Create Purchase Order",- icon: LuShoppingCart,- description: "Creating a purchase order",- },- getPart: {- name: "Get Part",- icon: LuSquareStack,- description: "Searching for a part",- },- getSupplier: {- name: "Get Supplier",- icon: LuSearch,- description: "Searching for a supplier",- },- getSupplierForParts: {- name: "Get Supplier for Parts",- icon: LuSearch,- description: "Searching for suppliers for parts",- },-- // Research tools- webSearch: {- name: "Web Search",- icon: LuSearch,- description: "Searching the web",- },-- // Memory tools- updateWorkingMemory: {- name: "Update Memory",- icon: LuBrain,- description: "Updating working memory",- },-- // Handoff tools- handoff_to_agent: {- name: "Routing",- icon: LuArrowRight,- description: "Routing to specialist",- },-};--/**- * Get tool configuration by tool name- */-export function getToolConfig(toolName: string): ToolConfig | null {- return TOOL_CONFIGS[toolName] || null;-}--/**- * Get tool icon component by tool name- */-export function getToolIcon(toolName: string): IconComponent | null {- const config = getToolConfig(toolName);- return config?.icon || null;-}--/**- * Get tool display name by tool name- */-export function getToolDisplayName(toolName: string): string | null {- const config = getToolConfig(toolName);- return config?.name || null;-}diff --git a/apps/erp/app/routes/api+/ai+/chat+/_index.ts b/apps/erp/app/routes/api+/ai+/chat+/_index.tsindex a39efdfe21..adc8e0fecd 100644--- a/apps/erp/app/routes/api+/ai+/chat+/_index.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/_index.ts@@ -13,11 +13,6 @@ export async function action({ request }: ActionFunctionArgs) {const payload = await request.json();- console.log({- function: "chat",- ...payload,- });-const {message,id,@@ -32,7 +27,7 @@ export async function action({ request }: ActionFunctionArgs) {baseCurrency,} = payload;- const appContext = createChatContext({+ const context = createChatContext({userId,companyId,client,@@ -48,12 +43,12 @@ export async function action({ request }: ActionFunctionArgs) {return orchestrationAgent.toUIMessageStream({message,+ context,+ agentChoice,+ toolChoice,strategy: "auto",maxRounds: 5,maxSteps: 20,- context: appContext,- agentChoice,- toolChoice,experimental_transform: smoothStream({chunking: "word",}),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 a73db5198b..4557c1694d 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,10 +1,8 @@import { openai } from "@ai-sdk/openai";-import { getPartTool } from "../tools/part-tools";-import { createPurchaseOrderTool } from "../tools/purchasing-tools";-import {- getSupplierForPartsTool,- getSupplierTool,-} from "../tools/supplier-tools";+import { createPurchaseOrderTool } from "../tools/create-purchase-order";+import { getPartTool } from "../tools/get-part";+import { getSupplierTool } from "../tools/get-supplier";+import { getSupplierForPartsTool } from "../tools/get-supplier-for-parts";import { createAgent } from "./shared/agent";import { COMMON_AGENT_RULES, formatContextForLLM } from "./shared/prompts";diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/search-agent.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/search-agent.tsindex e1ecb9a864..b166aa6986 100644--- a/apps/erp/app/routes/api+/ai+/chat+/agents/search-agent.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/agents/search-agent.ts@@ -1,5 +1,5 @@import { openai } from "@ai-sdk/openai";-import { webSearchTool } from "../tools/search-tools";+import { webSearchTool } from "../tools/web-search";import { purchasingAgent } from "./purchasing-agent";import { createAgent } from "./shared/agent";import { COMMON_AGENT_RULES, formatContextForLLM } from "./shared/prompts";diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/shared/tools.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/tools.tsnew file mode 100644index 0000000000..2b85ed2ae0--- /dev/null+++ b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/tools.ts@@ -0,0 +1,7 @@+import type { IconType } from "react-icons";++export interface ToolConfig {+ name: string;+ icon: IconType;+ displayText?: string;+}diff --git a/apps/erp/app/routes/api+/ai+/chat+/config.ts b/apps/erp/app/routes/api+/ai+/chat+/config.tsnew file mode 100644index 0000000000..153d49c0f4--- /dev/null+++ b/apps/erp/app/routes/api+/ai+/chat+/config.ts@@ -0,0 +1,39 @@+import type { ToolConfig } from "./agents/shared/tools";++// Dynamically import all tool configs+const toolModules = import.meta.glob("./tools/*/index.ts", {+ eager: true,+}) as Record<string, { config: ToolConfig }>;++// Alternative pattern for direct tool files+const directToolModules = import.meta.glob("./tools/*.ts", {+ eager: true,+}) as Record<string, { config: ToolConfig }>;++// Combine both patterns and create the config object+export const toolConfigs: Record<+ string,+ Pick<ToolConfig, "icon" | "displayText">+> = {+ ...Object.values(toolModules).reduce((acc, module) => {+ if (module.config) {+ acc[module.config.name] = {+ icon: module.config.icon,+ displayText: module.config.displayText,+ };+ }+ return acc;+ }, {} as Record<string, Pick<ToolConfig, "icon" | "displayText">>),++ ...Object.values(directToolModules).reduce((acc, module) => {+ if (module.config) {+ acc[module.config.name] = {+ icon: module.config.icon,+ displayText: module.config.displayText,+ };+ }+ return acc;+ }, {} as Record<string, Pick<ToolConfig, "icon" | "displayText">>),+};++console.log(toolConfigs);diff --git a/apps/erp/app/routes/api+/ai+/chat+/tools/purchasing-tools.ts b/apps/erp/app/routes/api+/ai+/chat+/tools/create-purchase-order.tssimilarity index 70%rename from apps/erp/app/routes/api+/ai+/chat+/tools/purchasing-tools.tsrename to apps/erp/app/routes/api+/ai+/chat+/tools/create-purchase-order.tsindex c3e8d0398d..4612155ce6 100644--- a/apps/erp/app/routes/api+/ai+/chat+/tools/purchasing-tools.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/tools/create-purchase-order.ts@@ -10,9 +10,17 @@ import {} from "~/modules/purchasing/purchasing.service";import { getAppUrl, getCarbonServiceRole } from "@carbon/auth";+import { LuShoppingCart } from "react-icons/lu";import { getNextSequence } from "~/modules/settings";import { path } from "~/utils/path";import type { ChatContext } from "../agents/shared/context";+import type { ToolConfig } from "../agents/shared/tools";++export const config: ToolConfig = {+ name: "createPurchaseOrder",+ icon: LuShoppingCart,+ displayText: "Creating a Purchase Order",+};export const createPurchaseOrderSchema = z.object({supplierId: z.string(),@@ -59,46 +67,23 @@ 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",};@@ -114,11 +99,6 @@ export const createPurchaseOrderTool = tool({createdBy: context.userId,};- console.log(- "[createPurchaseOrderTool] Initial purchase order data:",- purchaseOrder- );-const {paymentTermId,invoiceSupplierId,@@ -129,35 +109,23 @@ 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",};@@ -166,24 +134,13 @@ 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")@@ -210,21 +167,9 @@ 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@@ -242,24 +187,7 @@ 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}`);}@@ -279,11 +207,6 @@ export const createPurchaseOrderTool = tool({.single(),]);- console.log(- "[createPurchaseOrderTool] Retrieved cost and replenishment data for part:",- part.partId- );-const lineData = {purchaseOrderId: purchaseOrderId,itemId: part.partId,@@ -311,13 +234,6 @@ export const createPurchaseOrderTool = tool({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")@@ -327,24 +243,12 @@ export const createPurchaseOrderTool = tool({}));- 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/part-tools.ts b/apps/erp/app/routes/api+/ai+/chat+/tools/get-part.tssimilarity index 65%rename from apps/erp/app/routes/api+/ai+/chat+/tools/part-tools.tsrename to apps/erp/app/routes/api+/ai+/chat+/tools/get-part.tsindex e9d7ea134b..1fc0363b68 100644--- a/apps/erp/app/routes/api+/ai+/chat+/tools/part-tools.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/tools/get-part.ts@@ -1,7 +1,15 @@import { tool } from "ai";+import { LuSearch } from "react-icons/lu";import { z } from "zod";import { generateEmbedding } from "~/modules/shared/shared.service";import type { ChatContext } from "../agents/shared/context";+import type { ToolConfig } from "../agents/shared/tools";++export const config: ToolConfig = {+ name: "getPart",+ icon: LuSearch,+ displayText: "Getting Part",+};export const getPartSchema = z.object({@@ -19,11 +27,9 @@ export const getPartTool = tool({const context = executionOptions.experimental_context as ChatContext;let { readableId, description } = args;- console.log("[getPartTool] Starting part search with args:", args);+ console.log("[getPartTool]", args);if (readableId) {- console.log("[getPartTool] Searching by readableId:", readableId);-const [part, supplierPart] = await Promise.all([context.client.from("item")@@ -42,17 +48,7 @@ export const getPartTool = tool({.single(),]);- console.log("[getPartTool] Part query result:", part.data);- console.log(- "[getPartTool] Supplier part query result:",- supplierPart.data- );-if (supplierPart.data) {- console.log(- "[getPartTool] Found supplier part, returning:",- supplierPart.data.itemId- );return {id: supplierPart.data.itemId,name: supplierPart.data.item?.name,@@ -61,7 +57,6 @@ export const getPartTool = tool({};}if (part.data?.[0]) {- console.log("[getPartTool] Found part, returning:", part.data[0].id);return {id: part.data[0].id,name: part.data[0].name,@@ -70,23 +65,14 @@ export const getPartTool = tool({}if (!description) {- console.log(- "[getPartTool] No part found by readableId, using readableId as description"- );description = readableId;} else {- console.log(- "[getPartTool] No part found by readableId and description provided, returning null"- );return null;}}if (description) {- console.log("[getPartTool] Searching by description:", description);-const embedding = await generateEmbedding(context.client, description);- console.log("[getPartTool] Generated embedding for description");const search = await context.client.rpc("items_search", {query_embedding: JSON.stringify(embedding),@@ -95,20 +81,11 @@ export const getPartTool = tool({p_company_id: context.companyId,});- console.log(- "[getPartTool] Search results:",- search.data?.length || 0,- "items found"- );- console.log("[getPartTool] Search results:", search.data);-if (search.data && search.data.length > 0) {- console.log("[getPartTool] Returning search results");return search.data;}}- console.log("[getPartTool] No parts found, returning null");return null;},});diff --git a/apps/erp/app/routes/api+/ai+/chat+/tools/get-supplier-for-parts.ts b/apps/erp/app/routes/api+/ai+/chat+/tools/get-supplier-for-parts.tsnew file mode 100644index 0000000000..f5e23d6235--- /dev/null+++ b/apps/erp/app/routes/api+/ai+/chat+/tools/get-supplier-for-parts.ts@@ -0,0 +1,137 @@+import { getAppUrl } from "@carbon/auth";+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import { tool } from "ai";+import { LuSearch } from "react-icons/lu";+import { z } from "zod";+import { path } from "~/utils/path";+import type { ChatContext } from "../agents/shared/context";+import type { ToolConfig } from "../agents/shared/tools";++export const config: ToolConfig = {+ name: "getSupplierForParts",+ icon: LuSearch,+ displayText: "Getting Supplier for Parts",+};++export const getSupplierForPartsSchema = z.object({+ partIds: z.array(z.string()),+});++export const getSupplierForPartsTool = tool({+ description: "Suggest a list of suppliers for a given list of parts",+ inputSchema: getSupplierForPartsSchema,+ execute: async function (args, executionOptions) {+ const context = executionOptions.experimental_context as ChatContext;+ console.log("[getSupplierForPartsTool]", args);+ return await getSuppliersForParts(context.client, args.partIds, context);+ },+});++export async function getSuppliersForParts(+ client: SupabaseClient<Database>,+ partIds: string[],+ context: { companyId: string }+) {+ // Find suppliers that provide these parts+ const [supplierParts, preferredSuppliers] = await Promise.all([+ client+ .from("supplierPart")+ .select("itemId, supplierId, unitPrice, supplierUnitOfMeasureCode")+ .in("itemId", partIds)+ .eq("companyId", context.companyId),+ client+ .from("itemReplenishment")+ .select("itemId, preferredSupplierId")+ .in("itemId", partIds)+ .eq("companyId", context.companyId),+ ]);++ if (partIds.length === 1) {+ const preferredSupplier = preferredSuppliers.data?.find(+ (p) => p.itemId === partIds[0]+ );+ if (preferredSupplier && preferredSupplier.preferredSupplierId) {+ return {+ id: preferredSupplier.preferredSupplierId,+ };+ }++ const firstSupplier = supplierParts.data?.find(+ (p) => p.itemId === partIds[0]+ );+ if (firstSupplier) {+ return {+ link: `${getAppUrl()}${path.to.supplier(firstSupplier.supplierId)}`,+ id: firstSupplier.supplierId,+ };+ }+ }++ // Count occurrences of each supplier in preferred suppliers+ const preferredSupplierCounts =+ preferredSuppliers.data?.reduce((counts, item) => {+ if (item.preferredSupplierId) {+ counts[item.preferredSupplierId] =+ (counts[item.preferredSupplierId] || 0) + 1;+ }+ return counts;+ }, {} as Record<string, number>) || {};++ // Find the most frequent preferred supplier+ let mostFrequentPreferredSupplierId: string | null = null;+ let maxPreferredCount = 0;++ for (const [supplierId, count] of Object.entries(preferredSupplierCounts)) {+ if (count > maxPreferredCount) {+ maxPreferredCount = count;+ mostFrequentPreferredSupplierId = supplierId;+ }+ }++ // If we found a preferred supplier, return it+ if (mostFrequentPreferredSupplierId) {+ return {+ link: `${getAppUrl()}${path.to.supplier(+ mostFrequentPreferredSupplierId+ )}`,+ id: mostFrequentPreferredSupplierId,+ };+ }++ // If no preferred supplier, count occurrences in supplierParts+ const supplierPartCounts =+ supplierParts.data?.reduce((counts, item) => {+ if (item.supplierId) {+ counts[item.supplierId] = (counts[item.supplierId] || 0) + 1;+ }+ return counts;+ }, {} as Record<string, number>) || {};++ // Find the most frequent supplier from supplierParts+ let mostFrequentSupplierId: string | null = null;+ let maxCount = 0;++ for (const [supplierId, count] of Object.entries(supplierPartCounts)) {+ if (count > maxCount) {+ maxCount = count;+ mostFrequentSupplierId = supplierId;+ }+ }++ // Return the most frequent supplier if found+ if (mostFrequentSupplierId) {+ const supplier = supplierParts.data?.find(+ (p) => p.supplierId === mostFrequentSupplierId+ );+ return {+ link: `${getAppUrl()}${path.to.supplier(mostFrequentSupplierId)}`,+ id: mostFrequentSupplierId,+ unitPrice: supplier?.unitPrice,+ supplierUnitOfMeasureCode: supplier?.supplierUnitOfMeasureCode,+ };+ }++ // Return null if no supplier was found+ return null;+}diff --git a/apps/erp/app/routes/api+/ai+/chat+/tools/get-supplier.ts b/apps/erp/app/routes/api+/ai+/chat+/tools/get-supplier.tsnew file mode 100644index 0000000000..73e50fd399--- /dev/null+++ b/apps/erp/app/routes/api+/ai+/chat+/tools/get-supplier.ts@@ -0,0 +1,94 @@+import { getAppUrl } from "@carbon/auth";+import { tool } from "ai";+import { LuSearch } from "react-icons/lu";+import { z } from "zod";+import { generateEmbedding } from "~/modules/shared/shared.service";+import { path } from "~/utils/path";+import type { ChatContext } from "../agents/shared/context";+import type { ToolConfig } from "../agents/shared/tools";+import { getSuppliersForParts } from "./get-supplier-for-parts";++export const config: ToolConfig = {+ name: "getSupplier",+ icon: LuSearch,+ displayText: "Getting Supplier",+};++export const getSupplierSchema = z+ .object({+ id: z.string().optional(),+ name: z.string().optional(),+ description: z.string().optional(),+ partIds: z.array(z.string()).optional(),+ })+ .refine((data) => data.id || data.name || data.description || data.partIds, {+ message: "Either id, name, description, orpartIds must be provided",+ });++export const getSupplierTool = tool({+ description:+ "Search for suppliers by a specific name as specified by the user, a deduced description, or a list of part ids",+ inputSchema: getSupplierSchema,+ execute: async function (args, executionOptions) {+ const context = executionOptions.experimental_context as ChatContext;+ let { name, description, partIds } = args;++ console.log("[getSupplierTool]", args);++ if (args.id) {+ const supplier = await context.client+ .from("supplier")+ .select("*")+ .eq("id", args.id)+ .eq("companyId", context.companyId)+ .single();++ if (supplier.data) {+ 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 (args.name) {+ const supplier = await context.client+ .from("supplier")+ .select("*")+ .eq("name", args.name)+ .eq("companyId", context.companyId)+ .single();++ if (supplier.data) {+ return {+ id: supplier.data.id,+ };+ }+ if (!description) {+ description = name;+ }+ }++ if (description) {+ const embedding = await generateEmbedding(context.client, description);++ const search = await context.client.rpc("suppliers_search", {+ query_embedding: JSON.stringify(embedding),+ match_threshold: 0.8,+ match_count: 10,+ p_company_id: context.companyId,+ });++ if (search.data && search.data.length > 0) {+ return search.data;+ }+ }++ return null;+ },+});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.tsdeleted file mode 100644index fbf2564993..0000000000--- a/apps/erp/app/routes/api+/ai+/chat+/tools/supplier-tools.ts+++ /dev/null@@ -1,310 +0,0 @@-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- .object({- id: z.string().optional(),- name: z.string().optional(),- description: z.string().optional(),- itemIds: z.array(z.string()).optional(),- })- .refine((data) => data.id || data.name || data.description || data.itemIds, {- message: "Either id, name, description, or itemIds must be provided",- });--export const getSupplierTool = tool({- description:- "Search for suppliers by a specific name as specified by the user, a deduced description, or a list of part ids",- inputSchema: getSupplierSchema,- execute: async function (args, executionOptions) {- const context = executionOptions.experimental_context as ChatContext;- 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 (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) {- 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,- match_count: 10,- 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({- itemIds: z.array(z.string()),-});--export const getSupplierForPartsTool = tool({- description: "Suggest a list of suppliers for a given list of parts",- inputSchema: getSupplierForPartsSchema,- execute: async function (args, executionOptions) {- const context = executionOptions.experimental_context as ChatContext;- console.log(- "[getSupplierForPartsTool] Starting with itemIds:",- args.itemIds- );- return await getSuppliersForParts(context.client, args.itemIds, context);- },-});--async function getSuppliersForParts(- client: SupabaseClient<Database>,- itemIds: string[],- context: { companyId: string }-) {- console.log("[getSuppliersForParts] Starting with itemIds:", itemIds);-- // Find suppliers that provide these parts- const [supplierParts, preferredSuppliers] = await Promise.all([- client- .from("supplierPart")- .select("itemId, supplierId, unitPrice, supplierUnitOfMeasureCode")- .in("itemId", itemIds)- .eq("companyId", context.companyId),- client- .from("itemReplenishment")- .select("itemId, preferredSupplierId")- .in("itemId", itemIds)- .eq("companyId", context.companyId),- ]);-- 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 === itemIds[0]- );- 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 === 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 suppliers- const preferredSupplierCounts =- preferredSuppliers.data?.reduce((counts, item) => {- if (item.preferredSupplierId) {- counts[item.preferredSupplierId] =- (counts[item.preferredSupplierId] || 0) + 1;- }- return counts;- }, {} as Record<string, number>) || {};-- console.log(- "[getSuppliersForParts] Preferred supplier counts:",- preferredSupplierCounts- );-- // Find the most frequent preferred supplier- let mostFrequentPreferredSupplierId: string | null = null;- let maxPreferredCount = 0;-- for (const [supplierId, count] of Object.entries(preferredSupplierCounts)) {- if (count > maxPreferredCount) {- maxPreferredCount = count;- mostFrequentPreferredSupplierId = supplierId;- }- }-- console.log(- "[getSuppliersForParts] Most frequent preferred supplier:",- mostFrequentPreferredSupplierId,- "with count:",- maxPreferredCount- );-- // If we found a preferred supplier, return it- if (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 supplierParts- const supplierPartCounts =- supplierParts.data?.reduce((counts, item) => {- if (item.supplierId) {- counts[item.supplierId] = (counts[item.supplierId] || 0) + 1;- }- return counts;- }, {} as Record<string, number>) || {};-- console.log(- "[getSuppliersForParts] Supplier part counts:",- supplierPartCounts- );-- // Find the most frequent supplier from supplierParts- let mostFrequentSupplierId: string | null = null;- let maxCount = 0;-- for (const [supplierId, count] of Object.entries(supplierPartCounts)) {- if (count > maxCount) {- maxCount = count;- mostFrequentSupplierId = supplierId;- }- }-- console.log(- "[getSuppliersForParts] Most frequent supplier:",- mostFrequentSupplierId,- "with count:",- maxCount- );-- // Return the most frequent supplier if found- if (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,- };- }-- // Return null if no supplier was found- console.log("[getSuppliersForParts] No suppliers found, returning null");- return null;-}diff --git a/apps/erp/app/routes/api+/ai+/chat+/tools/search-tools.ts b/apps/erp/app/routes/api+/ai+/chat+/tools/web-search.tssimilarity index 92%rename from apps/erp/app/routes/api+/ai+/chat+/tools/search-tools.tsrename to apps/erp/app/routes/api+/ai+/chat+/tools/web-search.tsindex fc2c3e62d8..fa748364f1 100644--- a/apps/erp/app/routes/api+/ai+/chat+/tools/search-tools.ts+++ b/apps/erp/app/routes/api+/ai+/chat+/tools/web-search.ts@@ -1,14 +1,16 @@import { openai } from "@ai-sdk/openai";import type { Tool } from "ai";import { generateText, stepCountIs, tool } from "ai";+import { LuGlobe } from "react-icons/lu";import { z } from "zod";import type { ChatContext } from "../agents/shared/context";+import type { ToolConfig } from "../agents/shared/tools";-export interface SourceItem {- url: string;- title: string;- publishedDate?: string;-}+export const config: ToolConfig = {+ name: "webSearch",+ icon: LuGlobe,+ displayText: "Searching the Web",+};// Static tool that uses context at execution time via experimental_contextexport const webSearchTool = tool({@@ -86,3 +88,9 @@ export const webSearchTool = tool({}},});++export interface SourceItem {+ url: string;+ title: string;+ publishedDate?: string;+}diff --git a/packages/database/supabase/functions/lib/ai/openai.ts b/packages/database/supabase/functions/lib/ai/openai.tsindex 4d6bb5ed73..4c33437239 100644--- a/packages/database/supabase/functions/lib/ai/openai.ts+++ b/packages/database/supabase/functions/lib/ai/openai.ts@@ -1,5 +1,5 @@import { createOpenAI } from "npm:@ai-sdk/[email protected]";export const openai = createOpenAI({- apiKey: Deno.env.get("OPENAI_API_KEY"),+ apiKey: Deno.env.get("OPENAI_API_KEY") ?? "",});