11import AsyncAlgorithms
22import Foundation
33import Preferences
4+ import JSONRPC
45
56typealias CompletionStreamAPIBuilder = ( String , ChatFeatureProvider , URL , CompletionRequestBody ) -> CompletionStreamAPI
67
@@ -12,10 +13,64 @@ protocol CompletionStreamAPI {
1213}
1314
1415/// https://platform.openai.com/docs/api-reference/chat/create
15- struct CompletionRequestBody : Codable , Equatable {
16+ struct CompletionRequestBody : Encodable , Equatable {
1617 struct Message : Codable , Equatable {
18+ /// The role of the message.
1719 var role : ChatMessage . Role
18- var content : String
20+ /// The content of the message.
21+ var content : String ?
22+ /// When we want to reply to a function call with the result, we have to provide the
23+ /// name of the function call, and include the result in `content`.
24+ ///
25+ /// - important: It's required when the role is `function`.
26+ var name : String ?
27+ /// When the bot wants to call a function, it will reply with a function call in format:
28+ /// ```json
29+ /// {
30+ /// "name": "weather",
31+ /// "arguments": "{ \"location\": \"earth\" }"
32+ /// }
33+ /// ```
34+ var function_call : MessageFunctionCall ?
35+ }
36+
37+ struct MessageFunctionCall : Codable , Equatable {
38+ /// The name of the
39+ var name : String
40+ /// A JSON string.
41+ var arguments : String
42+ }
43+
44+ enum FunctionCallStrategy : Encodable , Equatable {
45+ /// Forbid the bot to call any function.
46+ case none
47+ /// Let the bot choose what function to call.
48+ case auto
49+ /// Force the bot to call a function with the given name.
50+ case name( String )
51+
52+ struct CallFunctionNamed : Codable {
53+ var name : String
54+ }
55+
56+ func encode( to encoder: Encoder ) throws {
57+ var container = encoder. singleValueContainer ( )
58+ switch self {
59+ case . none:
60+ try container. encode ( " none " )
61+ case . auto:
62+ try container. encode ( " auto " )
63+ case let . name( name) :
64+ try container. encode ( CallFunctionNamed ( name: name) )
65+ }
66+ }
67+ }
68+
69+ struct Function : Codable {
70+ var name : String
71+ var description : String
72+ /// JSON schema.
73+ var arguments : String
1974 }
2075
2176 var model : String
@@ -30,6 +85,8 @@ struct CompletionRequestBody: Codable, Equatable {
3085 var frequency_penalty : Double ?
3186 var logit_bias : [ String : Double ] ?
3287 var user : String ?
88+ var function_call : FunctionCallStrategy ?
89+ var functions : [ Int ] = [ ]
3390}
3491
3592struct CompletionStreamDataTrunk : Codable {
@@ -47,6 +104,7 @@ struct CompletionStreamDataTrunk: Codable {
47104 struct Delta : Codable {
48105 var role : ChatMessage . Role ?
49106 var content : String ?
107+ var function_call : String ?
50108 }
51109 }
52110}
0 commit comments