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
fix: pin ai packages in chat function
Brad Barbin27ea94ab0b52
diff --git a/apps/erp/app/components/Agent/Agent.ee.tsx b/apps/erp/app/components/Agent/Agent.ee.tsxindex 977c11503e..60d6a6b79a 100644--- a/apps/erp/app/components/Agent/Agent.ee.tsx+++ b/apps/erp/app/components/Agent/Agent.ee.tsx@@ -341,32 +341,60 @@ export function Agent() {setIsRateLimited(false);- if (result.finishReason === "tool-calls") {- for await (const toolCall of result.toolCalls) {- await addToolCalls(result.toolCalls);-- const toolResponse = await carbon.functions.invoke("mcp", {- body: JSON.stringify({- jsonrpc: "2.0",- method: "tools/call",- id: ++idRef.current,- params: {- name: toolCall.toolName,- arguments: JSON.parse(toolCall.args),+ // Handle different finish reasons from the AI SDK+ switch (result.finishReason) {+ case "tool-calls":+ // Handle tool calls+ for await (const toolCall of result.toolCalls) {+ await addToolCalls(result.toolCalls);++ const toolResponse = await carbon.functions.invoke("mcp", {+ body: JSON.stringify({+ jsonrpc: "2.0",+ method: "tools/call",+ id: ++idRef.current,+ params: {+ name: toolCall.toolName,+ arguments: JSON.parse(toolCall.args),+ },+ }),+ headers: {+ "x-company-id": companyId,+ "x-user-id": userId,},- }),- headers: {- "x-company-id": companyId,- "x-user-id": userId,- },- });+ });- const response = toolResponse?.data;+ const response = toolResponse?.data;- if ("content" in response?.result) {- await addToolResult(toolCall, response.result.content);+ if ("content" in response?.result) {+ await addToolResult(toolCall, response.result.content);+ }}- }+ break;++ case "end-turn":+ case "end_turn":+ // End turn means the assistant has completed its response+ // No additional action needed, just set status to ready+ break;++ case "stop":+ // Normal completion+ break;++ case "length":+ // Maximum token length reached+ console.warn("Maximum token length reached");+ break;++ case "error":+ // Error occurred during generation+ console.error("Error during generation");+ break;++ default:+ // Unknown finish reason+ console.warn(`Unknown finish reason: ${result.finishReason}`);}setStatus("ready");diff --git a/llm/cache/chat-ai-sdk-info.md b/llm/cache/chat-ai-sdk-info.mdnew file mode 100644index 0000000000..b64ae5b20e--- /dev/null+++ b/llm/cache/chat-ai-sdk-info.md@@ -0,0 +1,101 @@+# Chat Function and AI SDK Information++## Chat Function Implementation++The Carbon system implements a chat function using the `@ai-sdk/anthropic` package located in `/packages/database/supabase/functions/chat/index.ts`.++### Key Components:++**Supabase Edge Function**:+- Located at `/packages/database/supabase/functions/chat/index.ts`+- Uses `@ai-sdk/anthropic` to create an Anthropic model instance+- Configured with Claude 3.7 Sonnet model (`claude-3-7-sonnet-20250219`)+- Handles authentication via API key or Bearer token+- Supports both Carbon MCP API key and standard Supabase auth++**Frontend Agent Component**:+- Located at `/apps/erp/app/components/Agent/Agent.ee.tsx`+- Implements a chat interface with tool calling capabilities+- Uses `LanguageModelV1Prompt` type from the `ai` package+- Handles message history and conversation state++### API Structure:++```typescript+// Request body structure+{+ prompt: LanguageModelV1Prompt,+ mode: {+ type: "regular",+ tools: Array<{+ type: "function",+ name: string,+ description: string,+ parameters: object+ }>+ },+ inputFormat: "messages",+ temperature: number+}+```++## @ai-sdk/anthropic Package Usage++**Model Creation**:+```typescript+const model = createAnthropic({+ apiKey: Deno.env.get("ANTHROPIC_API_KEY"),+})("claude-3-7-sonnet-20250219");+```++**Generation Call**:+```typescript+const result = await model.doGenerate(body);+```++The system uses the `LanguageModelV1CallOptions` type from the `ai` package for request validation.++## Stop/Finish Reasons++### Finish Reason Handling:++The chat system checks for `finishReason` in the response:++```typescript+if (result.finishReason === "tool-calls") {+ // Handle tool calls+ for await (const toolCall of result.toolCalls) {+ // Process each tool call+ }+}+```++### Common Finish Reasons:+- `"tool-calls"`: When the model wants to call tools/functions+- `"stop"`: Normal completion+- `"length"`: Hit token limit+- `"error"`: Error occurred during generation++### Tool Call Flow:+1. Model returns `finishReason: "tool-calls"` with `toolCalls` array+2. Frontend processes tool calls through MCP (Model Context Protocol)+3. Tool results are added back to conversation+4. New generation request is triggered to continue conversation++## Authentication and Headers++The chat function supports two authentication methods:+1. **Carbon MCP API Key**: Via `CARBON_MCP_API_KEY` environment variable+2. **Bearer Token**: Standard Supabase authentication with `Authorization: Bearer <token>` header++Required headers:+- `x-company-id`: Company identifier+- `x-user-id`: User identifier (when using MCP API key)++## Error Handling++The system includes error handling for:+- `APICallError` from the AI SDK+- Authentication failures (401 Unauthorized)+- General exceptions with JSON error responses+- Proper CORS headers for cross-origin requests\ No newline at end of filediff --git a/packages/database/supabase/functions/chat/index.ts b/packages/database/supabase/functions/chat/index.tsindex 502138ee52..0b5c423fe2 100644--- a/packages/database/supabase/functions/chat/index.ts+++ b/packages/database/supabase/functions/chat/index.ts@@ -1,6 +1,6 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { createAnthropic } from "npm:@ai-sdk/anthropic";-import { APICallError, LanguageModelV1CallOptions } from "npm:ai";+import { createAnthropic } from "npm:@ai-sdk/[email protected]";+import { APICallError, LanguageModelV1CallOptions } from "npm:[email protected]";import { z } from "npm:zod";import { corsHeaders } from "../lib/headers.ts";