Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In my python code i get the error 'await' outside function

Whenever i try to make a Chatbot I choose to use endpoint

But i get this error File "/app/chatbot/plugins/response.py", line 10 print((await get_response('world'))) ^ SyntaxError: 'await' outside function

Please help me i would be highly obliged if you help me

Where my code is

import aiohttp

async def get_response(query):
    async with aiohttp.ClientSession() as ses:
        async with ses.get(
            f'https://some-random-api.ml/chatbot?message={query}'
        ) as resp:
            return (await resp.json())['response']

print((await get_response('world')))

like image 629
Reejit Avatar asked Oct 29 '25 10:10

Reejit


1 Answers

Solution:

await is used in an async functions/methods to wait on other asynchronous tasks, but if you are calling an async function/method outside of an async function/method you need to use asyncio.run() method to call an async function/method

Here is the full solution:

import aiohttp
import asyncio #to run async funtions you need to import asyncio

async def get_response(query):
    async with aiohttp.ClientSession() as ses:
        async with ses.get(
            f'https://some-random-api.ml/chatbot?message={query}'
        ) as resp:
            return (await resp.json())['response']

print((asyncio.run( get_response('world')))#run the async function
like image 67
TERMINATOR Avatar answered Oct 31 '25 23:10

TERMINATOR