-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllmwrapper.py
166 lines (117 loc) · 3.91 KB
/
llmwrapper.py
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Tuple,
Union,
)
from pydantic import Extra, Field, root_validator
import requests
import json
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import BaseChatModel
from langchain.llms.base import LLM
from langchain.schema import Generation, LLMResult
from langchain.callbacks.manager import (
AsyncCallbackManager,
AsyncCallbackManagerForLLMRun,
CallbackManager,
CallbackManagerForLLMRun,
Callbacks
)
from langchain.schema import (
AIMessage,
BaseMessage,
ChatGeneration,
ChatMessage,
ChatResult,
HumanMessage,
SystemMessage
)
# a langchain LLM just handles text - you probaby want a chatmodel instead
class CustomLLM(LLM):
service_name: str
model_name: str
@property
def _llm_type(self) -> str:
return self.service_name + "." + self.model_name
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
if stop is not None:
raise ValueError("stop kwargs are not permitted.")
response = requests.post(
url="http://localhost:3010/llm",
json={
"service": self.service_name,
"model": self.model_name,
"prompt": prompt
},
)
#print(response.content)
if response.status_code != 200:
optional_detail = response.text
raise ValueError(
f"LLM call failed with status code {response.status_code}. "
f"Details: {optional_detail}"
)
#response_text = response.text
#return response_text
response_dict = response.json()
if "error" in response_dict:
raise ValueError(response_dict["error"])
# langchain requires a string response
return response_dict["completion"]
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {}
def testLLM():
llm = CustomLLM(service_name="openai", model_name="gpt-4")
result = llm(
'''In less than 10 words, answer the following questions:
Do you know the way to San Jose?''')
print(result)
#result = llm("You can really breathe in San Jose")
#print(result)
#result = llm("I got lots of friends in San Jose")
#print(result)
class CustomChatModel(BaseChatModel):
service_name: str
model_name: str
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return self.service_name + "-" + self.model_name
def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> ChatResult:
llm = CustomLLM(service_name=self.service_name, model_name=self.model_name)
prompt = "".join(message.content for message in messages)
content = llm(prompt)
return ChatResult(generations=[ChatGeneration(message=SystemMessage(content=content))])
async def _agenerate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
) -> ChatResult:
return ChatResult(generations=[ChatGeneration(message=SystemMessage(content="not used"))])
def testChatModel():
#chat_model = CustomChatModel(service_name="openai", model_name="text-davinci-002-render-sha")
chat_model = CustomChatModel(service_name="poe", model_name="Claude-instant")
message = HumanMessage(content="describe Sandestin FL in just 5 words or less")
print(chat_model([message]).content)
if __name__ == "__main__":
#testLLM()
testChatModel()