#๐Ÿ”’ WebSocket Async Function call - Socket Handler is blocking websocket.recv()

6 messages ยท Page 1 of 1 (latest)

novel spindle
#

I am using websocket to communicate with an AI agent and based on the user prompt the agent shall perform certain function calls on the client side.

async def async_Task1():
    """Run Task1 and interact with WebSocket client."""
    if websocket_client is None:
        print("WebSocket client is not connected.")
        return "Task not performed"

    try:
        print("Sending Task1 request")
        await websocket_client.send(json.dumps({"type": "action_call", "content": "Task1"}))

        # Waiting for a response with a timeout
        print("Waiting for Task1 response")
        try:
            response = await asyncio.wait_for(websocket_client.recv(), timeout=5)  # Adjust timeout as needed
            response_data = json.loads(response)
            print(f"Received response from WebSocket server: {response_data}")
            return response_data.get("content", "No content in response")
        except asyncio.TimeoutError:
            print("Timeout waiting for response")
            return "Timeout waiting for response"
    except Exception as e:
        print(f"Error in Task1: {e}")
        return "Error in Task1"

@tool
def Task1():
    """Runs Task1



    No args
    """
    return asyncio.run(async_Task1())




slim spireBOT
#

@novel spindle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

novel spindle
#

the socket handler:


async def handle_connection(websocket, path):
    global websocket_client
    websocket_client = websocket
    print(f"Client connected from {path}")
    
    try:
        async for message in websocket:
            data = json.loads(message)
            print(f"Received message: {data}")
            
            if data["type"] == "Unity":
                # Do something
                response_object = {
                    "type": "Action",
                    "content": data["content"]
                }
                response_json = json.dumps(response_object)
                await websocket.send(response_json)

            elif data["type"] == "Echo":
                response_object = {
                    "type": "Print",
                    "content": data["content"]
                }
                response_json = json.dumps(response_object)
                await websocket.send(response_json)

            elif data["type"] == "user_prompt":
                response = agent_executor.invoke(
                    {"messages": [HumanMessage(content=data["content"])]}
                )
                # Check if there are any messages
                if response["messages"]:
                    # Print only the last message
                    last_message = response["messages"][-1]
                    print(last_message)
                            
            elif(data["type"] == "action_result"):
                 print(f"Got response from handler as {json.dumps(data)}")
    except websockets.exceptions.ConnectionClosed as e:
        print(f"Connection closed: {e}")
        websocket_client = None
        print(f"Connection closed: {e}")

#

terminal output
Received message: {'type': 'user_prompt', 'content': 'Hows the weather in Chicago, multiply 268 with 584 and Perform Task1'}
Running Mult
Sending Task1 request
Waiting for Task1 response
Timeout waiting for response
content='The weather in Chicago is currently Partly cloudy with a temperature of 23.3 degrees Celsius. The wind is blowing from the East at 10.5 mph. \n\n268 multiplied by 584 is 156,512. \n\nI was unable to perform Task1. \n' response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]} id='run-f704f94e-38cc-46ae-ba80-f5eb2d067f27-0' usage_metadata={'input_tokens': 968, 'output_tokens': 67, 'total_tokens': 1035}
Received message: {'type': 'action_result', 'content': 'Task completed after 2 seconds'}
Got response from handler as {"type": "action_result", "content": "Task completed after 2 seconds"}

slim spireBOT
#

@novel spindle

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.