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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287 | class OpenLLM(LLM):
"""打开LLM LLM。
示例:
`pip install llama-index-llms-openllm`
```python
# 如果需要,将OPENLLM_ENDPOINT环境变量设置为远程服务器地址
# os.environ["OPENLLM_ENDPOINT"] = "remote_server_address"
from llama_index.llms.openllm import OpenLLM
# 设置OpenLLM实例
llm = OpenLLM("HuggingFaceH4/zephyr-7b-alpha")
# 使用OpenLLM进行示例完成
response = llm.complete("To infinity, and beyond")
print(str(response))
```"""
model_id: str = Field(
description="Given Model ID from HuggingFace Hub. This can be either a pretrained ID or local path. This is synonymous to HuggingFace's '.from_pretrained' first argument"
)
model_version: Optional[str] = Field(
description="Optional model version to save the model as."
)
model_tag: Optional[str] = Field(
description="Optional tag to save to BentoML store."
)
prompt_template: Optional[str] = Field(
description="Optional prompt template to pass for this LLM."
)
backend: Optional[Literal["vllm", "pt"]] = Field(
description="Optional backend to pass for this LLM. By default, it will use vLLM if vLLM is available in local system. Otherwise, it will fallback to PyTorch."
)
quantize: Optional[Literal["awq", "gptq", "int8", "int4", "squeezellm"]] = Field(
description="Optional quantization methods to use with this LLM. See OpenLLM's --quantize options from `openllm start` for more information."
)
serialization: Literal["safetensors", "legacy"] = Field(
description="Optional serialization methods for this LLM to be save as. Default to 'safetensors', but will fallback to PyTorch pickle `.bin` on some models."
)
trust_remote_code: bool = Field(
description="Optional flag to trust remote code. This is synonymous to Transformers' `trust_remote_code`. Default to False."
)
_llm: openllm.LLM[Any, Any] = PrivateAttr()
def __init__(
self,
model_id: str,
model_version: Optional[str] = None,
model_tag: Optional[str] = None,
prompt_template: Optional[str] = None,
backend: Optional[Literal["vllm", "pt"]] = None,
*args: Any,
quantize: Optional[Literal["awq", "gptq", "int8", "int4", "squeezellm"]] = None,
serialization: Literal["safetensors", "legacy"] = "safetensors",
trust_remote_code: bool = False,
callback_manager: Optional[CallbackManager] = None,
system_prompt: Optional[str] = None,
messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None,
completion_to_prompt: Optional[Callable[[str], str]] = None,
pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT,
**attrs: Any,
):
self._llm = openllm.LLM[Any, Any](
model_id,
model_version=model_version,
model_tag=model_tag,
prompt_template=prompt_template,
system_message=system_prompt,
backend=backend,
quantize=quantize,
serialisation=serialization,
trust_remote_code=trust_remote_code,
embedded=True,
**attrs,
)
if messages_to_prompt is None:
messages_to_prompt = self._tokenizer_messages_to_prompt
# NOTE: We need to do this here to ensure model is saved and revision is set correctly.
assert self._llm.bentomodel
super().__init__(
model_id=model_id,
model_version=self._llm.revision,
model_tag=str(self._llm.tag),
prompt_template=prompt_template,
backend=self._llm.__llm_backend__,
quantize=self._llm.quantise,
serialization=self._llm._serialisation,
trust_remote_code=self._llm.trust_remote_code,
callback_manager=callback_manager,
system_prompt=system_prompt,
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
pydantic_program_mode=pydantic_program_mode,
)
@classmethod
def class_name(cls) -> str:
return "OpenLLM"
@property
def metadata(self) -> LLMMetadata:
"""LLM元数据。"""
return LLMMetadata(
num_output=self._llm.config["max_new_tokens"],
model_name=self.model_id,
)
def _tokenizer_messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
"""使用标记器将消息转换为提示。如果失败,则回退到通用。"""
if hasattr(self._llm.tokenizer, "apply_chat_template"):
return self._llm.tokenizer.apply_chat_template(
[message.dict() for message in messages],
tokenize=False,
add_generation_prompt=True,
)
return generic_messages_to_prompt(messages)
@llm_completion_callback()
def complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
return asyncio.run(self.acomplete(prompt, **kwargs))
@llm_chat_callback()
def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse:
return asyncio.run(self.achat(messages, **kwargs))
@property
def _loop(self) -> asyncio.AbstractEventLoop:
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.get_event_loop()
return loop
@llm_completion_callback()
def stream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseGen:
generator = self.astream_complete(prompt, **kwargs)
# Yield items from the queue synchronously
while True:
try:
yield self._loop.run_until_complete(generator.__anext__())
except StopAsyncIteration:
break
@llm_chat_callback()
def stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
generator = self.astream_chat(messages, **kwargs)
# Yield items from the queue synchronously
while True:
try:
yield self._loop.run_until_complete(generator.__anext__())
except StopAsyncIteration:
break
@llm_chat_callback()
async def achat(
self,
messages: Sequence[ChatMessage],
**kwargs: Any,
) -> ChatResponse:
response = await self.acomplete(self.messages_to_prompt(messages), **kwargs)
return completion_response_to_chat_response(response)
@llm_completion_callback()
async def acomplete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
response = await self._llm.generate(prompt, **kwargs)
return CompletionResponse(
text=response.outputs[0].text,
raw=response.model_dump(),
additional_kwargs={
"prompt_token_ids": response.prompt_token_ids,
"prompt_logprobs": response.prompt_logprobs,
"finished": response.finished,
"outputs": {
"token_ids": response.outputs[0].token_ids,
"cumulative_logprob": response.outputs[0].cumulative_logprob,
"logprobs": response.outputs[0].logprobs,
"finish_reason": response.outputs[0].finish_reason,
},
},
)
@llm_chat_callback()
async def astream_chat(
self,
messages: Sequence[ChatMessage],
**kwargs: Any,
) -> ChatResponseAsyncGen:
async for response_chunk in self.astream_complete(
self.messages_to_prompt(messages), **kwargs
):
yield completion_response_to_chat_response(response_chunk)
@llm_completion_callback()
async def astream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseAsyncGen:
config = self._llm.config.model_construct_env(**kwargs)
if config["n"] > 1:
logger.warning("Currently only support n=1")
texts: List[List[str]] = [[]] * config["n"]
async for response_chunk in self._llm.generate_iterator(prompt, **kwargs):
for output in response_chunk.outputs:
texts[output.index].append(output.text)
yield CompletionResponse(
text=response_chunk.outputs[0].text,
delta=response_chunk.outputs[0].text,
raw=response_chunk.model_dump(),
additional_kwargs={
"prompt_token_ids": response_chunk.prompt_token_ids,
"prompt_logprobs": response_chunk.prompt_logprobs,
"finished": response_chunk.finished,
"outputs": {
"text": response_chunk.outputs[0].text,
"token_ids": response_chunk.outputs[0].token_ids,
"cumulative_logprob": response_chunk.outputs[
0
].cumulative_logprob,
"logprobs": response_chunk.outputs[0].logprobs,
"finish_reason": response_chunk.outputs[0].finish_reason,
},
},
)
|