commit 342f2d9c09399e45307d3f403be0ab61e4edf25f Author: STARAI\Star Date: Sat Sep 7 23:17:32 2024 +0800 1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..53669e9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.* +go.sum +env.yml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f166f95 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/agent.go b/agent.go new file mode 100644 index 0000000..7667ceb --- /dev/null +++ b/agent.go @@ -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, + }, + }) +} diff --git a/chat.go b/chat.go new file mode 100644 index 0000000..95bdbcd --- /dev/null +++ b/chat.go @@ -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 +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..48dcd11 --- /dev/null +++ b/go.mod @@ -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 diff --git a/tests/1024.jpg b/tests/1024.jpg new file mode 100644 index 0000000..8fb8bc7 Binary files /dev/null and b/tests/1024.jpg differ diff --git a/tests/1080.mp4 b/tests/1080.mp4 new file mode 100644 index 0000000..3b62d3a Binary files /dev/null and b/tests/1080.mp4 differ diff --git a/tests/1920.jpg b/tests/1920.jpg new file mode 100644 index 0000000..4cb1aae Binary files /dev/null and b/tests/1920.jpg differ diff --git a/tests/4032.jpg b/tests/4032.jpg new file mode 100644 index 0000000..227abb6 Binary files /dev/null and b/tests/4032.jpg differ diff --git a/tests/720.mp4 b/tests/720.mp4 new file mode 100644 index 0000000..05e9060 Binary files /dev/null and b/tests/720.mp4 differ diff --git a/tests/chat_test.go b/tests/chat_test.go new file mode 100644 index 0000000..f295896 --- /dev/null +++ b/tests/chat_test.go @@ -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]) + } +} diff --git a/tests/env.sample.yml b/tests/env.sample.yml new file mode 100644 index 0000000..e19de77 --- /dev/null +++ b/tests/env.sample.yml @@ -0,0 +1,6 @@ +agent: + openai: + apiKey: ... +# endpoint: ... + zhipu: + apiKey: ... diff --git a/tests/go.mod b/tests/go.mod new file mode 100644 index 0000000..ca6e843 --- /dev/null +++ b/tests/go.mod @@ -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 => ../