MCPcopy
hub / github.com/mudler/LocalAI / StreamChat

Method StreamChat

core/cli/chat/client.go:45–81  ·  view source on GitHub ↗
(ctx context.Context, model string, messages []chatMessage, out io.Writer)

Source from the content-addressed store, hash-verified

43}
44
45func (c *localAIChatClient) StreamChat(ctx context.Context, model string, messages []chatMessage, out io.Writer) (string, error) {
46 stream, err := c.client.CreateChatCompletionStream(ctx, openai.ChatCompletionRequest{
47 Model: model,
48 Messages: openAIChatMessages(messages),
49 })
50 if err != nil {
51 return "", friendlyChatError(err, model)
52 }
53 defer func() {
54 _ = stream.Close()
55 }()
56
57 var answer strings.Builder
58 for {
59 resp, err := stream.Recv()
60 if errors.Is(err, io.EOF) {
61 break
62 }
63 if err != nil {
64 return answer.String(), friendlyChatError(err, model)
65 }
66 if len(resp.Choices) == 0 {
67 continue
68 }
69
70 token := resp.Choices[0].Delta.Content
71 if token == "" {
72 continue
73 }
74 answer.WriteString(token)
75 if _, err := fmt.Fprint(out, token); err != nil {
76 return answer.String(), err
77 }
78 }
79
80 return answer.String(), nil
81}
82
83func openAIChatMessages(messages []chatMessage) []openai.ChatCompletionMessage {
84 converted := make([]openai.ChatCompletionMessage, len(messages))

Callers

nothing calls this directly

Calls 6

openAIChatMessagesFunction · 0.85
friendlyChatErrorFunction · 0.85
CloseMethod · 0.65
RecvMethod · 0.65
StringMethod · 0.65
IsMethod · 0.45

Tested by

no test coverage detected