Skip to content

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.

refactor: move tools to new architecture

Brad Barbina5e1a9a2bdab
diff --git a/apps/erp/app/routes/api+/ai+/agents+/lib/index.ts b/apps/erp/app/routes/api+/ai+/agents+/lib/index.ts
deleted file mode 100644
index 12c26c32e7..0000000000
--- a/apps/erp/app/routes/api+/ai+/agents+/lib/index.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { Agent, type AgentConfig } from "@ai-sdk-tools/agents";
-import { UpstashProvider } from "@ai-sdk-tools/memory/upstash";
-import { openai } from "@ai-sdk/openai";
-import { UPSTASH_REDIS_REST_TOKEN, UPSTASH_REDIS_REST_URL } from "@carbon/auth";
-import { Redis } from "@upstash/redis";
-import PROFILE_PROMPT from "./profile.txt?raw";
-import SUGGESTIONS_INSTRUCTIONS from "./suggestions.txt?raw";
-import TITLE_INSTRUCTIONS from "./title.txt?raw";
-
-export function formatContextForLLM(context: AppContext): string {
- return `<company_info>
-<current_date>${context.currentDateTime}</current_date>
-<timezone>${context.timezone}</timezone>
-<company_name>${context.companyName}</company_name>
-<base_currency>${context.baseCurrency}</base_currency>
-<locale>${context.locale}</locale>
-</company_info>
-
-Important: Use the current date/time above for time-sensitive operations. User-specific information is maintained in your working memory.`;
-}
-
-export const COMMON_AGENT_RULES = `<behavior_rules>
-- Call tools immediately without explanatory text
-- Use parallel tool calls when possible
-- Provide specific numbers and actionable insights
-- Explain your reasoning
-- Lead with the most important information first
-- When presenting repeated structured data (lists of items, multiple entries, time series), always use markdown tables
-- Tables make data scannable and easier to compare - use them for any data with 2+ rows
-</behavior_rules>`;
-
-export interface AppContext {
- userId: string;
- fullName: string;
- companyName: string;
- baseCurrency: string;
- locale: string;
- currentDateTime: string;
- country?: string;
- city?: string;
- timezone: string;
- chatId: string;
- // Allow additional properties to satisfy Record<string, unknown> constraint
- [key: string]: unknown;
-}
-
-export function createAppContext(params: {
- userId: string;
- fullName: string;
- companyName: string;
- country?: string;
- city?: string;
- chatId: string;
- baseCurrency?: string;
- locale?: string;
- timezone?: string;
- teamId?: string;
-}) {
- return {
- userId: params.userId,
- fullName: params.fullName,
- companyName: params.companyName,
- country: params.country,
- city: params.city,
- chatId: params.chatId,
- baseCurrency: params.baseCurrency || "USD",
- locale: params.locale || "en-US",
- currentDateTime: new Date().toISOString(),
- timezone:
- params.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,
- teamId: params.teamId,
- };
-}
-
-export const memoryProvider = new UpstashProvider(
- new Redis({
- url: UPSTASH_REDIS_REST_URL,
- token: UPSTASH_REDIS_REST_TOKEN,
- })
-);
-
-export const createAgent = (config: AgentConfig<AppContext>) => {
- return new Agent({
- modelSettings: {
- parallel_tool_calls: true,
- },
- ...config,
- memory: {
- provider: memoryProvider,
- history: {
- enabled: true,
- limit: 10,
- },
- workingMemory: {
- enabled: true,
- template: PROFILE_PROMPT,
- scope: "user",
- },
- chats: {
- enabled: true,
- generateTitle: {
- model: openai("gpt-4.1-nano"),
- instructions: TITLE_INSTRUCTIONS,
- },
- generateSuggestions: {
- enabled: true,
- model: openai("gpt-4.1-nano"),
- limit: 5,
- instructions: SUGGESTIONS_INSTRUCTIONS,
- },
- },
- },
- });
-};
\ No newline at end of file
diff --git a/apps/erp/app/routes/api+/ai+/agents+/lib/profile.txt b/apps/erp/app/routes/api+/ai+/agents+/lib/profile.txt
deleted file mode 100644
index d2a6e9ddb5..0000000000
--- a/apps/erp/app/routes/api+/ai+/agents+/lib/profile.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-<user_profile>
-Name: [Learn from conversation]
-Role: [CFO, purchasing, production manager, salesman, etc.]
-</user_profile>
-
-<financial_focus>
-Key Metrics: [Revenue, purchase orders, lead time, on time deliveries, etc.]
-Recent Concerns: [Outstanding accounts payable]
-</financial_focus>
-
-<business_context>
-Industry: [If mentioned]
-Company Size: [SMB, startup, mid-market, public company]
-</business_context>
-
-<communication_preferences>
-Style: [Formal vs casual, technical vs simplified]
-Tone: [Professional, friendly, analytical, etc.]
-</communication_preferences>
\ No newline at end of file
diff --git a/apps/erp/app/routes/api+/ai+/agents+/lib/suggestions.txt b/apps/erp/app/routes/api+/ai+/agents+/lib/suggestions.txt
deleted file mode 100644
index ced76f5310..0000000000
--- a/apps/erp/app/routes/api+/ai+/agents+/lib/suggestions.txt
+++ /dev/null
@@ -1,56 +0,0 @@
-<instructions>
-Generate 5 brief follow-up suggestions (2-3 words each, max 5 words).
-
-<suggestion_guidelines>
-After showing data/metrics:
-- Compare periods or categories
-- Show related metrics
-- Visualize trends (charts/graphs)
-- Drill into details
-- Analyze patterns
-
-After analysis/reports:
-- Check underlying data
-- Create visualizations
-- Compare benchmarks
-- Explore segments
-
-After lists/tables:
-- Filter or sort
-- Show details
-- Visualize distribution
-- Analyze patterns
-</suggestion_guidelines>
-
-<visualization_support>
-When data would benefit from visual representation, suggest creating artifacts:
-- "Visualize trends" → Line chart of time series
-- "Chart distribution" → Bar/pie chart
-- "Graph comparison" → Multi-series chart
-- "Plot forecast" → Projection visualization
-</visualization_support>
-
-<examples>
-<example>
-After showing purchase orders:
-"Compare suppliers", "Show lead times", "Chart volumes", "Analyze delays", "Track deliveries"
-</example>
-
-<example>
-After displaying inventory levels:
-"Show turnover", "Chart movements", "Compare locations", "Analyze shortages", "Plot forecasts"
-</example>
-
-<example>
-After presenting financial metrics:
-"Compare periods", "Show cash flow", "Analyze ratios", "Chart performance", "Track budgets"
-</example>
-</examples>
-
-<rules>
-What NOT to suggest:
-- "Tell me more" (too generic)
-- "What else can you do?" (not contextual)
-- Repeating what was just shown
-</rules>
-</instructions>
\ No newline at end of file
diff --git a/apps/erp/app/routes/api+/ai+/agents+/lib/title.txt b/apps/erp/app/routes/api+/ai+/agents+/lib/title.txt
deleted file mode 100644
index 141caf2660..0000000000
--- a/apps/erp/app/routes/api+/ai+/agents+/lib/title.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Generate a concise title that reflects the user's main focus.
-
-- Identify the core subject or objective, not the specific question - Use descriptive phrases (e.g., "Budget Travel Tips" not "How to Travel on a Budget") Use title case (capitalize all principal words) - Exclude periods unless for abbreviations - Apply appropriate abbreviations (FYI, ASAP, etc.) Create a title for the discussion. Only return the title. Maximum 60 characters.
-```
\ No newline at end of file
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index c40640dac4..50f7994622 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -166,3 +166,14 @@ entrypoint = "./functions/post-stock-transfer/index.ts"
# Specifies static files to be bundled with the function. Supports glob patterns.
# For example, if you want to serve static HTML pages in your function:
# static_files = [ "./functions/post-stock-transfer/*.html" ]
+
+[functions.chat]
+enabled = true
+verify_jwt = true
+import_map = "./functions/chat/deno.json"
+# Uncomment to specify a custom file path to the entrypoint.
+# Supported file extensions are: .ts, .js, .mjs, .jsx, .tsx
+entrypoint = "./functions/chat/index.ts"
+# Specifies static files to be bundled with the function. Supports glob patterns.
+# For example, if you want to serve static HTML pages in your function:
+# static_files = [ "./functions/chat/*.html" ]
diff --git a/packages/database/supabase/functions/chat/.npmrc b/packages/database/supabase/functions/chat/.npmrc
new file mode 100644
index 0000000000..48c6388638
--- /dev/null
+++ b/packages/database/supabase/functions/chat/.npmrc
@@ -0,0 +1,3 @@
+# Configuration for private npm package dependencies
+# For more information on using private registries with Edge Functions, see:
+# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registries
diff --git a/packages/database/supabase/functions/chat/agents/main.ts b/packages/database/supabase/functions/chat/agents/main.ts
new file mode 100644
index 0000000000..c5cbee42d7
--- /dev/null
+++ b/packages/database/supabase/functions/chat/agents/main.ts
@@ -0,0 +1,37 @@
+import { openai } from "npm:@ai-sdk/[email protected]";
+
+
+import { purchasingAgent } from "./purchasing.ts";
+import { createAgent } from "./shared/agent.ts";
+import { formatContextForLLM } from "./shared/prompts.ts";
+
+
+export const mainAgent = createAgent({
+ name: "triage",
+ model: openai("gpt-4o-mini"),
+ temperature: 0.1,
+ modelSettings: {
+ toolChoice: {
+ type: "tool",
+ toolName: "handoff_to_agent",
+ },
+ },
+ instructions: (ctx) => `Route user requests to the appropriate specialist.
+
+<background-data>
+${formatContextForLLM(ctx)}
+
+<agent-capabilities>
+general: General questions, greetings, web search
+purchasing: creating purchase orders or getting quotes from suppliers
+parts: searching for parts or creating new parts
+suppliers: searching for suppliers or creating new suppliers
+</agent-capabilities>
+</background-data>`,
+ handoffs: [
+ purchasingAgent,
+ // partsAgent,
+ // suppliersAgent,
+ ],
+ maxTurns: 1,
+});
diff --git a/packages/database/supabase/functions/chat/agents/purchasing.ts b/packages/database/supabase/functions/chat/agents/purchasing.ts
new file mode 100644
index 0000000000..03a2d5461d
--- /dev/null
+++ b/packages/database/supabase/functions/chat/agents/purchasing.ts
@@ -0,0 +1,42 @@
+import { openai } from "npm:@ai-sdk/[email protected]";
+import {
+ createPurchaseOrderTool,
+ getPartTool,
+ getSupplierForPartsTool,
+ getSupplierTool,
+} from "../tools/purchasing.ts";
+import { createAgent } from "./shared/agent.ts";
+import {
+ COMMON_AGENT_RULES,
+ formatContextForLLM,
+} from "./shared/prompts.ts";
+
+export const purchasingAgent = createAgent({
+ name: "purchasing",
+ model: openai("gpt-4o-mini"),
+ temperature: 0.3,
+ instructions: (
+ ctx,
+ ) => `You are a purchasing specialist for ${ctx.companyName}. Create purchase orders or get quotes from suppliers.
+
+<background-data>
+${formatContextForLLM(ctx)}
+</background-data>
+
+${COMMON_AGENT_RULES}
+
+<guidelines>
+- For direct queries: lead with results, add context
+</guidelines>`,
+ tools: {
+ // @ts-expect-error - version mismatch between [email protected] and @ai-sdk-tools/[email protected]
+ getPart: getPartTool,
+ // @ts-expect-error - version mismatch between [email protected] and @ai-sdk-tools/[email protected]
+ getSupplier: getSupplierTool,
+ // @ts-expect-error - version mismatch between [email protected] and @ai-sdk-tools/[email protected]
+ getSupplierForParts: getSupplierForPartsTool,
+ // @ts-expect-error - version mismatch between [email protected] and @ai-sdk-tools/[email protected]
+ createPurchaseOrder: createPurchaseOrderTool,
+ },
+ maxTurns: 10,
+});
diff --git a/packages/database/supabase/functions/chat/agents/shared/agent.ts b/packages/database/supabase/functions/chat/agents/shared/agent.ts
new file mode 100644
index 0000000000..9e22905c44
--- /dev/null
+++ b/packages/database/supabase/functions/chat/agents/shared/agent.ts
@@ -0,0 +1,48 @@
+import { Agent, type AgentConfig } from "npm:@ai-sdk-tools/[email protected]";
+import { UpstashProvider } from "npm:@ai-sdk-tools/[email protected]/upstash";
+import { openai } from "npm:@ai-sdk/[email protected]";
+import { Redis } from "npm:@upstash/[email protected]";
+import { ChatContext } from "./context.ts";
+import { PROFILE_PROMPT, SUGGESTION_PROMPT, TITLE_PROMPT } from "./prompts.ts";
+
+
+export const memoryProvider = new UpstashProvider(
+ new Redis({
+ url: Deno.env.get("UPSTASH_REDIS_REST_URL") ?? "",
+ token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN") ?? "",
+ })
+);
+
+export const createAgent = (config: AgentConfig<ChatContext>) => {
+ return new Agent({
+ modelSettings: {
+ parallel_tool_calls: true,
+ },
+ ...config,
+ memory: {
+ provider: memoryProvider,
+ history: {
+ enabled: true,
+ limit: 10,
+ },
+ workingMemory: {
+ enabled: true,
+ template: PROFILE_PROMPT,
+ scope: "user",
+ },
+ chats: {
+ enabled: true,
+ generateTitle: {
+ model: openai("gpt-4.1-nano"),
+ instructions: TITLE_PROMPT,
+ },
+ generateSuggestions: {
+ enabled: true,
+ model: openai("gpt-4.1-nano"),
+ limit: 5,
+ instructions: SUGGESTION_PROMPT,
+ },
+ },
+ },
+ });
+};
\ No newline at end of file
diff --git a/packages/database/supabase/functions/chat/agents/shared/context.ts b/packages/database/supabase/functions/chat/agents/shared/context.ts
new file mode 100644
index 0000000000..aabbdcf00b
--- /dev/null
+++ b/packages/database/supabase/functions/chat/agents/shared/context.ts
@@ -0,0 +1,56 @@
+import SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";
+import { Transaction } from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";
+import { DB } from "../../../lib/database.ts";
+import { Database } from "../../../lib/types.ts";
+
+export interface ChatContext {
+ db: Transaction<DB>;
+ client: SupabaseClient<Database>;
+ userId: string;
+ companyId: string;
+ fullName: string;
+ companyName: string;
+ baseCurrency: string;
+ locale: string;
+ currentDateTime: string;
+ country?: string;
+ city?: string;
+ timezone: string;
+ chatId: string;
+ // Allow additional properties to satisfy Record<string, unknown> constraint
+ [key: string]: unknown;
+}
+
+export function createChatContext(params: {
+ userId: string;
+ companyId: string;
+ db: Transaction<DB>;
+ client: SupabaseClient<Database>;
+ fullName: string;
+ companyName: string;
+ country?: string;
+ city?: string;
+ chatId: string;
+ baseCurrency?: string;
+ locale?: string;
+ timezone?: string;
+
+}) {
+ return {
+ userId: params.userId,
+ companyId: params.companyId,
+ db: params.db,
+ client: params.client,
+ fullName: params.fullName,
+ companyName: params.companyName,
+ country: params.country,
+ city: params.city,
+ chatId: params.chatId,
+ baseCurrency: params.baseCurrency || "USD",
+ locale: params.locale || "en-US",
+ currentDateTime: new Date().toISOString(),
+ timezone:
+ params.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,
+
+ };
+}
\ No newline at end of file
diff --git a/packages/database/supabase/functions/chat/agents/shared/prompts.ts b/packages/database/supabase/functions/chat/agents/shared/prompts.ts
new file mode 100644
index 0000000000..5a540d493e
--- /dev/null
+++ b/packages/database/supabase/functions/chat/agents/shared/prompts.ts
@@ -0,0 +1,107 @@
+import { ChatContext } from "./context.ts";
+
+export const PROFILE_PROMPT = `<user_profile>
+Name: [Learn from conversation]
+Role: [CFO, purchasing, production manager, salesman, etc.]
+</user_profile>
+
+<financial_focus>
+Key Metrics: [Revenue, purchase orders, lead time, on time deliveries, etc.]
+Recent Concerns: [Outstanding accounts payable]
+</financial_focus>
+
+<business_context>
+Industry: [If mentioned]
+Company Size: [SMB, startup, mid-market, public company]
+</business_context>
+
+<communication_preferences>
+Style: [Formal vs casual, technical vs simplified]
+Tone: [Professional, friendly, analytical, etc.]
+</communication_preferences>`;
+
+export const TITLE_PROMPT = `Generate a concise title that reflects the user's main focus.
+
+- Identify the core subject or objective, not the specific question - Use descriptive phrases (e.g., "Budget Travel Tips" not "How to Travel on a Budget") Use title case (capitalize all principal words) - Exclude periods unless for abbreviations - Apply appropriate abbreviations (FYI, ASAP, etc.) Create a title for the discussion. Only return the title. Maximum 60 characters.`;
+
+export const SUGGESTION_PROMPT = `<instructions>
+Generate 5 brief follow-up suggestions (2-3 words each, max 5 words).
+
+<suggestion_guidelines>
+After showing data/metrics:
+- Compare periods or categories
+- Show related metrics
+- Visualize trends (charts/graphs)
+- Drill into details
+- Analyze patterns
+
+After analysis/reports:
+- Check underlying data
+- Create visualizations
+- Compare benchmarks
+- Explore segments
+
+After lists/tables:
+- Filter or sort
+- Show details
+- Visualize distribution
+- Analyze patterns
+</suggestion_guidelines>
+
+<visualization_support>
+When data would benefit from visual representation, suggest creating artifacts:
+- "Visualize trends" → Line chart of time series
+- "Chart distribution" → Bar/pie chart
+- "Graph comparison" → Multi-series chart
+- "Plot forecast" → Projection visualization
+</visualization_support>
+
+<examples>
+<example>
+After showing purchase orders:
+"Compare suppliers", "Show lead times", "Chart volumes", "Analyze delays", "Track deliveries"
+</example>
+
+<example>
+After displaying inventory levels:
+"Show turnover", "Chart movements", "Compare locations", "Analyze shortages", "Plot forecasts"
+</example>
+
+<example>
+After presenting financial metrics:
+"Compare periods", "Show cash flow", "Analyze ratios", "Chart performance", "Track budgets"
+</example>
+</examples>
+
+<rules>
+What NOT to suggest:
+- "Tell me more" (too generic)
+- "What else can you do?" (not contextual)
+- Repeating what was just shown
+</rules>
+</instructions>`;
+
+
+
+export function formatContextForLLM(context: ChatContext): string {
+ return `<company_info>
+<current_date>${context.currentDateTime}</current_date>
+<timezone>${context.timezone}</timezone>
+<company_name>${context.companyName}</company_name>
+<base_currency>${context.baseCurrency}</base_currency>
+<locale>${context.locale}</locale>
+</company_info>
+
+Important: Use the current date/time above for time-sensitive operations. User-specific information is maintained in your working memory.`;
+}
+
+export const COMMON_AGENT_RULES = `<behavior_rules>
+- Call tools immediately without explanatory text
+- Use parallel tool calls when possible
+- Provide specific numbers and actionable insights
+- Explain your reasoning
+- Lead with the most important information first
+- When presenting repeated structured data (lists of items, multiple entries, time series), always use markdown tables
+- Tables make data scannable and easier to compare - use them for any data with 2+ rows
+</behavior_rules>`;
+
diff --git a/packages/database/supabase/functions/chat/deno.json b/packages/database/supabase/functions/chat/deno.json
new file mode 100644
index 0000000000..f6ca8454c5
--- /dev/null
+++ b/packages/database/supabase/functions/chat/deno.json
@@ -0,0 +1,3 @@
+{
+ "imports": {}
+}
diff --git a/packages/database/supabase/functions/chat/index.ts b/packages/database/supabase/functions/chat/index.ts
new file mode 100644
index 0000000000..fd817e418f
--- /dev/null
+++ b/packages/database/supabase/functions/chat/index.ts
@@ -0,0 +1,32 @@
+// Follow this setup guide to integrate the Deno language server with your editor:
+// https://deno.land/manual/getting_started/setup_your_environment
+// This enables autocomplete, go to definition, etc.
+
+// Setup type definitions for built-in Supabase Runtime APIs
+import "jsr:@supabase/functions-js/edge-runtime.d.ts"
+
+console.log("Hello from Functions!")
+
+Deno.serve(async (req) => {
+ const { name } = await req.json()
+ const data = {
+ message: `Hello ${name}!`,
+ }
+
+ return new Response(
+ JSON.stringify(data),
+ { headers: { "Content-Type": "application/json" } },
+ )
+})
+
+/* To invoke locally:
+
+ 1. Run `supabase start` (see: https://supabase.com/docs/reference/cli/supabase-start)
+ 2. Make an HTTP request:
+
+ curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/chat' \
+ --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0' \
+ --header 'Content-Type: application/json' \
+ --data '{"name":"Functions"}'
+
+*/
diff --git a/packages/database/supabase/functions/chat/tools/parts.ts b/packages/database/supabase/functions/chat/tools/parts.ts
new file mode 100644
index 0000000000..e688c9e450
--- /dev/null
+++ b/packages/database/supabase/functions/chat/tools/parts.ts
@@ -0,0 +1,92 @@
+import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+import { tool } from "npm:[email protected]";
+import z from "npm:zod@^3.24.1/v3";
+import { ChatContext } from "../agents/shared/context.ts";
+
+const model = new Supabase.ai.Session("gte-small");
+
+export const getPartSchema = z
+ .object({
+ readableId: z.string().optional(),
+ description: z.string().optional(),
+ })
+ .refine((data) => data.readableId || data.description, {
+ message: "Either readableId or description must be provided",
+ });
+
+export const getPartTool = tool({
+ description: "Search for a part by description or readable id",
+ inputSchema: getPartSchema,
+ execute: async function (args, executionOptions) {
+ const context = executionOptions.experimental_context as ChatContext;
+ let { readableId, description } = args;
+
+ if (readableId) {
+ const [part, supplierPart] = await Promise.all([
+ context.client
+ .from("item")
+ .select("*")
+ .or(
+ `readableId.eq.${readableId},readableIdWithRevision.eq.${readableId}`
+ )
+ .eq("companyId", context.companyId)
+ .order("revision", { ascending: false })
+ .limit(1),
+ context.client
+ .from("supplierPart")
+ .select("*, item(*)")
+ .eq("supplierPartId", readableId)
+ .eq("companyId", context.companyId)
+ .single(),
+ ]);
+
+ if (supplierPart.data) {
+ return {
+ id: supplierPart.data.itemId,
+ name: supplierPart.data.item?.name,
+ description: supplierPart.data.item?.description,
+ supplierId: supplierPart.data.supplierId,
+ };
+ }
+ if (part.data?.[0]) {
+ return {
+ id: part.data[0].id,
+ name: part.data[0].name,
+ description: part.data[0].description,
+ };
+ }
+
+ if (!description) {
+ description = readableId;
+ } else {
+ return null;
+ }
+ }
+
+ if (description) {
+ const embedding = await generateEmbedding(description);
+ const search = await context.client.rpc("items_search", {
+ query_embedding: JSON.stringify(embedding),
+ match_threshold: 0.7,
+ match_count: 10,
+ p_company_id: context.companyId,
+ });
+
+ if (search.data && search.data.length > 0) {
+ return search.data;
+ }
+ }
+
+ return null;
+ },
+});
+
+async function generateEmbedding(text: string): Promise<number[]> {
+ const embedding = await model.run(text, {
+ mean_pool: true,
+ normalize: true,
+ });
+
+ return embedding as number[];
+}
+
diff --git a/packages/database/supabase/functions/chat/tools/purchasing.ts b/packages/database/supabase/functions/chat/tools/purchasing.ts
new file mode 100644
index 0000000000..62b625a265
--- /dev/null
+++ b/packages/database/supabase/functions/chat/tools/purchasing.ts
@@ -0,0 +1,255 @@
+import { Transaction } from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";
+import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+import { tool } from "npm:[email protected]";
+import z from "npm:zod@^3.24.1/v3";
+import { getCurrencyByCode } from "../../lib/api/accounting.ts";
+import {
+ deletePurchaseOrder,
+ getSupplier as getSupplierById,
+ getSupplierPayment,
+ getSupplierShipping,
+ insertSupplierInteraction,
+} from "../../lib/api/purchasing.ts";
+import { DB } from "../../lib/database.ts";
+import { getNextSequence } from "../../shared/get-next-sequence.ts";
+import { ChatContext } from "../agents/shared/context.ts";
+
+
+
+export const createPurchaseOrderSchema = z.object({
+ supplierId: z.string(),
+ parts: z.array(
+ z.object({
+ partId: z.string(),
+ quantity: z.number().positive().default(1),
+ })
+ ),
+})
+
+export const createPurchaseOrderTool = tool({
+ description:
+ "Create a purchase order from a list of parts and a supplier",
+ inputSchema: createPurchaseOrderSchema,
+ execute: async function (args, executionOptions) {
+ const context = executionOptions.experimental_context as ChatContext;
+ const [
+ nextSequence,
+ supplierInteraction,
+ supplier,
+ supplierPayment,
+ supplierShipping,
+ // purchaser
+ ] = await Promise.all([
+ getNextSequence(
+ context.db as unknown as Transaction<DB>,
+ "purchaseOrder",
+ context.companyId
+ ),
+ insertSupplierInteraction(context.db, context.companyId, args.supplierId),
+ getSupplierById(context.db, args.supplierId),
+ getSupplierPayment(context.db, args.supplierId),
+ getSupplierShipping(context.db, args.supplierId),
+ // getEmployeeJob(client, context.userId, context.companyId),
+ ]);
+
+ if (!supplierInteraction) {
+ return {
+ error: "Failed to create supplier interaction",
+ };
+ }
+
+ if (!supplier) {
+ return {
+ error: "Supplier not found",
+ };
+ }
+ if (!supplierPayment) {
+ return {
+ error: "Supplier payment not found",
+ };
+ }
+ if (!supplierShipping) {
+ return {
+ error: "Supplier shipping not found",
+ };
+ }
+
+ const purchaseOrder = {
+ purchaseOrderId: nextSequence,
+ supplierId: args.supplierId,
+ supplierInteractionId: supplierInteraction?.id! ?? null,
+ exchangeRate: 1,
+ exchangeRateUpdatedAt: new Date().toISOString(),
+ companyId: context.companyId,
+ createdBy: context.userId,
+ };
+
+ const {
+ paymentTermId,
+ invoiceSupplierId,
+ invoiceSupplierContactId,
+ invoiceSupplierLocationId,
+ } = supplierPayment;
+
+ const { shippingMethodId, shippingTermId } = supplierShipping;
+
+ if (supplier.currencyCode) {
+ const currency = await getCurrencyByCode(
+ // @ts-ignore: kysely transaction type compatibility
+ context.db,
+ context.companyId,
+ supplier.currencyCode
+ );
+ if (currency) {
+ purchaseOrder.exchangeRate = currency.exchangeRate ?? 1;
+ purchaseOrder.exchangeRateUpdatedAt = new Date().toISOString();
+ }
+ }
+
+ const order = await context.db
+ .insertInto("purchaseOrder")
+ .values([purchaseOrder])
+ .returning(["id", "purchaseOrderId"])
+ .executeTakeFirst();
+
+ if (!order) {
+ return {
+ error: "Failed to create purchase order",
+ };
+ }
+
+ const purchaseOrderId = order.id;
+ const locationId = null; // TODO
+
+ if (!purchaseOrderId) {
+ return {
+ error: "Failed to create purchase order",
+ };
+ }
+
+ try {
+ await Promise.all([
+ context.db
+ .insertInto("purchaseOrderDelivery")
+ .values({
+ id: purchaseOrderId,
+ locationId: locationId,
+ shippingMethodId: shippingMethodId,
+ shippingTermId: shippingTermId,
+ companyId: context.companyId,
+ })
+ .executeTakeFirstOrThrow(),
+ context.db
+ .insertInto("purchaseOrderPayment")
+ .values({
+ id: purchaseOrderId,
+ invoiceSupplierId: invoiceSupplierId,
+ invoiceSupplierContactId: invoiceSupplierContactId,
+ invoiceSupplierLocationId: invoiceSupplierLocationId,
+ paymentTermId: paymentTermId,
+ companyId: context.companyId,
+ })
+ .executeTakeFirstOrThrow(),
+ ]);
+
+ // Create purchase order lines for each part
+ await Promise.all(
+ args.parts.map(async (part: { partId: string; quantity: number }) => {
+ // Get item details
+ const [item, supplierPart] = await Promise.all([
+ context.db
+ .selectFrom("item")
+ .select([
+ "id",
+ "name",
+ "readableIdWithRevision",
+ "type",
+ "unitOfMeasureCode",
+ ])
+ .where("id", "=", part.partId)
+ .where("companyId", "=", context.companyId)
+ .executeTakeFirst(),
+ context.db
+ .selectFrom("supplierPart")
+ .selectAll()
+ .where("itemId", "=", part.partId)
+ .where("companyId", "=", context.companyId)
+ .where("supplierId", "=", args.supplierId)
+ .executeTakeFirst(),
+ ]);
+
+ if (!item) {
+ throw new Error(`Item not found: ${part.partId}`);
+ }
+
+ // Get item cost and replenishment info
+ const [itemCost, itemReplenishment] = await Promise.all([
+ context.db
+ .selectFrom("itemCost")
+ .select(["unitCost"])
+ .where("itemId", "=", part.partId)
+ .executeTakeFirst(),
+ context.db
+ .selectFrom("itemReplenishment")
+ .select([
+ "purchasingUnitOfMeasureCode",
+ "conversionFactor",
+ "leadTime",
+ ])
+ .where("itemId", "=", part.partId)
+ .executeTakeFirst(),
+ ]);
+
+ // Create the purchase order line
+ return context.db
+ .insertInto("purchaseOrderLine")
+ .values({
+ purchaseOrderId: purchaseOrderId,
+ itemId: part.partId,
+ description: item.name,
+ purchaseOrderLineType: item.type,
+ purchaseQuantity: part.quantity,
+ supplierUnitPrice:
+ (supplierPart?.unitPrice ?? itemCost?.unitCost ?? 0) /
+ purchaseOrder.exchangeRate,
+ supplierShippingCost: 0,
+ purchaseUnitOfMeasureCode:
+ supplierPart?.supplierUnitOfMeasureCode ??
+ itemReplenishment?.purchasingUnitOfMeasureCode ??
+ item.unitOfMeasureCode ??
+ "EA",
+ inventoryUnitOfMeasureCode: item.unitOfMeasureCode ?? "EA",
+ conversionFactor:
+ supplierPart?.conversionFactor ??
+ itemReplenishment?.conversionFactor ??
+ 1,
+ locationId: locationId,
+ shelfId: null,
+ supplierTaxAmount: 0,
+ companyId: context.companyId,
+ createdBy: context.userId,
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+ })
+ );
+
+ return order;
+ } catch (error) {
+ if (purchaseOrderId) {
+ await deletePurchaseOrder(context.db, purchaseOrderId);
+ }
+ return {
+ error: `Failed to create purchase order details: ${error.message}`,
+ };
+ }
+ },
+});
+
+// Re-export tools from other modules for convenience
+export { getPartTool } from "./parts.ts";
+export {
+ getSupplierForPartsTool,
+ getSupplierTool
+} from "./suppliers.ts";
+
diff --git a/packages/database/supabase/functions/chat/tools/suppliers.ts b/packages/database/supabase/functions/chat/tools/suppliers.ts
new file mode 100644
index 0000000000..e98e54de43
--- /dev/null
+++ b/packages/database/supabase/functions/chat/tools/suppliers.ts
@@ -0,0 +1,210 @@
+import SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";
+import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+import { tool } from "npm:[email protected]";
+import z from "npm:zod@^3.24.1/v3";
+import { Database } from "../../lib/types.ts";
+import { ChatContext } from "../agents/shared/context.ts";
+
+const model = new Supabase.ai.Session("gte-small");
+
+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, or partIds 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;
+
+ if (args.id) {
+ const supplier = await context.client
+ .from("supplier")
+ .select("*")
+ .eq("id", args.id)
+ .eq("companyId", context.companyId)
+ .single();
+ if (supplier.data) {
+ return {
+ 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(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;
+ },
+});
+
+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;
+ return await getSuppliersForParts(context.client, args.partIds, context);
+ },
+});
+
+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) {
+ return {
+ id: preferredSupplier.preferredSupplierId,
+ };
+ }
+
+ const firstSupplier = supplierParts.data?.find(
+ (p) => p.itemId === partIds[0]
+ );
+ if (firstSupplier) {
+ return {
+ 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 {
+ 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 {
+ id: mostFrequentSupplierId,
+ unitPrice: supplier?.unitPrice,
+ supplierUnitOfMeasureCode: supplier?.supplierUnitOfMeasureCode,
+ };
+ }
+
+ // Return null if no supplier was found
+ return null;
+}
+
+async function generateEmbedding(text: string): Promise<number[]> {
+ const embedding = await model.run(text, {
+ mean_pool: true,
+ normalize: true,
+ });
+
+ return embedding as number[];
+}
+