82 lines
2.1 KiB
Go
82 lines
2.1 KiB
Go
// nonce_timestamp.go
|
||
package crypt
|
||
|
||
import (
|
||
"context"
|
||
|
||
"github.com/sashabaranov/go-openai"
|
||
"github.com/sashabaranov/go-openai/jsonschema"
|
||
)
|
||
|
||
type NonceTimestampTool struct{}
|
||
|
||
func (t *NonceTimestampTool) Name() string { return "nonce_timestamp" }
|
||
|
||
func (t *NonceTimestampTool) Description() string {
|
||
return "时间戳和随机数生成规范。当文档要求携带timestamp、nonce等防重放参数时使用"
|
||
}
|
||
|
||
func (t *NonceTimestampTool) GetFunctionDefinition() openai.FunctionDefinition {
|
||
return openai.FunctionDefinition{
|
||
Name: t.Name(),
|
||
Description: t.Description(),
|
||
Parameters: jsonschema.Definition{
|
||
Type: jsonschema.Object,
|
||
Properties: map[string]jsonschema.Definition{},
|
||
Required: []string{},
|
||
},
|
||
}
|
||
}
|
||
|
||
func (t *NonceTimestampTool) GetDetail(ctx context.Context, params map[string]string) (string, error) {
|
||
return `
|
||
### 时间戳和随机数生成规范
|
||
|
||
**代码模板**:
|
||
|
||
` + "```go" + `
|
||
package crypto
|
||
|
||
import (
|
||
"crypto/rand"
|
||
"fmt"
|
||
"math/big"
|
||
"time"
|
||
)
|
||
|
||
// GenerateTimestamp 生成秒级时间戳
|
||
func GenerateTimestamp() string {
|
||
return fmt.Sprintf("%d", time.Now().Unix())
|
||
}
|
||
|
||
// GenerateTimestampMillis 生成毫秒级时间戳
|
||
func GenerateTimestampMillis() string {
|
||
return fmt.Sprintf("%d", time.Now().UnixMilli())
|
||
}
|
||
|
||
// GenerateNonce 生成指定长度的随机字符串(加密安全)
|
||
func GenerateNonce(length int) (string, error) {
|
||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||
b := make([]byte, length)
|
||
for i := range b {
|
||
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
b[i] = charset[num.Int64()]
|
||
}
|
||
return string(b), nil
|
||
}
|
||
` + "```" + `
|
||
|
||
**注意事项**:
|
||
- 确认文档要求的是秒级还是毫秒级时间戳
|
||
- 确认nonce的长度要求(通常16-32位)
|
||
- 生产环境建议使用加密安全的随机数生成器
|
||
`, nil
|
||
}
|
||
|
||
func (t *NonceTimestampTool) Execute(ctx context.Context, params map[string]string) (string, error) {
|
||
return t.GetDetail(ctx, params)
|
||
}
|