In Python, create a web service. Use the transformers package to generate text for each…
- User
In Python, create a web service. Use the
transformerspackage to generate text for each request with GPT-2. Make it asynchronous. Assistant
In Python, create a web service. Use the transformers package to generate text for each request with GPT-2. Make it asynchronous.
from fastapi import FastAPI
from transformers import pipeline, GPT2Tokenizer, GPT2LMHeadModel
from typing import Optional
import asyncio
import uvicorn
# Initialize GPT-2 model and tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")
generator = pipeline('text-generation', model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
app = FastAPI()
@app.post("/generate/")
async def generate_text(
prompt: str,
max_length: Optional[int] = 50,
num_return_sequences: Optional[int] = 1,
temperature: Optional[float] = 1.0,
top_k: Optional[int] = 50,
top_p: Optional[float] = 1.0,
do_sample: Optional[bool] = True
):
"""
Generates text using GPT-2.
Args:
prompt: The text prompt to generate text from.
max_length: The maximum length of the generated text.
num_return_sequences: The number of text sequences to generate.
temperature: Controls the randomness of the generated text.
top_k: The number of highest probability vocabulary tokens to consider for generation.
top_p: The cumulative probability threshold for vocabulary tokens to consider for generation.
do_sample: Whether to sample from the model's probability distribution.
Returns:
A list of generated text sequences.
"""
async def generate_async():
return generator(
prompt,
max_length=max_length,
num_return_sequences=num_return_sequences,
temperature=temperature,
top_k=top_k,
top_p=top_p,
do_sample=do_sample
)
return await asyncio.gather(generate_async())
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
Explanation:
Import Libraries:
fastapi: For building the web service.transformers: For loading and using the GPT-2 model.asyncio: For asynchronous operations.uvicorn: For running the FastAPI application.Load GPT-2 Model & Tokenizer:
gpt2) and model (gpt2).pipeline from transformers.Create FastAPI App:
Define /generate/ Endpoint:
/generate/ using @app.post("/generate/").prompt: The text prompt.max_length: Maximum length of generated text (optional).num_return_sequences: Number of sequences to generate (optional).temperature, top_k, top_p, do_sample: Parameters for controlling text generation (optional).generate_async to run the GPT-2 generation using the generator pipeline.asyncio.gather(generate_async()) to run the generation asynchronously and await its result.Run the App:
uvicorn.run to start the FastAPI application.host="0.0.0.0" to make it accessible from any network interface.port=8000 to listen on port 8000.How to Run:
gpt2_api.py).pip install fastapi transformers uvicorn
uvicorn gpt2_api:app --reload
--reload flag will restart the server automatically when you make changes to the code.How to Use:
You can use tools like curl or make POST requests to the /generate/ endpoint to generate text.
Example using curl:
curl -X POST "http://localhost:8000/generate/" \
-H "Content-Type: application/json" \
-d '{"prompt": "The future of AI is", "max_length": 30}'
This will send a request to the server to generate text with the prompt "The future of AI is" and a maximum length of 30 tokens. The server will respond with the generated text.
Not yet included in a published release.