Files
ssw-ontology/server/handlers_functions.go
T
admin 1e30d4c355 docs+code: 通用化平台叙事,去掉尚数网业务绑定
## 文档重构(5 个 md + 1 个 html)
- README.md: '尚数网本体管理平台' → '本体元数据平台 · Ontology Platform'
- docs/README.md: 通用化定位,补全 P0/P1/P2 (Palantir Ontology 对标) + Materialization/BackingSource/Suggestions 全清单
- docs/PLAN.md: 通用化设计目标,改为 'Palantir Ontology 对标' 路线图
- docs/USAGE.md: 用通用占位符(项目/空间/组织)替换尚数网具体业务举例
- docs/IMPORT.md: 把 shangshu 当成 '一个采用方示例' 展示通用模式
- docs/product-intro.html: title/brand/hero/场景/footer 全改通用,沙数只作典型场景之一

## 代码字符串同步去 shangshu
- server/main.go: '[boot] 尚数网本体管理平台监听' → '[boot] 本体平台监听'
- server/handlers_connector.go: manifest 'server' 字段 → 'ontology-platform'
- server/handlers_mcp.go: tool description + serverInfo → 通用
- server/handlers_functions.go: builtin interface description → 通用
- server/handlers_backing_source.go: 注释去 shangshuwang.cn 具体网址
- server/config.go + server/db.go: 注释/seed 数据改占位 (demo_self / demo_partner_a/b)
- server/ai/anthropic.go: fallback systemPrompt → '通用本体平台工程师'
- server/ai/heuristic.go: 未识别 summary → '本体概念'
- server/ai/prompt.go: 静态 systemPrompt 头部 + JSON 示例去 shangshu

## 前端文案同步
- web/src/App.vue: title 改 '本体元数据平台'
- web/src/views/LoginView.vue: 登录页 h1 改通用
- web/src/views/OntologyView.vue: backing source placeholder 改 example.com
- web/src/components/ReviewWorkbench.vue + useReviewWorkbench.js: '尚数网' → '本体平台'

## 验证
- go build ./server OK
- 剩余 '尚数网' / 'shangshu-ontology' 引用:
  - 文档 README/README/USAGE/PLAN/IMPORT 仅在 '采用方示例' 上下文出现
  - 代码注释 sswOntologySystemPrompt 等 identifier 保持不变(避免改动 API 表面)
  - skill 名 'ssw-ontology-reviewer' 保持不变(已发布技能)

Refs: docs/README.md (1.1 元数据组件表)、docs/PLAN.md (4 当前已完成能力)
2026-08-24 14:04:59 +08:00

398 lines
15 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
// Function 元原语 REST API
// GET /api/v1/ontology/function-types 列出全部
// GET /api/v1/ontology/function-types/:name 单个
// POST /api/v1/ontology/function-types 新建(自定义 script/external_api)
// DELETE /api/v1/ontology/function-types/:name 删除
// POST /api/v1/ontology/function-types/:name/invoke 按 api_name 调用(manager 可调)
import (
"context"
"fmt"
"log"
"github.com/gin-gonic/gin"
)
// FunctionType 是返回结构(inputs/outputs 解码成 map)
type FunctionTypeOut struct {
ID int64 `json:"id"`
APIName string `json:"api_name"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Inputs interface{} `json:"inputs"`
Outputs interface{} `json:"outputs"`
ImplKind string `json:"impl_kind"`
ImplRef string `json:"impl_ref"`
IsPure bool `json:"is_pure"`
BuiltinFn string `json:"builtin_fn"`
WhenToSuggest []string `json:"when_to_suggest"`
LLMToolDescription string `json:"llm_tool_description"`
}
func scanFunctionRow(scan func(...any) error) (FunctionTypeOut, error) {
var f FunctionTypeOut
var inputs, outputs, whenToSuggest []byte
var llmDesc string
if err := scan(&f.ID, &f.APIName, &f.DisplayName, &f.Description, &inputs, &outputs,
&f.ImplKind, &f.ImplRef, &f.IsPure, &f.BuiltinFn,
&whenToSuggest, &llmDesc); err != nil {
return f, err
}
f.Inputs = jsonRaw(inputs)
f.Outputs = jsonRaw(outputs)
f.WhenToSuggest = parseStringArray(whenToSuggest)
f.LLMToolDescription = llmDesc
return f, nil
}
func (a *app) listFunctionTypes(c *gin.Context) {
rows, err := a.pool.Query(c,
`SELECT id, api_name, display_name, description, inputs, outputs, impl_kind, impl_ref, is_pure, builtin_fn,
when_to_suggest, llm_tool_description
FROM function_types ORDER BY id`)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
defer rows.Close()
var out []FunctionTypeOut
for rows.Next() {
f, err := scanFunctionRow(rows.Scan)
if err == nil {
out = append(out, f)
}
}
c.JSON(200, gin.H{"function_types": out, "count": len(out)})
}
func (a *app) getFunctionType(c *gin.Context) {
name := c.Param("name")
f, err := scanFunctionRow(func(args ...any) error {
return a.pool.QueryRow(c,
`SELECT id, api_name, display_name, description, inputs, outputs, impl_kind, impl_ref, is_pure, builtin_fn,
when_to_suggest, llm_tool_description
FROM function_types WHERE api_name=$1`, name).Scan(args...)
})
if err != nil {
c.JSON(404, gin.H{"error": "function_type 不存在"})
return
}
c.JSON(200, f)
}
type functionTypeInput struct {
APIName string `json:"api_name"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Inputs string `json:"inputs"`
Outputs string `json:"outputs"`
ImplKind string `json:"impl_kind"`
ImplRef string `json:"impl_ref"`
IsPure bool `json:"is_pure"`
WhenToSuggest []string `json:"when_to_suggest"`
LLMToolDescription string `json:"llm_tool_description"`
}
func (a *app) createFunctionType(c *gin.Context) {
var in functionTypeInput
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if in.APIName == "" || in.DisplayName == "" {
c.JSON(400, gin.H{"error": "api_name/display_name 必填"})
return
}
if in.Inputs == "" {
in.Inputs = "[]"
}
if in.Outputs == "" {
in.Outputs = "[]"
}
if in.ImplKind == "" {
in.ImplKind = "script"
}
if in.ImplKind == "builtin" {
// builtin 只能由系统注册(builtin_fn 必填 = api_name)
c.JSON(400, gin.H{"error": "builtin 类型不可手动新建,请改名为 script/external_api"})
return
}
if in.WhenToSuggest == nil {
in.WhenToSuggest = []string{}
}
whenJSON := mustJSON(in.WhenToSuggest)
_, err := a.pool.Exec(c,
`INSERT INTO function_types(api_name,display_name,description,inputs,outputs,impl_kind,impl_ref,is_pure,
when_to_suggest,llm_tool_description)
VALUES($1,$2,$3,$4::jsonb,$5::jsonb,$6,$7,$8,$9::jsonb,$10)
ON CONFLICT(api_name) DO UPDATE SET
display_name=EXCLUDED.display_name,
description=EXCLUDED.description,
inputs=EXCLUDED.inputs,
outputs=EXCLUDED.outputs,
impl_kind=EXCLUDED.impl_kind,
impl_ref=EXCLUDED.impl_ref,
is_pure=EXCLUDED.is_pure,
when_to_suggest=EXCLUDED.when_to_suggest,
llm_tool_description=EXCLUDED.llm_tool_description,
updated_at=now()`,
in.APIName, in.DisplayName, in.Description, in.Inputs, in.Outputs, in.ImplKind, in.ImplRef, in.IsPure,
whenJSON, in.LLMToolDescription)
if err != nil {
c.JSON(409, gin.H{"error": "创建失败: " + err.Error()})
return
}
c.JSON(201, gin.H{"ok": true, "api_name": in.APIName})
}
func (a *app) deleteFunctionType(c *gin.Context) {
name := c.Param("name")
tag, err := a.pool.Exec(c, `DELETE FROM function_types WHERE api_name=$1 AND impl_kind<>'builtin'`, name)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
if tag.RowsAffected() == 0 {
c.JSON(404, gin.H{"error": "function_type 不存在或为内置(不可删)"})
return
}
c.JSON(200, gin.H{"ok": true})
}
func (a *app) invokeFunctionType(c *gin.Context) {
name := c.Param("name")
var args map[string]interface{}
if err := c.ShouldBindJSON(&args); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
out, err := invokeFunction(c, a, name, args)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"ok": true, "function": name, "result": out})
}
// ============ Interface 元原语(⑦Interface)============
type InterfaceTypeOut struct {
ID int64 `json:"id"`
APIName string `json:"api_name"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Protocol string `json:"protocol"` // rest | mcp
Method string `json:"method"`
Path string `json:"path"`
Inputs interface{} `json:"inputs"`
Outputs interface{} `json:"outputs"`
RequiresAuth bool `json:"requires_auth"`
ExposeToMCP bool `json:"expose_to_mcp"`
BackingRef string `json:"backing_ref"`
Builtin bool `json:"builtin"`
SharedProperties []string `json:"shared_properties"` // P1-4
ParentInterfaceID *int64 `json:"parent_interface_id"` // P1-4
ParentAPIName string `json:"parent_api_name"` // P1-4(JOIN 出来)
}
func scanInterfaceRow(scan func(...any) error) (InterfaceTypeOut, error) {
var it InterfaceTypeOut
var inputs, outputs, shared []byte
var parentID *int64
var parentName *string
if err := scan(&it.ID, &it.APIName, &it.DisplayName, &it.Description, &it.Protocol, &it.Method, &it.Path,
&inputs, &outputs, &it.RequiresAuth, &it.ExposeToMCP, &it.BackingRef, &it.Builtin,
&shared, &parentID, &parentName); err != nil {
return it, err
}
it.Inputs = jsonRaw(inputs)
it.Outputs = jsonRaw(outputs)
it.SharedProperties = parseStringArray(shared)
it.ParentInterfaceID = parentID
if parentName != nil {
it.ParentAPIName = *parentName
}
return it, nil
}
func (a *app) listInterfaceTypes(c *gin.Context) {
rows, err := a.pool.Query(c,
`SELECT it.id, it.api_name, it.display_name, it.description, it.protocol, it.method, it.path,
it.inputs, it.outputs, it.requires_auth, it.expose_to_mcp, it.backing_ref, it.builtin,
it.shared_properties, it.parent_interface_id, p.api_name
FROM interface_types it
LEFT JOIN interface_types p ON p.id = it.parent_interface_id
ORDER BY it.protocol, it.method, it.api_name`)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
defer rows.Close()
var out []InterfaceTypeOut
for rows.Next() {
it, err := scanInterfaceRow(rows.Scan)
if err == nil {
out = append(out, it)
}
}
c.JSON(200, gin.H{"interface_types": out, "count": len(out)})
}
func (a *app) getInterfaceType(c *gin.Context) {
name := c.Param("name")
it, err := scanInterfaceRow(func(args ...any) error {
return a.pool.QueryRow(c,
`SELECT it.id, it.api_name, it.display_name, it.description, it.protocol, it.method, it.path,
it.inputs, it.outputs, it.requires_auth, it.expose_to_mcp, it.backing_ref, it.builtin,
it.shared_properties, it.parent_interface_id, p.api_name
FROM interface_types it
LEFT JOIN interface_types p ON p.id = it.parent_interface_id
WHERE it.api_name=$1`, name).Scan(args...)
})
if err != nil {
c.JSON(404, gin.H{"error": "interface_type 不存在"})
return
}
c.JSON(200, it)
}
type interfaceTypeInput struct {
APIName string `json:"api_name"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Protocol string `json:"protocol"`
Method string `json:"method"`
Path string `json:"path"`
Inputs string `json:"inputs"`
Outputs string `json:"outputs"`
RequiresAuth bool `json:"requires_auth"`
ExposeToMCP bool `json:"expose_to_mcp"`
BackingRef string `json:"backing_ref"`
SharedProperties []string `json:"shared_properties"`
ParentInterfaceID *int64 `json:"parent_interface_id"`
}
func (a *app) createInterfaceType(c *gin.Context) {
var in interfaceTypeInput
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if in.APIName == "" || in.DisplayName == "" {
c.JSON(400, gin.H{"error": "api_name/display_name 必填"})
return
}
if in.Inputs == "" {
in.Inputs = "[]"
}
if in.Outputs == "" {
in.Outputs = "{}"
}
if in.Protocol == "" {
in.Protocol = "rest"
}
if in.SharedProperties == nil {
in.SharedProperties = []string{}
}
sharedJSON := mustJSON(in.SharedProperties)
// 校验 parent_interface_id 存在(不防自环,留给上层做)
if in.ParentInterfaceID != nil {
var cnt int
if err := a.pool.QueryRow(c, `SELECT count(*) FROM interface_types WHERE id=$1`, *in.ParentInterfaceID).Scan(&cnt); err != nil || cnt == 0 {
c.JSON(400, gin.H{"error": "parent_interface_id 引用的 interface_type 不存在"})
return
}
}
_, err := a.pool.Exec(c,
`INSERT INTO interface_types(api_name,display_name,description,protocol,method,path,inputs,outputs,requires_auth,expose_to_mcp,backing_ref,
shared_properties,parent_interface_id)
VALUES($1,$2,$3,$4,$5,$6,$7::jsonb,$8::jsonb,$9,$10,$11,$12::jsonb,$13)
ON CONFLICT(api_name) DO UPDATE SET
display_name=EXCLUDED.display_name,
description=EXCLUDED.description,
protocol=EXCLUDED.protocol,
method=EXCLUDED.method,
path=EXCLUDED.path,
inputs=EXCLUDED.inputs,
outputs=EXCLUDED.outputs,
requires_auth=EXCLUDED.requires_auth,
expose_to_mcp=EXCLUDED.expose_to_mcp,
backing_ref=EXCLUDED.backing_ref,
shared_properties=EXCLUDED.shared_properties,
parent_interface_id=EXCLUDED.parent_interface_id,
updated_at=now()`,
in.APIName, in.DisplayName, in.Description, in.Protocol, in.Method, in.Path, in.Inputs, in.Outputs,
in.RequiresAuth, in.ExposeToMCP, in.BackingRef, sharedJSON, in.ParentInterfaceID)
if err != nil {
c.JSON(409, gin.H{"error": "创建失败: " + err.Error()})
return
}
c.JSON(201, gin.H{"ok": true, "api_name": in.APIName})
}
func (a *app) deleteInterfaceType(c *gin.Context) {
name := c.Param("name")
tag, err := a.pool.Exec(c, `DELETE FROM interface_types WHERE api_name=$1 AND builtin=false`, name)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
if tag.RowsAffected() == 0 {
c.JSON(404, gin.H{"error": "interface_type 不存在或为内置(不可删)"})
return
}
c.JSON(200, gin.H{"ok": true})
}
// ensureBuiltinInterfaces 启动时把 6 个 connector REST 端点注册到 interface_types
func ensureBuiltinInterfaces(ctx context.Context, a *app) error {
ifs := []struct {
APIName string
DisplayName string
Description string
Method string
Path string
Inputs string
Outputs string
}{
{"list_object_types", "列出对象类型", "获取本体平台的全部对象类型(含属性定义)", "GET", "/api/v1/connector/object-types", "[]",
`{"object_types":"[ObjectType]","count":"int"}`},
{"list_objects", "列出某类实例", "按对象类型列出全部实例", "GET", "/api/v1/connector/objects/:type",
`[{"name":"type","type":"string","required":true},{"name":"limit","type":"int","required":false}]`,
`{"type":"string","items":"Object[]","count":"int"}`},
{"get_object", "获取单个实例", "按类型与主键获取单个本体对象", "GET", "/api/v1/connector/object/:type/:pk",
`[{"name":"type","type":"string","required":true},{"name":"pk","type":"string","required":true}]`,
`{"object":"Object"}`},
{"search_ontology", "精准检索", "按名称命中优先排序;可选 type/field/limit", "GET", "/api/v1/connector/search",
`[{"name":"q","type":"string","required":true},{"name":"type","type":"string","required":false},{"name":"field","type":"string","required":false},{"name":"limit","type":"int","required":false}]`,
`{"query":"string","items":"Object[]","count":"int"}`},
{"get_facets", "获取维度取值", "返回各类型可过滤的维度取值", "GET", "/api/v1/connector/facets",
`[{"name":"type","type":"string","required":false}]`,
`{"facets":"{type:{facet:[values]}}"}`},
{"query_related", "图式查询", "按类型+属性过滤,并可沿链接类型展开邻居", "POST", "/api/v1/connector/query",
`[{"name":"type","type":"string","required":true},{"name":"filters","type":"object","required":false},{"name":"expand","type":"string","required":false},{"name":"limit","type":"int","required":false}]`,
`{"type":"string","items":"Object[]","neighbors":"Object[]","neighbor_count":"int"}`},
}
for _, x := range ifs {
_, err := a.pool.Exec(ctx,
`INSERT INTO interface_types(api_name,display_name,description,protocol,method,path,inputs,outputs,requires_auth,expose_to_mcp,backing_ref,builtin)
VALUES($1,$2,$3,'rest',$4,$5,$6::jsonb,$7::jsonb,true,true,$1,true)
ON CONFLICT(api_name) DO UPDATE SET
display_name=EXCLUDED.display_name,
description=EXCLUDED.description,
method=EXCLUDED.method,
path=EXCLUDED.path,
expose_to_mcp=true,
updated_at=now()`,
x.APIName, x.DisplayName, x.Description, x.Method, x.Path, x.Inputs, x.Outputs)
if err != nil {
return fmt.Errorf("register builtin interface %s: %w", x.APIName, err)
}
}
log.Printf("[interface] 内置接口就绪: %d 个 connector REST + MCP 暴露", len(ifs))
return nil
}