forked from lean-dojo/LeanCopilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExternal.lean
More file actions
97 lines (66 loc) · 2.32 KB
/
External.lean
File metadata and controls
97 lines (66 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import Lean
import LeanCopilot.Models.Interface
set_option autoImplicit false
open Lean
namespace LeanCopilot
structure ExternalModel where
name : String
host : String := "localhost"
port : UInt16 := 23337
deriving Inhabited, Repr
structure ExternalGenerator extends ExternalModel
deriving Repr
structure GeneratorRequest where
name : String
input : String
«prefix» : String
deriving ToJson
structure Generation where
output: String
score: Float
deriving FromJson
structure GeneratorResponse where
outputs : Array Generation
deriving FromJson
structure EnencoderRequest where
name : String
input : String
deriving ToJson
structure EncoderResponse where
outputs : Array Float
deriving FromJson
def send {α β : Type} [ToJson α] [FromJson β] (req : α) (url : String) : IO β := do
let reqStr := (toJson req).pretty 99999999999999999
let out ← IO.Process.output {
cmd := "curl"
args := #["-X", "POST", url, "-H", "accept: application/json", "-H", "Content-Type: application/json", "-d", reqStr]
}
if out.exitCode != 0 then
throw $ IO.userError s!"Request failed. Please check if the server is up at `{url}`."
let some json := Json.parse out.stdout |>.toOption
| throw $ IO.userError "Failed to parse response"
let some res := (fromJson? json : Except String β) |>.toOption
| throw $ IO.userError "Failed to parse response"
return res
def ExternalGenerator.generate (model : ExternalGenerator) (input : String) (targetPrefix : String) : IO $ Array (String × Float) := do
let url := s!"http://{model.host}:{model.port}/generate"
let req : GeneratorRequest := {
name := model.name,
input := input,
«prefix» := targetPrefix
}
let res : GeneratorResponse ← send req url
return res.outputs.map fun g => (g.output, g.score)
instance : TextToText ExternalGenerator := ⟨ExternalGenerator.generate⟩
structure ExternalEncoder extends ExternalModel
deriving Repr
def ExternalEncoder.encode (model : ExternalEncoder) (input : String) : IO FloatArray := do
let url := s!"http://{model.host}:{model.port}/encode"
let req : EnencoderRequest := {
name := model.name,
input := input,
}
let res : EncoderResponse ← send req url
return FloatArray.mk res.outputs
instance : TextToVec ExternalEncoder := ⟨ExternalEncoder.encode⟩
end LeanCopilot