### OpenAI Prompt for Voice Data to JSON Conversion Source: https://github.com/connectai-e/base-easywrite/blob/main/README.md This prompt guides the OpenAI model to convert spoken or transcribed text into a structured JSON array representing inventory records. It provides examples of input text and desired JSON output, including handling date formatting, product name matching against a database, and supplier information. It also specifies fallback logic for missing information like dates and supplier names. The input includes product names, supplier lists, today's date, the current year, and the user's content. The output is a JSON array of inventory records. ```Go prompt := `你是仓库管理员,产品数据库有如下商品:【` + productNames + `】。供应商有:【` + suppliers + `】,你可以将下面的文本转换为json数组的入库记录单。 下面是部分实例 --- Q: 【李峰供应商,送来吊龙三斤,总价143元】 A: [{ "date":` + today + `, "productName":"吊龙", "companyName":"李峰", "totalNumber":3, "totalPrice":143, }] Q:【3月23号,生菜4.2斤,12块6,平菇,1.1斤,5块5】 A: [{ "date":"2023/03/23", "productName": "生菜", "companyName":"", "totalNumber": 4.2, "totalPrice": 12.6 }, { "date":"2023/03/23", "productName": "平菇", "companyName":"", "totalNumber": 1.1, "totalPrice": 5.5 }] Q: 【线下自购莲藕100斤 合计189元】 A: [{ "date":` + today + `, "productName":"藕", "companyName":"线下自购", "totalNumber":100, "totalPrice":189, }] Q: 【6月3日,供应商小军收入豆奶10瓶子 合计100元】 A: [{ "date":"2023/06/03", "productName":"唯怡豆奶(塑框玻璃瓶)", "companyName":"小军", "totalNumber":10, "totalPrice"'':100, }] ---- 那么,Q:【` + content + `】 转换成json数组的入库单结果是什么?直接返回 json数组的代码,不要其他提示信息。 请注意: 1. 如果没说明时间,那么 date 字段就是 UTC+8 的现在日期; 2. 如果没说明年份,默认是` + strconv.Itoa(year) + `年,比如 3月23号,date 就是` + strconv.Itoa(year) + `/03/23; 3. productName 根据产品数据库中的名称,对提供的信息进行转换,结果请从产品数据库中选择,比如提供的信息是 雪花超级勇闯(蓝Super X),产品数据库中 是 雪花超级勇闯(蓝SuperX),那么请返回 雪花超级勇闯(蓝SuperX); 4. companyName 请从供应商中选择,如果没有匹配的,companyName 为空字符串; 5. 可能会出现部分错别字,比如把 “5斤” 写成 “5金”。` ``` -------------------------------- ### Create Feishu Bitable Inventory Records (Go) Source: https://context7.com/connectai-e/base-easywrite/llms.txt Creates inventory records in a Feishu Bitable table. It matches products and suppliers based on provided maps and generates a link to the newly created records. Requires Feishu API client and initialization configuration. ```go // Create inventory records in Feishu Bitable package lark import ( "context" "inventory-manager/initialization" larkbitable "github.com/larksuite/oapi-sdk-go/v3/service/bitable/v1" "time" ) type ReceiptRecord struct { Date string `json:"date"` // 2025/10/09 ProductName string `json:"productName"` // 大白菜 CompanyName string `json:"companyName"` // 王峰 TotalNumber float64 `json:"totalNumber"` // 30 TotalPrice float64 `json:"totalPrice"` // 100 } func CreateTableRecord(config initialization.Config, recordList []*ReceiptRecord, products map[string][2]string, suppliers map[string]string) (string, string, error) { records := make([]*larkbitable.AppTableRecord, 0) for _, item := range recordList { // Parse date to timestamp t, err := time.Parse("2006/01/02", item.Date) if err != nil { t = time.Now() } timestamp := t.UnixMilli() // Match product ID ridAndCompany := products[item.ProductName] productId := ridAndCompany[0] defaultSupplier := ridAndCompany[1] // Match supplier ID supplierId := suppliers[item.CompanyName] record := map[string]interface{}{ "日期": timestamp, "产品名称": []string{productId}, "实收": item.TotalNumber, "金额": item.TotalPrice, } if item.CompanyName != defaultSupplier && supplierId != "" { record["非主供应商"] = true record["本次供应商"] = []string{supplierId} } records = append(records, larkbitable.NewAppTableRecordBuilder().Fields(record).Build()) } // Batch create records client := initialization.GetLarkClient() req := larkbitable.NewBatchCreateAppTableRecordReqBuilder(). AppToken(config.BitableAppToken). TableId(config.ReceiptBitableId). Body(larkbitable.NewBatchCreateAppTableRecordReqBodyBuilder(). Records(records). Build()). Build() resp, err := client.Bitable.AppTableRecord.BatchCreate(context.Background(), req) if err != nil { return "", "", err } // Generate result link firstRecordId := *resp.Data.Records[0].RecordId link := `https://` + config.BitableHost + `/base/` + config.BitableAppToken + `?table=` + config.ReceiptBitableId + `&record=` + firstRecordId return "录入成功", link, nil } // Input: [{date: "2025/10/09", productName: "大白菜", companyName: "王峰", totalNumber: 30, totalPrice: 100}] // Output: "录入成功", "https://fork-way.feishu.cn/base/Norqbd3anazOMlsceoEcbeIMn2g?table=tblghsq6TY3XktYG&record=recXXX" ``` -------------------------------- ### Load Application Configuration using Go Source: https://context7.com/connectai-e/base-easywrite/llms.txt Loads application configuration from a YAML file and allows overrides via environment variables. It utilizes the Viper library for configuration management. The function returns a Config struct populated with settings. ```go // Load configuration from config.yaml package initialization import ( "github.com/spf13/viper" ) type Config struct { FeishuAppId string FeishuAppSecret string FeishuBotName string BitableHost string BitableAppToken string ProductBitableId string ReceiptBitableId string ReceiptBitableView string SupplierBitableId string OpenaiApiKeys []string AliAccessKeyId string AliAccessKeySecret string HttpPort int } func LoadConfig(cfgPath string) *Config { viper.SetConfigFile(cfgPath) viper.ReadInConfig() viper.AutomaticEnv() // Override with environment variables return &Config{ FeishuAppId: viper.GetString("APP_ID"), FeishuAppSecret: viper.GetString("APP_SECRET"), FeishuBotName: viper.GetString("BOT_NAME"), BitableHost: viper.GetString("BITABLE_HOST"), BitableAppToken: viper.GetString("BITABLE_APP_TOKEN"), ProductBitableId: viper.GetString("PRODUCT_BITABLE_ID"), ReceiptBitableId: viper.GetString("RECEIPT_BITABLE_ID"), SupplierBitableId: viper.GetString("SUPPLIER_BITABlE_ID"), OpenaiApiKeys: getViperStringArray("OPENAI_KEY", nil), AliAccessKeyId: viper.GetString("ALI_ACCESSKEY_ID"), AliAccessKeySecret: viper.GetString("ALI_ACCESSKEY_SECRET"), HttpPort: viper.GetInt("HTTP_PORT"), } } // Example config.yaml: // APP_ID: cli_a4172ca48e7b9013 // APP_SECRET: tWFwzQNzkD.. // BOT_NAME: ChatGPT // OPENAI_KEY: sk-zTeWCJSr... // BITABLE_HOST: fork-way.feishu.cn // BITABLE_APP_TOKEN: Norqbd3anazOMlsceoEcbeIMn2g // PRODUCT_BITABLE_ID: tblVY2JwWJfbzWzS // ALI_ACCESSKEY_ID: LTAI5tEBvzfgfjZSy... // HTTP_PORT: 9001 ``` -------------------------------- ### Configuration File for Base-EasyWrite Source: https://github.com/connectai-e/base-easywrite/blob/main/README.md This JSON5 configuration file outlines the necessary parameters for deploying and running the Base-EasyWrite application. It includes settings for Feishu BOT integration, OpenAI API access (model, token limits, key), multi-dimensional table (Bitable) connection details (host, app token, table IDs for products, suppliers, and receipts), Alibaba Cloud OCR credentials, and server ports for HTTP and HTTPS. ```JSON5 #飞书BOT配置 APP_ID: cli_a4172ca48e7b9013 APP_SECRET: tWFwzQNzkD.. APP_ENCRYPT_KEY: 39XCQUA00uqeDC.. APP_VERIFICATION_TOKEN: CYyoRCIz.. BOT_NAME: ChatGPT # openai 配置 OPENAI_MODEL: gpt-3.5-turbo # openAI 最大token数 默认为2000 OPENAI_MAX_TOKENS: 2000 OPENAI_KEY: sk-zTeWCJSr... # mvp多维表格 BITABLE_HOST: fork-way.feishu.cn BITABLE_APP_TOKEN: Norqbd3anazOMlsceoEcbeIMn2g #产品数据库tableID PRODUCT_BITABLE_ID: tblVY2JwWJfbzWzS #供应商tableID SUPPLIER_BITABlE_ID: tbltrRO7DJGXd1ZJ #目标写入tableID及其视图ID RECEIPT_BITABLE_ID: tblghsq6TY3XktYG RECEIPT_BITABLE_VIEW: vewr4Kwn8O # 阿里云 OCR https://ai.aliyun.com/ocr/invoice ALI_ACCESSKEY_ID: LTAI5tEBvzfgfjZSy... ALI_ACCESSKEY_SECRET: DxpKnI64q31630.... # 服务器配置 HTTP_PORT: 9001 HTTPS_PORT: 9002 ``` -------------------------------- ### Configuration Loading Utility Source: https://context7.com/connectai-e/base-easywrite/llms.txt This utility function loads application configuration from a YAML file. Environment variables can be used to override settings defined in the configuration file. ```APIDOC ## Configuration Loading ### Description Loads application configuration from a YAML file with environment variable overrides. ### Method N/A (This is a utility function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters - **cfgPath** (string) - Required - The path to the configuration YAML file. ### Request Example (This is a function call, not a request body) ```go config := initialization.LoadConfig("config.yaml") ``` ### Response #### Success Response - Returns a pointer to a `Config` struct containing the loaded configuration values. - **FeishuAppId** (string) - Feishu application ID. - **FeishuAppSecret** (string) - Feishu application secret. - **FeishuBotName** (string) - Name of the Feishu bot. - **BitableHost** (string) - Host for Bitable integration. - **BitableAppToken** (string) - App token for Bitable integration. - **ProductBitableId** (string) - Bitable ID for products. - **ReceiptBitableId** (string) - Bitable ID for receipts. - **ReceiptBitableView** (string) - View ID for receipt Bitable. - **SupplierBitableId** (string) - Bitable ID for suppliers. - **OpenaiApiKeys** (array of strings) - List of OpenAI API keys. - **AliAccessKeyId** (string) - Alibaba Cloud Access Key ID. - **AliAccessKeySecret** (string) - Alibaba Cloud Access Key Secret. - **HttpPort** (integer) - The HTTP port for the application. #### Response Example (The `Config` struct represents the loaded configuration) ```go &Config{ FeishuAppId: "cli_a4172ca48e7b9013", FeishuAppSecret: "tWFwzQNzkD..", FeishuBotName: "ChatGPT", BitableHost: "fork-way.feishu.cn", BitableAppToken: "Norqbd3anazOMlsceoEcbeIMn2g", ProductBitableId: "tblVY2JwWJfbzWzS", ReceiptBitableId: "...", SupplierBitableId: "...", OpenaiApiKeys: []string{"sk-zTeWCJSr..."}, AliAccessKeyId: "LTAI5tEBvzfgfjZSy...", AliAccessKeySecret: "...", HttpPort: 9001 } ``` ``` -------------------------------- ### OpenAI GPT Completions API Source: https://context7.com/connectai-e/base-easywrite/llms.txt This API allows you to send prompts to OpenAI's GPT-3.5 model for natural language processing. You can configure parameters like temperature to control the creativity and precision of the responses. ```APIDOC ## POST /chat/completions ### Description Sends prompts to OpenAI GPT-3.5 for natural language processing with configurable temperature. ### Method POST ### Endpoint /chat/completions ### Parameters #### Request Body - **model** (string) - Required - The GPT model to use (e.g., "gpt-3.5-turbo-16k"). - **messages** (array of Messages) - Required - The conversation history. - **role** (string) - Required - The role of the message sender ("user" or "assistant"). - **content** (string) - Required - The text of the message. - **max_tokens** (integer) - Optional - The maximum number of tokens to generate (default: 4000). - **temperature** (float) - Optional - Controls randomness. Lower values make output more focused and deterministic (0.0-1.0). - **top_p** (integer) - Optional - Controls diversity via nucleus sampling (default: 1). - **frequency_penalty** (integer) - Optional - Controls repetition (default: 0). - **presence_penalty** (integer) - Optional - Controls new topics (default: 0). ### Request Example ```json { "model": "gpt-3.5-turbo-16k", "messages": [ {"role": "user", "content": "将【大白菜30斤100元】转换为JSON"} ], "temperature": 0.0 } ``` ### Response #### Success Response (200) - **choices** (array of ChatGPTChoiceItem) - Contains the generated completion(s). - **message** (Messages) - The generated message. - **role** (string) - The role of the sender (e.g., "assistant"). - **content** (string) - The text content of the message. #### Response Example ```json { "choices": [ { "message": { "role": "assistant", "content": "[\"{\"productName\":\"大白菜\",\"totalNumber\":30,\"totalPrice\":100}\"]" } } ] } ``` ``` -------------------------------- ### Cache Feishu Bitable Product Data (Go) Source: https://context7.com/connectai-e/base-easywrite/llms.txt Retrieves all products from a specified Feishu Bitable table, mapping product names to their record IDs and default suppliers. This helps in reducing redundant API calls by caching the data. Requires Feishu API client and initialization configuration. ```go // Get all products from Bitable package lark import ( "context" "encoding/json" larkbitable "github.com/larksuite/oapi-sdk-go/v3/service/bitable/v1" ) func GetAllProducts(config initialization.Config) (map[string][2]string, error) { client := initialization.GetLarkClient() req := larkbitable.NewListAppTableRecordReqBuilder(). AppToken(config.BitableAppToken). TableId(config.ProductBitableId). FieldNames(`["产品名称","主供应商"]`). TextFieldAsArray(true). Build() resp, err := client.Bitable.AppTableRecord.List(context.Background(), req) if err != nil { return nil, err } var r Response json.Unmarshal(resp.ApiResp.RawBody, &r) // Map: productName -> [recordId, defaultSupplier] result := make(map[string][2]string) for _, item := range r.Data.Items { productName := item.Fields["产品名称"][0].Text supplierName := "" if len(item.Fields["主供应商"]) > 0 { supplierName = item.Fields["主供应商"][0].Text } result[productName] = [2]string{item.RecordId, supplierName} } return result, nil } // Output (Products): {"大白菜": ["rec123", "王峰"], "生菜": ["rec456", "李峰"]} ``` -------------------------------- ### Feishu Card Action Handler (Go) Source: https://context7.com/connectai-e/base-easywrite/llms.txt Processes interactive actions triggered by Feishu cards, such as button clicks or menu selections. It utilizes the Feishu SDK for card actions and Gin for web framework integration. Requires Feishu SDK and Gin framework. ```Go // POST /webhook/card // Processes interactive card actions package main import ( "github.com/gin-gonic/gin" larkcard "github.com/larksuite/oapi-sdk-go/v3/card" sdkginext "github.com/larksuite/oapi-sdk-gin" ) func main() { r := gin.Default() cardHandler := larkcard.NewCardActionHandler( "your-verification-token", "your-encrypt-key", handlers.CardHandler(), ) r.POST("/webhook/card", sdkginext.NewCardActionHandlerFunc(cardHandler)) r.Run(":9001") } // Example card action payload: // { // "action": { // "value": { // "kind": "clear", // "sessionId": "msg_xxx", // "value": "1" // } // } // } ``` -------------------------------- ### Process Receipt Image OCR to Inventory Records (Go) Source: https://context7.com/connectai-e/base-easywrite/llms.txt Extracts text from receipt images using Alibaba Cloud OCR and processes it into inventory records. It downloads images from Lark, performs OCR, and then uses GPT to structure the recognized text into inventory fields. Requires Alibaba Cloud OCR and GPT services. ```go // Process receipt image and extract inventory data package handlers import ( "context" "inventory-manager/services/ocr" "inventory-manager/initialization" larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1" "os" "inventory-manager/services/gpt" "inventory-manager/services/openai" ) func processImageMessage(ctx context.Context, msgId *string, imageKey string, config initialization.Config) (string, error) { // Download image from Feishu req := larkim.NewGetMessageResourceReqBuilder(). MessageId(*msgId). FileKey(imageKey). Type("image"). Build() resp, err := initialization.GetLarkClient().Im.MessageResource.Get(context.Background(), req) if err != nil { return "", err } // Save temporarily imagePath := imageKey + ".png" resp.WriteFile(imagePath) defer os.Remove(imagePath) // Perform OCR content, err := ocr.RecognizeTableOcr(config, imagePath) if err != nil { return "", err } // Extract structured data from OCR result prompt := `下面是一些通过 OCR 识别图片生成的文字 【` + content + `】,请整理返回 存货名称/品名/数量/金额/日期` msg := []openai.Messages{{Role: "user", Content: prompt}} completions, err := gpt.Completions(msg, 0) return completions.Content, err } // Input: Receipt image with text "生菜 4.2斤 12.6元" // OCR Output: "生菜 4.2斤 12.6元" // Structured Output: "存货名称: 生菜, 数量: 4.2斤, 金额: 12.6元, 日期: 2025/10/09" ``` -------------------------------- ### POST /webhook/card Source: https://context7.com/connectai-e/base-easywrite/llms.txt Handles interactive card button clicks and menu selections initiated from Feishu cards. ```APIDOC ## POST /webhook/card ### Description Processes interactive actions triggered by users interacting with Feishu cards, such as button clicks or menu selections. ### Method POST ### Endpoint /webhook/card ### Parameters #### Request Body - **token** (string) - Required - Your Feishu Bot verification token. - **encrypt_key** (string) - Required - Your Feishu Bot encryption key. ### Request Example ```json { "action": { "value": { "kind": "clear", "sessionId": "msg_xxx", "value": "1" } } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the processing status of the card action. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Send OpenAI GPT Completions using Go Source: https://context7.com/connectai-e/base-easywrite/llms.txt Sends prompts to OpenAI GPT-3.5 for natural language processing. It configures the request with model, messages, max tokens, and temperature. The function returns the model's response message or an error if the request fails. ```go // Send completion request to OpenAI package openai import ( "errors" ) type Messages struct { Role string `json:"role"` // "user" or "assistant" Content string `json:"content"` // message text } type ChatGPTRequestBody struct { Model string `json:"model"` // "gpt-3.5-turbo-16k" Messages []Messages `json:"messages"` // conversation history MaxTokens int `json:"max_tokens"` // 4000 Temperature float64 `json:"temperature"` // 0.0-1.0 TopP int `json:"top_p"` // 1 FrequencyPenalty int `json:"frequency_penalty"` // 0 PresencePenalty int `json:"presence_penalty"` // 0 } type ChatGPTResponseBody struct { Choices []ChatGPTChoiceItem `json:"choices"` } type ChatGPTChoiceItem struct { Message Messages `json:"message"` } func (gpt *ChatGPT) Completions(msg []Messages, temperature float64) (Messages, error) { requestBody := ChatGPTRequestBody{ Model: "gpt-3.5-turbo-16k", Messages: msg, MaxTokens: 4000, Temperature: temperature, // 0.0 for precise tasks, 1.0 for creative TopP: 1, FrequencyPenalty: 0, PresencePenalty: 0, } gptResponseBody := &ChatGPTResponseBody{} url := gpt.FullUrl("chat/completions") err := gpt.sendRequestWithBodyType(url, "POST", jsonBody, requestBody, gptResponseBody) if err != nil || len(gptResponseBody.Choices) == 0 { return Messages{}, errors.New("openai 请求失败") } return gptResponseBody.Choices[0].Message, nil } // Example usage: // msg := []Messages{{Role: "user", Content: "将【大白菜30斤100元】转换为JSON"}} // response, err := gpt.Completions(msg, 0.0) // response.Content: `[{"productName":"大白菜","totalNumber":30,"totalPrice":100}]` ``` -------------------------------- ### Feishu Bot Webhook Event Handler (Go) Source: https://context7.com/connectai-e/base-easywrite/llms.txt Handles incoming Feishu Bot events, including text, image, and audio messages. It uses a dispatcher to route events to appropriate handlers based on message type. Requires Feishu SDK and Gin framework. ```Go // POST /webhook/event // Processes Feishu bot events (text, image, audio messages) package main import ( "context" "github.com/gin-gonic/gin" sdkginext "github.com/larksuite/oapi-sdk-gin" "github.com/larksuite/oapi-sdk-go/v3/event/dispatcher" larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1" ) func main() { r := gin.Default() eventHandler := dispatcher.NewEventDispatcher( "your-verification-token", "your-encrypt-key", ).OnP2MessageReceiveV1(handlers.Handler) r.POST("/webhook/event", sdkginext.NewEventHandlerFunc(eventHandler)) r.Run(":9001") } // Example incoming event from Feishu: // { // "event": { // "message": { // "message_type": "text", // "content": "{\"text\":\"收到了大白菜 30斤 一共100块\"}", // "message_id": "om_xxx", // "chat_id": "oc_xxx" // } // } // } ``` -------------------------------- ### Text Message Processing Source: https://context7.com/connectai-e/base-easywrite/llms.txt Converts natural language inventory descriptions into structured JSON records using GPT with few-shot learning. ```APIDOC ## Text Message Processing (Internal Function) ### Description This function processes natural language text describing inventory items and converts it into a structured JSON array of receipt records. It utilizes OpenAI's GPT model with few-shot learning to understand context, product names, suppliers, quantities, and prices. ### Method Internal Function (called by webhook handlers) ### Parameters #### Input Parameters - **msgContent** (string) - Required - The natural language text describing the inventory input (e.g., "收到了大白菜 30斤 一共100块"). - **products** (map[string][2]string) - Required - A map of known products and their details used for context. - **suppliers** (map[string]string) - Required - A map of known suppliers used for context. - **gpt** (*openai.ChatGPT) - Required - An instance of the ChatGPT client for making API calls. ### Request Example (Conceptual - for internal use) ```go // Assuming you have products, suppliers, and a gpt client initialized products := map[string][2]string{"大白菜": {"unit": "斤", "price": "1.0"}} suppliers := map[string]string{"王峰": "supplier_id_1"} gptClient := openai.NewChatGPT("your-api-key") recordList, err := processTextMessage("收到了大白菜 30斤 一共100块", products, suppliers, gptClient) ``` ### Response #### Success Response - **recordList** ([]*lark.ReceiptRecord) - A slice of receipt records in JSON format. #### Response Example ```json [ { "date": "2025/10/09", "productName": "大白菜", "companyName": "", "totalNumber": 30, "totalPrice": 100 } ] ``` ``` -------------------------------- ### Transcribe Audio Messages to Text (Go) Source: https://context7.com/connectai-e/base-easywrite/llms.txt Converts voice messages to text using OpenAI Whisper API. It downloads audio files from Lark, converts them to MP3 format, and then uses the Whisper API for transcription. Requires OpenAI Whisper API access. ```go // Process audio message and transcribe to text package handlers import ( "context" "inventory-manager/utils/audio" "inventory-manager/services/openai" larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1" "os" "fmt" "inventory-manager/initialization" ) func processAudioMessage(ctx context.Context, msgId *string, fileKey string, gpt *openai.ChatGPT) (string, error) { // Download audio file from Feishu req := larkim.NewGetMessageResourceReqBuilder(). MessageId(*msgId). FileKey(fileKey). Type("file"). Build() resp, err := initialization.GetLarkClient().Im.MessageResource.Get(context.Background(), req) if err != nil { return "", err } // Save as OGG oggPath := fileKey + ".ogg" resp.WriteFile(oggPath) defer os.Remove(oggPath) // Convert OGG to MP3 for Whisper mp3Path := fileKey + ".mp3" audio.OggToWavByPath(oggPath, mp3Path) defer os.Remove(mp3Path) // Transcribe using Whisper text, err := gpt.AudioToText(mp3Path) if err != nil { return "", fmt.Errorf("语音转换失败: %v", err) } return text, nil } // Input: Audio file saying "今天收到大白菜三十斤一共一百块" // Output: "今天收到大白菜三十斤一共一百块" ``` -------------------------------- ### Text Message Inventory Data Extraction (Go) Source: https://context7.com/connectai-e/base-easywrite/llms.txt Processes natural language inventory descriptions to extract structured JSON data for Feishu Bitable records. It uses OpenAI GPT with few-shot learning for natural language processing and integrates with Lark and OpenAI SDKs. Input is a natural language string, output is a list of receipt records. ```Go // Process text message and extract inventory data package handlers import ( "encoding/json" "inventory-manager/services/openai" "inventory-manager/services/lark" "time" ) func processTextMessage(msgContent string, products map[string][2]string, suppliers map[string]string, gpt *openai.ChatGPT) ([]*lark.ReceiptRecord, error) { // Build prompt with product and supplier context location, _ := time.LoadLocation("Asia/Shanghai") today := time.Now().In(location).Format("2006/01/02") prompt := `你是仓库管理员,产品数据库有如下商品:【` + productNames + `】。供应商有:【` + suppliers + `】,你可以将下面的文本转换为json数组的入库记录单。 下面是部分实例 --- Q: 【王峰供应商,送来吊龙三斤,总价143元】 A: [{ "date":"` + today + `", "productName":"吊龙", "companyName":"王峰", "totalNumber":3, "totalPrice":143 }] Q:【3月23号,生菜4.2斤,12块6,平菇,1.1斤,5块5】 A: [{ "date":"2023/03/23", "productName": "生菜", "companyName":"", "totalNumber": 4.2, "totalPrice": 12.6 }, { "date":"2023/03/23", "productName": "平菇", "companyName":"", "totalNumber": 1.1, "totalPrice": 5.5 }] 那么,Q:【` + msgContent + `】 转换成json数组的入库单结果是什么?直接返回 json数组的代码,不要其他提示信息。` msg := []openai.Messages{{Role: "user", Content: prompt}} completions, err := gpt.Completions(msg, 0) // temperature=0 for precision if err != nil { return nil, err } var recordList []*lark.ReceiptRecord err = json.Unmarshal([]byte(completions.Content), &recordList) return recordList, err } // Input: "收到了大白菜 30斤 一共100块" // Output: [{ // "date": "2025/10/09", // "productName": "大白菜", // "companyName": "", // "totalNumber": 30, // "totalPrice": 100 // }] ``` -------------------------------- ### Cache Feishu Bitable Supplier Data (Go) Source: https://context7.com/connectai-e/base-easywrite/llms.txt Retrieves all suppliers from a specified Feishu Bitable table, mapping supplier names to their record IDs. This caching mechanism helps to optimize API interactions. Requires Feishu API client and initialization configuration. ```go func GetAllSuppliers(config initialization.Config) (map[string]string, error) { client := initialization.GetLarkClient() req := larkbitable.NewListAppTableRecordReqBuilder(). AppToken(config.BitableAppToken). TableId(config.SupplierBitableId). FieldNames(`["供应商名称"]`). TextFieldAsArray(true). Build() resp, err := client.Bitable.AppTableRecord.List(context.Background(), req) if err != nil { return nil, err } var r Response json.Unmarshal(resp.ApiResp.RawBody, &r) // Map: supplierName -> recordId result := make(map[string]string) for _, item := range r.Data.Items { supplierName := item.Fields["供应商名称"][0].Text result[supplierName] = item.RecordId } return result, nil } // Output (Suppliers): {"王峰": "rec789", "李峰": "rec012"} ``` -------------------------------- ### POST /webhook/event Source: https://context7.com/connectai-e/base-easywrite/llms.txt Receives and processes incoming messages from Feishu Bot, routing them through a chain of action handlers based on message type (text, image, audio). ```APIDOC ## POST /webhook/event ### Description Processes incoming Feishu bot events, including text, image, and audio messages, by dispatching them to appropriate handlers. ### Method POST ### Endpoint /webhook/event ### Parameters #### Request Body - **token** (string) - Required - Your Feishu Bot verification token. - **encrypt_key** (string) - Required - Your Feishu Bot encryption key. ### Request Example ```json { "event": { "message": { "message_type": "text", "content": "{\"text\":\"收到了大白菜 30斤 一共100块\"}", "message_id": "om_xxx", "chat_id": "oc_xxx" } } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the processing status of the event. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### OpenAI Prompt for OCR Data Extraction Source: https://github.com/connectai-e/base-easywrite/blob/main/README.md This prompt is designed to be used after OCR processing of an image. It instructs the OpenAI model to extract specific fields such as item name, quantity, price, and date from the recognized text. The input is the OCR-processed text, and the output is a structured summary of these fields. ```Go prompt := `下面是一些通过 OCR 识别图片生成的文字 【` + a.info.qParsed + `】,请整理返回 存货名称/品名/数量/金额/日期` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.