LTSuggest - Submit suggestions to a LibreTranslate server from Python

# Written by ChatGPT-4

import requests

def suggest_translation(url, q, s, source, target):
    # Build the JSON payload
    payload = {
        "q": q,
        "s": s,
        "source": source,
        "target": target
    }

    # Add trailing slash to URL if not present
    if not url.endswith("/"):
        url += "/"    
    
    # Make the request
    response = requests.post(f"{url}suggest", json=payload)

    return response

ChatGPT wrote >90% of this! I copied the docs for the API endpoint and it wrote a working version on the first try. It also wrote extensions for uploading CSV data.

It looks like there’s some issue with needing an API key to make suggest requests to LibreTranslate but I haven’t been able to figure it out.

I wasn’t able to recreate the issue locally. When I run LibreTranslate with this configuration the suggest endpoint works:

python main.py --suggestions --api-keys --req-limit 10
$ python demo.py 
Status code: 200
{'success': True}

However, I see the same bug when trying to connect to LibreTranslate.com:

$ python demo.py 
Status code: 400
{'error': 'Visit https://portal.libretranslate.com to get an API key'}

Based on my reading of the code it seems like you should be able to make suggest requests as long as your IP address isn’t over the request limit. I can make translate requests to LibreTranslate.com so I don’t think I’m over the limit and don’t know what the problem is.

Ah, that’s awesome! I find that the newer versions of ChatGPT can write small snippets of code quite well. Queries also. But I always need to double check its output.

1 Like

It could be due to --require-api-key-origin and/or --require-api-key-secret which are both turned on on libretranslate.com. But I haven’t checked.

1 Like

This was it. I reproduced the issue with --require-api-key-secret

python main.py --suggestions --api-keys --req-limit 10 --require-api-key-secret
~/git/LTSuggest$ python demo.py 
Status code: 400
{'error': 'Please contact the server operator to get an API key'
1 Like