feat: initialize terminal chat example with streaming and memory
This commit is contained in:
commit
43fc905c82
13 files changed
+666
No files matched your search
@@ -0,0 +1,139 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/internal/opt"
|
||||
"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 原样发送上层组装的消息,通过通道返回文本片段。
|
||||
// 流开始后的错误记录日志并关闭通道。
|
||||
// 调用方应持续读取通道,提前停止时取消 ctx。
|
||||
func (c *_chat) ChatCompletion(ctx context.Context, messages []model.ChatMessage) (<-chan string, error) {
|
||||
if len(messages) == 0 {
|
||||
return nil, fmt.Errorf("至少需要一条消息")
|
||||
}
|
||||
|
||||
body := model.ChatCompletionRequest{Model: c.opt.modelName, Messages: messages, Stream: true}
|
||||
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
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("模型接口未返回流式响应")
|
||||
}
|
||||
|
||||
out := make(chan string, opt.RESPONSE_CHAN_SIZE)
|
||||
go func() {
|
||||
defer close(out)
|
||||
defer resp.Body.Close()
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
scanner.Buffer(make([]byte, 4096), 1024*1024)
|
||||
for scanner.Scan() {
|
||||
data, ok := bytes.CutPrefix(scanner.Bytes(), []byte("data:"))
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
data = bytes.TrimSpace(data)
|
||||
if bytes.Equal(data, []byte("[DONE]")) {
|
||||
return
|
||||
}
|
||||
|
||||
var chunk model.ChatCompletionResponse
|
||||
if err := json.Unmarshal(data, &chunk); err != nil {
|
||||
log.Printf("解析模型流式响应失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(chunk.Choices) == 0 || chunk.Choices[0].Delta.Content == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
select {
|
||||
case out <- chunk.Choices[0].Delta.Content:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.Err() == nil {
|
||||
log.Printf("模型响应流未正常结束: %v", scanner.Err())
|
||||
}
|
||||
}()
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// httpClient 由所有 provider 请求共用。
|
||||
var httpClient = &http.Client{}
|
||||
|
||||
// PostJSON 发送 JSON 请求,将响应解码到 result,并检查 HTTP 状态码。
|
||||
func PostJSON(ctx context.Context, endpoint string, headers map[string]string, body, result any) error {
|
||||
resp, err := PostJSONResponse(ctx, endpoint, headers, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return json.NewDecoder(resp.Body).Decode(result)
|
||||
}
|
||||
|
||||
// PostJSONResponse 发送 JSON 请求并检查状态码,调用方负责关闭响应体。
|
||||
func PostJSONResponse(ctx context.Context, endpoint string, headers map[string]string, body any) (*http.Response, error) {
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
for key, value := range headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("接口返回 %s,读取错误信息失败: %w", resp.Status, err)
|
||||
}
|
||||
return nil, fmt.Errorf("接口返回 %s: %s", resp.Status, data)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
Reference in new issue
Block a user