Text Summary API Endpoint

Test this app for free
24
import logging
from fastapi import FastAPI, HTTPException
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
from abilities import llm

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()

class TextInput(BaseModel):
    text: str

@app.get("/", include_in_schema=False)
def root():
    return RedirectResponse(url="/docs")

@app.post("/summarize")
async def summarize_text(input_data: TextInput):
    try:
        response_schema = {
            "type": "object",
            "properties": {
Get full code

Frequently Asked Questions

What are some potential business applications for this Text Summary API Endpoint?

The Text Summary API Endpoint has numerous business applications across various industries. Some examples include: - Content curation: Quickly summarize articles, reports, or long-form content for newsletters or social media posts. - Customer support: Summarize lengthy customer inquiries or support tickets to help agents respond more efficiently. - Market research: Condense lengthy market reports or competitor analyses into digestible summaries for decision-makers. - Legal document processing: Summarize contracts, legal briefs, or case studies to save time for legal professionals. - Educational tools: Create concise summaries of textbooks or academic papers for students and researchers.

How can this Text Summary API Endpoint improve productivity in a business setting?

The Text Summary API Endpoint can significantly boost productivity by: - Reducing time spent reading and processing long documents. - Enabling faster decision-making by providing concise summaries of important information. - Facilitating better information sharing across teams by creating easily digestible content. - Automating the summarization process, allowing employees to focus on higher-value tasks. - Improving content creation workflows by quickly generating summaries for various communication channels.

What are the potential cost savings associated with implementing this Text Summary API Endpoint?

Implementing the Text Summary API Endpoint can lead to cost savings in several ways: - Reduced labor costs: Automating summarization tasks can save countless hours of manual work. - Improved decision-making: Quicker access to summarized information can lead to more informed and timely decisions, potentially avoiding costly mistakes. - Increased efficiency: By streamlining information processing, businesses can handle more tasks with existing resources. - Lower training costs: New employees can quickly get up to speed by accessing concise summaries of company documents and processes. - Optimized content creation: Content teams can produce more output in less time by leveraging automated summaries as a starting point.

How can I customize the summary length in the Text Summary API Endpoint?

To customize the summary length in the Text Summary API Endpoint, you can modify the prompt and response schema in the summarize_text function. Here's an example of how to change it to 100 words:

```python @app.post("/summarize") async def summarize_text(input_data: TextInput): try: response_schema = { "type": "object", "properties": { "summary": { "type": "string", "description": "Summary of the input text in under 100 words" } }, "required": ["summary"] }

       prompt = f"Please summarize the following text in under 100 words:\n\n{input_data.text}"

       # Rest of the function remains the same

```

By adjusting the word count in both the description and the prompt, you can control the desired summary length.

How can I add error handling for invalid input in the Text Summary API Endpoint?

To add error handling for invalid input, you can modify the TextInput model and the summarize_text function. Here's an example:

```python from pydantic import BaseModel, Field, validator

class TextInput(BaseModel): text: str = Field(..., min_length=10, max_length=10000)

   @validator('text')
   def check_text_content(cls, v):
       if not v.strip():
           raise ValueError('Input text cannot be empty or just whitespace')
       return v

@app.post("/summarize") async def summarize_text(input_data: TextInput): try: # Existing function code except ValueError as ve: logger.error(f"Invalid input: {str(ve)}") raise HTTPException(status_code=400, detail=str(ve)) except Exception as e: logger.error(f"Error during summarization: {str(e)}") raise HTTPException(status_code=500, detail="Error processing the text") ```

This modification adds input validation to ensure the text is between 10 and 10,000 characters and not just whitespace. It also includes specific error handling for invalid input.

Created: | Last Updated:

API endpoint for summarizing text with LLM in under 200 words.

Here's a step-by-step guide on how to use the Text Summary API Endpoint template:

Introduction

This template provides an API endpoint for summarizing text using a Language Model (LLM). It takes a text input and returns a summary of the text in under 200 words.

Getting Started

  1. Click "Start with this Template" to begin using the Text Summary API Endpoint template in the Lazy Builder interface.

Test the Application

  1. Press the "Test" button to deploy the application and launch the Lazy CLI.

Using the API

Once the application is deployed, you'll receive two important links through the Lazy builder CLI:

  • An API endpoint URL
  • A documentation (docs) link

  • Open the documentation link in your web browser. This will take you to the FastAPI auto-generated documentation page.

  • On the docs page, you'll see the /summarize endpoint. Click on it to expand the details.

  • Click the "Try it out" button.

  • In the request body, replace the example with your own text that you want to summarize. For example:

json { "text": "Your long text goes here. This can be multiple sentences or paragraphs that you want to summarize." }

  1. Click the "Execute" button to send the request.

  2. Scroll down to see the response. The API will return a JSON object containing the summary of your input text.

Sample Request and Response

Here's an example of how to use the API programmatically:

```python import requests import json

url = "YOUR_API_ENDPOINT_URL/summarize" headers = {"Content-Type": "application/json"} data = { "text": "Your long text goes here. This can be multiple sentences or paragraphs that you want to summarize." }

response = requests.post(url, headers=headers, data=json.dumps(data)) result = response.json()

print(result["summary"]) ```

The response will be in this format:

json { "summary": "A concise summary of your input text, not exceeding 200 words." }

Integrating the API

To integrate this summarization API into your application:

  1. Use the API endpoint URL provided by the Lazy builder CLI.
  2. Send POST requests to the /summarize endpoint with your text in the request body.
  3. Parse the JSON response to extract the summary.

You can use this API in various scenarios, such as:

  • Summarizing articles or long-form content
  • Creating brief descriptions for products or services
  • Generating concise versions of documents or reports

Remember to handle any potential errors or exceptions in your integration to ensure a smooth user experience.



Template Benefits

  1. Efficient Information Processing: This API enables businesses to quickly summarize large volumes of text, saving time and improving productivity for employees who need to digest extensive information rapidly.

  2. Enhanced Content Creation: Content creators and marketers can use this tool to generate concise summaries of longer articles or reports, facilitating the creation of social media posts, email newsletters, or executive briefs.

  3. Improved Customer Service: By summarizing lengthy customer inquiries or feedback, support teams can quickly grasp the core issues and provide more timely and accurate responses, enhancing customer satisfaction.

  4. Streamlined Research and Analysis: Researchers and analysts can use this API to summarize multiple documents or reports, accelerating the process of literature review and data analysis in various industries.

  5. Scalable NLP Integration: The template provides a foundation for easily integrating advanced natural language processing capabilities into existing business systems, allowing companies to leverage AI-powered text summarization across multiple applications and departments.

Technologies

Similar templates