-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllm-chat-llama3.py
307 lines (281 loc) · 13.8 KB
/
llm-chat-llama3.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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
from flask import Flask, request, jsonify
import transformers
import torch
import os
from waitress import serve
import logging
from flask_swagger_ui import get_swaggerui_blueprint
import json
# Configure logging format
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler("api.log"), logging.StreamHandler()]
)
logger = logging.getLogger(__name__)
app = Flask(__name__)
# Initialize the text generation pipeline
pipeline = transformers.pipeline(
"text-generation",
model="meta-llama/Meta-Llama-3-8B-Instruct",
model_kwargs={"torch_dtype": torch.bfloat16},
device=0 if torch.cuda.is_available() else -1
)
# Define default values for parameters
DEFAULT_TEMPERATURE = 0.7
DEFAULT_TOP_P = 0.9
DEFAULT_MAX_NEW_TOKENS = 256
DEFAULT_MAX_SEQ_LEN = 1024
DEFAULT_MAX_GEN_LEN = 512
@app.route('/generate_text', methods=['POST'])
def generate_text():
"""
Generate Text
---
post:
summary: Generate text based on input messages
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
messages:
type: array
items:
type: object
properties:
role:
type: string
default: "system"
description: "The role of the message (e.g., system, user)"
content:
type: string
default: "Utilize prompt engineering to classify the given text accurately into one of the following predefined categories:\\n Environment\\n Soziales\\n Governance\\n Keine Armut\\n Kein Hunger\\n E-Umweltschutz\\n E-Klimaschutz\\n E-Erneuerbare Energie\\n E-Emissionsreduktion\\n E-Ressourceneffizienz\\n S-Arbeitssicherheit\\n S-Gesundheitsschutz\\n S-Arbeitsbedingungen\\nLimit your response to the identified class, nothing else. Optimize for increased accuracy."
description: "The content of the message"
description: "List of input messages"
default:
- role: "system"
content: "Utilize prompt engineering to classify the given text accurately into one of the following predefined categories:\\n Environment\\n Soziales\\n Governance\\n Keine Armut\\n Kein Hunger\\n E-Umweltschutz\\n E-Klimaschutz\\n E-Erneuerbare Energie\\n E-Emissionsreduktion\\n E-Ressourceneffizienz\\n S-Arbeitssicherheit\\n S-Gesundheitsschutz\\n S-Arbeitsbedingungen\\nLimit your response to the identified class, nothing else. Optimize for increased accuracy."
- role: "user"
content: "Am Wochenende fand ein tolles soziales Event statt. Die Gemeinschaft sammelte Spenden für wohltätige Zwecke und stärkte das Bewusstsein für lokale Anliegen. Mit Musik, Essen und Aktivitäten für alle Altersgruppen war die Veranstaltung ein großer Erfolg und förderte den Zusammenhalt der Gemeinde."
temperature:
type: number
default: 0.7
description: Sampling temperature (optional)
top_p:
type: number
default: 0.9
description: Nucleus sampling parameter (optional)
max_new_tokens:
type: integer
default: 256
description: Maximum number of new tokens to generate (optional)
max_seq_len:
type: integer
default: 1024
description: Maximum sequence length (optional)
max_gen_len:
type: integer
default: 512
description: Maximum generation length (optional)
responses:
200:
description: Generated text
content:
application/json:
schema:
type: object
properties:
generated_text:
type: string
400:
description: Bad Request
500:
description: Internal Server Error
"""
data = request.json
# Log the incoming request
logger.info(f"Incoming request data: {json.dumps(data)}")
if 'messages' not in data:
error_message = 'The "messages" key is required. Optional parameters: temperature, top_p, max_new_tokens, max_seq_len, max_gen_len.'
logger.error(error_message)
return jsonify({'error': error_message}), 400
# Retrieve parameters from the request or use default values
temperature = data.get('temperature', DEFAULT_TEMPERATURE)
top_p = data.get('top_p', DEFAULT_TOP_P)
max_new_tokens = data.get('max_new_tokens', DEFAULT_MAX_NEW_TOKENS)
max_seq_len = data.get('max_seq_len', DEFAULT_MAX_SEQ_LEN)
max_gen_len = data.get('max_gen_len', DEFAULT_MAX_GEN_LEN)
messages = data['messages']
try:
# Create the prompt using the tokenizer's chat template
prompt = pipeline.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
# eos_token_id or terminators
eos_token_id = pipeline.tokenizer.eos_token_id
# Generate the text
outputs = pipeline(
prompt,
max_new_tokens=max_new_tokens,
eos_token_id=eos_token_id,
do_sample=True,
temperature=temperature,
top_p=top_p,
)
# Extract the generated text
result = outputs[0]["generated_text"][len(prompt):]
# Log the generated response
logger.info(f"Generated text: {result}")
return jsonify({'generated_text': result})
except Exception as e:
logger.error(f"Error during text generation: {str(e)}")
return jsonify({'error': str(e)}), 500
# Swagger UI setup
SWAGGER_URL = '/swagger'
API_URL = '/static/swagger.json'
swaggerui_blueprint = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={
'app_name': "Text Generation and Classification API"
}
)
app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)
# Ensure the static directory exists
os.makedirs('static', exist_ok=True)
# Generate Swagger JSON
swagger_template = {
"swagger": "2.0",
"info": {
"title": "Text Generation and Classification API",
"description": "API for generating text based on input messages using a pre-trained large language model.",
"version": "1.0.0"
},
"basePath": "/",
"schemes": ["https"],
"paths": {
"/generate_text": {
"post": {
"summary": "Generate text based on input messages",
"consumes": ["application/json"],
"produces": ["application/json"],
"parameters": [
{
"in": "body",
"name": "body",
"required": True,
"schema": {
"type": "object",
"properties": {
"messages": {
"type": "array",
"items": {
"type": "object",
"properties": {
"role": {
"type": "string",
"default": "system"
},
"content": {
"type": "string",
"default": (
"Utilize prompt engineering to classify the given text accurately into one of the following predefined categories:\n"
" Environment\n"
" Soziales\n"
" Governance\n"
" Keine Armut\n"
" Kein Hunger\n"
" E-Umweltschutz\n"
" E-Klimaschutz\n"
" E-Erneuerbare Energie\n"
" E-Emissionsreduktion\n"
" E-Ressourceneffizienz\n"
" S-Arbeitssicherheit\n"
" S-Gesundheitsschutz\n"
" S-Arbeitsbedingungen\n"
"Limit your response to the identified class, nothing else. Optimize for increased accuracy."
)
}
},
"required": ["role", "content"]
},
"description": "List of input messages",
"default": [
{
"role": "system",
"content": (
"Utilize prompt engineering to classify the given text accurately into one of the following predefined categories:\n"
" Environment\n"
" Soziales\n"
" Governance\n"
" Keine Armut\n"
" Kein Hunger\n"
" E-Umweltschutz\n"
" E-Klimaschutz\n"
" E-Erneuerbare Energie\n"
" E-Emissionsreduktion\n"
" E-Ressourceneffizienz\n"
" S-Arbeitssicherheit\n"
" S-Gesundheitsschutz\n"
" S-Arbeitsbedingungen\n"
"Limit your response to the identified class, nothing else. Optimize for increased accuracy."
)
},
{
"role": "user",
"content": "Am Wochenende fand ein tolles soziales Event statt. Die Gemeinschaft sammelte Spenden für wohltätige Zwecke und stärkte das Bewusstsein für lokale Anliegen. Mit Musik, Essen und Aktivitäten für alle Altersgruppen war die Veranstaltung ein großer Erfolg und förderte den Zusammenhalt der Gemeinde."
}
]
},
"temperature": {
"type": "number",
"default": 0.7,
"description": "Sampling temperature (optional)"
},
"top_p": {
"type": "number",
"default": 0.9,
"description": "Nucleus sampling parameter (optional)"
},
"max_new_tokens": {
"type": "integer",
"default": 256,
"description": "Maximum number of new tokens to generate (optional)"
},
"max_seq_len": {
"type": "integer",
"default": 1024,
"description": "Maximum sequence length (optional)"
},
"max_gen_len": {
"type": "integer",
"default": 512,
"description": "Maximum generation length (optional)"
}
},
"required": ["messages"]
}
}
],
"responses": {
"200": {
"description": "Generated text",
"schema": {
"type": "object",
"properties": {
"generated_text": {"type": "string"}
}
}
},
"400": {"description": "Bad Request"},
"500": {"description": "Internal Server Error"}
}
}
}
}
}
with open('static/swagger.json', 'w') as f:
json.dump(swagger_template, f)
if __name__ == '__main__':
serve(app, host='0.0.0.0', port=5050)