feat: initialize Eino examples and ADK applications
Include chat, weather, image, travel, streaming ASR and text examples, shared model initialization, documentation, and existing tests. Co-authored-by: TRAE CLI <traecli@bytedance.com>
This commit is contained in:
commit
81deca8c8e
75 files changed
+7048
No files matched your search
@@ -0,0 +1,96 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
type option struct {
|
||||
baseURL string
|
||||
modelName string
|
||||
apiKey string
|
||||
}
|
||||
|
||||
type ChatOption func(*option)
|
||||
|
||||
func ChatBaseURL(baseURL string) ChatOption {
|
||||
return func(o *option) {
|
||||
if _, err := url.Parse(baseURL); err == nil {
|
||||
o.baseURL = strings.TrimRight(baseURL, "/")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ChatModel(modelName string) ChatOption {
|
||||
return func(o *option) {
|
||||
if modelName != "" {
|
||||
o.modelName = modelName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ChatApiKey(apiKey string) ChatOption {
|
||||
return func(o *option) {
|
||||
o.apiKey = apiKey
|
||||
}
|
||||
}
|
||||
|
||||
func ChatApiKeyByEnv(env string) ChatOption {
|
||||
return func(o *option) {
|
||||
if val := os.Getenv(env); val != "" {
|
||||
o.apiKey = val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type _chat struct {
|
||||
opt *option
|
||||
}
|
||||
|
||||
func NewChat(options ...ChatOption) *_chat {
|
||||
o := &option{
|
||||
modelName: "gpt-4o",
|
||||
baseURL: "https://api.openai.com/v1",
|
||||
apiKey: "",
|
||||
}
|
||||
|
||||
for _, fn := range options {
|
||||
fn(o)
|
||||
}
|
||||
|
||||
return &_chat{
|
||||
opt: o,
|
||||
}
|
||||
}
|
||||
|
||||
// ChatCompletion 通过回调输出文字,完整接收后返回助手消息;失败时直接返回错误。
|
||||
func (c *_chat) ChatCompletion(ctx context.Context, messages []model.ChatMessage, tools []model.ToolDefinition, onText func(string)) (*model.ChatMessage, error) {
|
||||
if len(messages) == 0 {
|
||||
return nil, fmt.Errorf("至少需要一条消息")
|
||||
}
|
||||
|
||||
body := model.ChatCompletionRequest{Model: c.opt.modelName, Messages: messages, Stream: true, Tools: tools}
|
||||
headers := map[string]string{"Accept": "text/event-stream"}
|
||||
if c.opt.apiKey != "" {
|
||||
headers["Authorization"] = "Bearer " + c.opt.apiKey
|
||||
}
|
||||
|
||||
endpoint := c.opt.baseURL + "/chat/completions"
|
||||
resp, err := PostJSONResponse(ctx, endpoint, headers, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
|
||||
return nil, fmt.Errorf("模型接口未返回流式响应")
|
||||
}
|
||||
|
||||
return readStream(ctx, resp.Body, onText)
|
||||
}
|
||||
Reference in new issue
Block a user