My Code Tool doesn't read my input in Python

Hello, I have an AI Agent which gives back a json list with parameters, which I have to use with a Code Tool. The problem is that I am unable to even read one of these parameters on my Code Tool and give it back as output.

I tried all options I know: query, input.params.get(), all the json.loads possibilities and anything I could find on the web, so that I can at least verify if something is read at all from my Agent.

When working with Javascript it worked but I need the whole thing in python. What can be done, any idea?

1 Like

Hi @harnesspnuaa Welcome!
in a custom code tool in python, you can access AI agent’s input via query or _query

The query variable in Python Code Tool is the right track, but there’s a catch – in Python mode, the agent passes the entire input as a single string, not a parsed dict. So when your agent sends {"param1": "value"}, what you get in query is literally the string '{"param1": "value"}' – you have to parse it yourself.

Here’s the pattern that actually works:

import json

# query comes in as a raw string from the agent
raw = query  # this is a string, not a dict

try:
    params = json.loads(raw)
except Exception:
    # if the agent sent plain text, handle gracefully
    params = {"input": raw}

# now access your params normally
param1 = params.get("param1", "default")

return {"result": param1}

A few things worth checking:

  1. Make sure your agent’s tool description tells it exactly what JSON structure to send – models are literal, if you don’t specify the key names they’ll make them up
  2. If you’re getting None from query, double-check your Code Tool is set to Tool mode (not regular Code node) – the variable injection only happens in tool context
  3. In Python mode the available globals are query, _query (same thing), and json is available by default – no need to import requests or anything fancy for basic parsing

The JavaScript equivalent you got working probably handled the string-to-object conversion automatically. Python just makes you do it explicitly with json.loads().

Hope that gets you unstuck!

Welcome to the community @harnesspnuaa

Here’s how you’ll need to retrieve the output of the AI Agent in n8n’s Python Code node:

# Get the AI Agent's output from the previous node
agent_output = _input.first().json

# If the AI Agent returned a JSON string, parse it
import json
if isinstance(agent_output, str):
    data = json.loads(agent_output)
else:
    data = agent_output

# Now you can access your parameters
# For example, if your JSON has a "parameters" field:
params = data.get('parameters', [])

# Return the output
return {"json": {"result": params}}

Hope this helps!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.