This commit is contained in:
STARAI\Star 2024-09-07 23:17:32 +08:00
commit 342f2d9c09
13 changed files with 428 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.*
go.sum
env.yml

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 apigo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

89
agent.go Normal file
View File

@ -0,0 +1,89 @@
package ai
import (
"apigo.cc/ai/agent"
"github.com/ssgo/config"
"github.com/ssgo/u"
"sync"
)
var confAes = u.NewAes([]byte("?GQ$0K0GgLdO=f+~L68PLm$uhKr4'=tV"), []byte("VFs7@sK61cj^f?HZ"))
var keysIsSet = false
func SetSSKey(key, iv []byte) {
if !keysIsSet {
confAes = u.NewAes(key, iv)
keysIsSet = true
}
}
const (
TypeText = agent.TypeText
TypeImage = agent.TypeImage
TypeVideo = agent.TypeVideo
RoleSystem = agent.RoleSystem
RoleUser = agent.RoleUser
RoleAssistant = agent.RoleAssistant
RoleTool = agent.RoleTool
ToolCodeInterpreter = agent.ToolCodeInterpreter
ToolWebSearch = agent.ToolWebSearch
)
type APIConfig struct {
Endpoint string
ApiKey string
DefaultChatModelConfig ChatModelConfig
}
type AgentConfig struct {
ApiKey string
Endpoint string
Agent string
ChatConfig ChatModelConfig
}
var agentConfigs map[string]*AgentConfig
var agentConfigsLock = sync.RWMutex{}
func GetAgent(name string) agent.Agent {
ag := agent.GetAgent(name)
if ag != nil {
return ag
}
var agConf *AgentConfig
if agentConfigs == nil {
agConfs := make(map[string]*AgentConfig)
config.LoadConfig("agent", &agConfs)
agConf = agConfs[name]
if agConf != nil {
agentConfigsLock.Lock()
agentConfigs = agConfs
agentConfigsLock.Unlock()
}
} else {
agentConfigsLock.RLock()
agConf = agentConfigs[name]
agentConfigsLock.RUnlock()
}
if agConf == nil {
return nil
}
if agConf.Agent == "" {
agConf.Agent = name
}
return agent.CreateAgent(name, agConf.Agent, agent.APIConfig{
Endpoint: agConf.Endpoint,
ApiKey: confAes.DecryptUrlBase64ToString(agConf.ApiKey),
DefaultChatModelConfig: agent.ChatModelConfig{
Model: agConf.ChatConfig.Model,
MaxTokens: agConf.ChatConfig.MaxTokens,
Temperature: agConf.ChatConfig.Temperature,
TopP: agConf.ChatConfig.TopP,
Tools: agConf.ChatConfig.Tools,
},
})
}

92
chat.go Normal file
View File

@ -0,0 +1,92 @@
package ai
import "apigo.cc/ai/agent"
type ChatMessage = agent.ChatMessage
type ChatMessageContent = agent.ChatMessageContent
type ChatModelConfig struct {
Model string
MaxTokens int
Temperature float64
TopP float64
Tools map[string]any
}
type MessagesMaker struct {
list []ChatMessage
}
func Messages() *MessagesMaker {
return &MessagesMaker{
list: make([]ChatMessage, 0),
}
}
func (m *MessagesMaker) Make() []ChatMessage {
return m.list
}
func (m *MessagesMaker) User(contents ...ChatMessageContent) *MessagesMaker {
m.list = append(m.list, ChatMessage{
Role: RoleUser,
Contents: contents,
})
return m
}
func (m *MessagesMaker) Assistant(contents ...ChatMessageContent) *MessagesMaker {
m.list = append(m.list, ChatMessage{
Role: RoleAssistant,
Contents: contents,
})
return m
}
func (m *MessagesMaker) System(contents ...ChatMessageContent) *MessagesMaker {
m.list = append(m.list, ChatMessage{
Role: RoleSystem,
Contents: contents,
})
return m
}
func (m *MessagesMaker) Tool(contents ...ChatMessageContent) *MessagesMaker {
m.list = append(m.list, ChatMessage{
Role: RoleTool,
Contents: contents,
})
return m
}
func (m *MessagesMaker) Text(text string) *MessagesMaker {
if len(m.list) > 0 {
lastIndex := len(m.list) - 1
m.list[lastIndex].Contents = append(m.list[lastIndex].Contents, ChatMessageContent{
Type: TypeText,
Content: text,
})
}
return m
}
func (m *MessagesMaker) Image(text string) *MessagesMaker {
if len(m.list) > 0 {
lastIndex := len(m.list) - 1
m.list[lastIndex].Contents = append(m.list[lastIndex].Contents, ChatMessageContent{
Type: TypeText,
Content: text,
})
}
return m
}
func (m *MessagesMaker) Video(text string) *MessagesMaker {
if len(m.list) > 0 {
lastIndex := len(m.list) - 1
m.list[lastIndex].Contents = append(m.list[lastIndex].Contents, ChatMessageContent{
Type: TypeText,
Content: text,
})
}
return m
}

11
go.mod Normal file
View File

@ -0,0 +1,11 @@
module apigo.cc/ai/ai
go 1.22
require (
apigo.cc/ai/agent v0.0.1
github.com/ssgo/config v1.7.7
github.com/ssgo/u v1.7.7
)
require gopkg.in/yaml.v3 v3.0.1 // indirect

BIN
tests/1024.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

BIN
tests/1080.mp4 Normal file

Binary file not shown.

BIN
tests/1920.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 545 KiB

BIN
tests/4032.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

BIN
tests/720.mp4 Normal file

Binary file not shown.

194
tests/chat_test.go Normal file
View File

@ -0,0 +1,194 @@
package tests
import (
"apigo.cc/ai/ai"
_ "apigo.cc/ai/openai"
_ "apigo.cc/ai/zhipu"
"fmt"
"github.com/ssgo/config"
"github.com/ssgo/u"
"testing"
)
var agentConf = map[string]ai.AgentConfig{}
func init() {
_ = config.LoadConfig("agent", &agentConf)
}
func TestAgent(t *testing.T) {
//testChat(t, "openai", "https://api.keya.pw/v1", keys.Openai)
// 尚未支持
//testCode(t, "openai", "https://api.keya.pw/v1", keys.Openai)
// keya 消耗过大,计费不合理
//testAskWithImage(t, "openai", "https://api.keya.pw/v1", keys.Openai, "4032.jpg")
// keya 不支持
//testMakeImage(t, "openai", "https://api.keya.pw/v1", keys.Openai, "冬天大雪纷飞,一个男人身穿军绿色棉大衣,戴着红色围巾和绿色帽子走在铺面大雪的小镇路上", "")
testChat(t, "zhipu")
//testCode(t, "zhipu", "", keys.Zhipu)
//testSearch(t, "zhipu", "", keys.Zhipu)
// 测试图片识别
//testAskWithImage(t, "zhipu", "", keys.Zhipu, "4032.jpg")
// 视频似乎尚不支持 glm-4v-plus
//testAskWithVideo(t, "zhipu", "", keys.Zhipu, "glm-4v", "1080.mp4")
//testMakeImage(t, "zhipu", "", keys.Zhipu, "冬天大雪纷飞,一个男人身穿军绿色棉大衣,戴着红色围巾和绿色帽子走在铺面大雪的小镇路上", "")
//testMakeVideo(t, "zhipu", "", keys.Zhipu, "大雪纷飞,男人蹦蹦跳跳", "https://aigc-files.bigmodel.cn/api/cogview/20240904133130c4b7121019724aa3_0.png")
}
func testChat(t *testing.T, agent string) {
ag := ai.GetAgent(agent)
if ag == nil {
t.Fatal("agent is nil")
}
r, usage, err := ag.FastAsk(ai.Messages().User().Text("你是什么模型,请给出具体名称、版本号").Make(), func(text string) {
fmt.Print(u.BCyan(text))
fmt.Print(" ")
})
if err != nil {
t.Fatal(err)
}
fmt.Println()
fmt.Println("result:", r)
fmt.Println("usage:", u.JsonP(usage))
}
func testCode(t *testing.T, agent string) {
ag := ai.GetAgent(agent)
if ag == nil {
t.Fatal("agent is nil")
}
r, usage, err := ag.CodeInterpreterAsk(ai.Messages().User().Text("计算[5,10,20,700,99,310,978,100]的平均值和方差。").Make(), func(text string) {
fmt.Print(u.BCyan(text))
fmt.Print(" ")
})
if err != nil {
t.Fatal(err)
}
fmt.Println()
fmt.Println("result:", r)
fmt.Println("usage:", u.JsonP(usage))
}
func testSearch(t *testing.T, agent string) {
ag := ai.GetAgent(agent)
if ag == nil {
t.Fatal("agent is nil")
}
r, usage, err := ag.WebSearchAsk(ai.Messages().User().Text("今天上海的天气怎么样?").Make(), func(text string) {
fmt.Print(u.BCyan(text))
fmt.Print(" ")
})
if err != nil {
t.Fatal(err)
}
fmt.Println()
fmt.Println("result:", r)
fmt.Println("usage:", u.JsonP(usage))
}
func testAskWithImage(t *testing.T, agent, imageFile string) {
ag := ai.GetAgent(agent)
if ag == nil {
t.Fatal("agent is nil")
}
ask := `请回答
1我用的是什么操作系统
2现在的日期时间是请给出年月日
3正在用什么软件播放什么歌谁演唱的歌曲的大意是
4后面的浏览器中正在浏览什么内容猜测一下我浏览这个网页是想干嘛
`
r, usage, err := ag.MultiAsk(ai.Messages().User().Text(ask).Image("data:image/jpeg;base64,"+u.Base64(u.ReadFileBytesN(imageFile))).Make(), func(text string) {
fmt.Print(u.BCyan(text))
fmt.Print(" ")
})
if err != nil {
t.Fatal("发生错误", err.Error())
}
fmt.Println()
fmt.Println("result:", r)
fmt.Println("usage:", u.JsonP(usage))
}
func testAskWithVideo(t *testing.T, agent, videoFile string) {
ag := ai.GetAgent(agent)
if ag == nil {
t.Fatal("agent is nil")
}
ask := `请回答
1正在用什么软件播放什么歌谁演唱的歌曲的大意是
4后面的浏览器中正在浏览什么内容猜测一下我浏览这个网页是想干嘛
`
r, usage, err := ag.MultiAsk(ai.Messages().User().Text(ask).Video("data:video/mp4,"+u.Base64(u.ReadFileBytesN(videoFile))).Make(), func(text string) {
fmt.Print(u.BCyan(text))
fmt.Print(" ")
})
if err != nil {
t.Fatal("发生错误", err.Error())
}
fmt.Println()
fmt.Println("result:", r)
fmt.Println("usage:", u.JsonP(usage))
}
func testMakeImage(t *testing.T, agent, prompt, refImage string) {
ag := ai.GetAgent(agent)
if ag == nil {
t.Fatal("agent is nil")
}
r, err := ag.FastMakeImage(prompt, "1024x1024", "")
if err != nil {
t.Fatal("发生错误", err.Error())
}
fmt.Println()
for i, v := range r {
fmt.Println("result:", i, v)
}
}
func testMakeVideo(t *testing.T, agent, prompt, refImage string) {
ag := ai.GetAgent(agent)
if ag == nil {
t.Fatal("agent is nil")
}
r, covers, err := ag.FastMakeVideo(prompt, "1280x720", refImage)
if err != nil {
t.Fatal("发生错误", err.Error())
}
fmt.Println()
for i, v := range r {
fmt.Println("result:", i, v, covers[i])
}
}

6
tests/env.sample.yml Normal file
View File

@ -0,0 +1,6 @@
agent:
openai:
apiKey: ...
# endpoint: ...
zhipu:
apiKey: ...

24
tests/go.mod Normal file
View File

@ -0,0 +1,24 @@
module tests
go 1.22
require (
apigo.cc/ai/ai v0.0.0
apigo.cc/ai/openai v0.0.1
apigo.cc/ai/zhipu v0.0.1
github.com/ssgo/config v1.7.7
github.com/ssgo/u v1.7.7
)
require (
apigo.cc/ai/agent v0.0.1 // indirect
github.com/go-resty/resty/v2 v2.14.0 // indirect
github.com/golang-jwt/jwt/v5 v5.2.1 // indirect
github.com/sashabaranov/go-openai v1.29.1 // indirect
github.com/ssgo/log v1.7.7 // indirect
github.com/ssgo/standard v1.7.7 // indirect
golang.org/x/net v0.29.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace apigo.cc/ai/ai v0.0.0 => ../