'$.messages[1].content' is invalid

This is my error code.
I’ve tried to find out about this, but I haven’t solved it.
Error code: 400 - {‘error’: {‘message’: “‘$.messages[1].content’ is invalid. Please check the API reference: https://platform.openai.com/docs/api-reference.”, ‘type’: ‘invalid_request_error’, ‘param’: None, ‘code’: None}}
Could you tell me which part I need to revise?

1 Like

Welcome to the community!

Looks like you didn’t actually insert the data, but rather sent your code over as a string.

Do you wanna share your code?

here is my code.

from dotenv import load_dotenv
import os
load_dotenv()
from openai import OpenAI
import pyupbit

import pandas as pd
import pandas_ta as ta

import json
import schedule
import time

upbit = pyupbit.Upbit(os.getenv("UPBIT_ACCESS_KEY"), os.getenv("UPBIT_SECRET_KEY"))
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
tickers = ["KRW-BTC"]


# Get current data from upbit
def get_current_data(ticker):
    orderbook = pyupbit.get_orderbook(ticker=ticker)
    current_time = orderbook['timestamp']
    ticker_balance = 0
    krw_balance = 0
    ticker_avg_buy_price = 0
    balances = upbit.get_balances()
    for b in balances:
        if b['currency'] == f"{ticker}":
            ticker_balance = b['balance']
            ticker_avg_buy_price = b['avg_buy_price']
        if b['currency'] == "KRW":
            krw_balance = b['balance']

    current_status = {'current_time': current_time, 'orderbook': orderbook, f'{ticker}_balance': ticker_balance, 'krw_balance': krw_balance, f'{ticker}_avg_buy_price': ticker_avg_buy_price}
    return json.dumps(current_status)

def fetch_and_prepare_data(ticker): #get data from upbit and add indicators
    
    df_daily = pyupbit.get_ohlcv(ticker, interval="day", count=30)
    df_hourly = pyupbit.get_ohlcv(ticker, interval="minute60", count=24*3)

    def add_indicators(df):
        
        # Moving Averages
        df['SMA_10'] = ta.sma(df['close'], length=10)
        df['EMA_10'] = ta.ema(df['close'], length=10)

        # RSI
        df['RSI_14'] = ta.rsi(df['close'], length=14)

        # Stochastic Oscillator
        stoch = ta.stoch(df['high'], df['low'], df['close'], k=14, d=3, smooth_k=3)
        df = df.join(stoch)

        # MACD
        ema_fast = df['close'].ewm(span=12, adjust=False).mean()
        ema_slow = df['close'].ewm(span=26, adjust=False).mean()
        df['MACD'] = ema_fast - ema_slow
        df['Signal_Line'] = df['MACD'].ewm(span=9, adjust=False).mean()
        df['MACD_Histogram'] = df['MACD'] - df['Signal_Line']
        
        # Bollinger Bands
        bbands = ta.bbands(df['close'], length=20)
            
        df['BBands_upper'] = bbands["BBU_20_2.0"]
        df['BBands_middle'] = bbands['BBM_20_2.0']
        df['BBands_lower'] = bbands['BBL_20_2.0']
        
        # OBV
        df['OBV'] = ta.obv(df['close'], df['volume'])

        return df


    df_daily = add_indicators(df_daily)
    df_hourly = add_indicators(df_hourly)

    combined_df = pd.concat([df_daily, df_hourly], keys=['daily', 'hourly'])
    
    return combined_df.to_json()
    
def combine_data(): #combine data from fetch_and_prepare_data and get_current_data
    data_json_files = []
    data_current_files = []
    
    for ticker in tickers:
        data_1 = fetch_and_prepare_data(ticker)
        data_2 = get_current_data(ticker)
        
        # Assuming fetch_and_prepare_data and get_current_data return file paths
        data_json_files.append(data_1)
        data_current_files.append(data_2)

    return data_json_files, data_current_files


def get_instructions(instruction_path):
    try:
        with open(instruction_path, 'r',encoding="utf-8") as f:
            instructions = f.read()
        return instructions
    except FileNotFoundError:
        print("File not found")
    except Exception as e:
          print("An error occurred while reading the file:", e)
          
def get_example_data(example_path):
    try:
        with open(example_path, 'r',encoding="utf-8") as f:
            example_data = f.read()
        return example_data
    except FileNotFoundError:
        print("File not found")
    except Exception as e:
          print("An error occurred while reading the file:", e)
    

def analyze_datas_with_GPT4(data_json, data_current):
    instructions_path = "instructions.md"
    example_path = "example.md"
    try:
        instructions = get_instructions(instructions_path)
        example_data = get_example_data(example_path)   
        if not instructions:
            print("No instructions found")
            return None
        if not example_data:
            print("No example data found")
            return None
        
        response = client.chat.completions.create(
            model="gpt-4-turbo-preview",
            messages=[
                {"role": "system", "content": instructions},
                {"role": "user", "content": data_json},
                {"role": "user", "content": data_current},
                
            ],
            response_format={"type":"json_object"}
        )
        return response.choices[0].message.content

    except Exception as e:
        print(f"Error in analyzing data with GPT-4: {e}")
        return None
    
def execute_buy(ticker,qunatity):
    print(f"Attempting to buy {ticker}...")
    try:
        krw = upbit.get_balance("KRW")
        if krw > 5000:
            upbit.buy_market_order(ticker, volume=qunatity)
            print(f"Successfully bought {ticker}, quantity: {qunatity}")
    except Exception as e:
        print(f"Error in buying {ticker}: {e}")


    
def execute_sell(ticker,qunatity):
    print(f"Attempting to buy {ticker}...")
    try:
        ticker_balance = upbit.get_balance(ticker)
        if ticker_balance > 0:
            upbit.sell_market_order(ticker, volume=qunatity)
            print(f"Successfully sold {ticker}, quantity: {qunatity}")
    except Exception as e:
        print(f"Error in selling {ticker}: {e}")
        
def make_decision_execute():
    print("making decision and executing...")
    data_json, data_current = combine_data()
    advise = analyze_datas_with_GPT4(data_json, data_current)
    
    try:
        decision = json.loads(advise)
        print(decision)
        if decision.get('decision') == "buy":
            execute_buy(decision.get('ticker'), decision.get('quantity'))
        elif decision.get('decision') == "sell":
            execute_sell(decision.get('ticker'), decision.get('quantity'))
            
    except Exception as e:
        print(f"Error in making decision and executing: {e}")

if __name__ == "__main__" :
    make_decision_execute()
    schedule.every().hour.at(":01").do(make_decision_execute)

    while True:
        schedule.run_pending()
        time.sleep(1)
            
            
    

1 Like

If you print out the messages object in “analyze_datas_with_GPT4” - what do you get?

1 Like

I want the GPT to give this answer.
(Response: {“ticker”: “KRW-BTC”, “decision”: “buy”, “quantity”: 0.8, “reason”: “For KRW-BTC, the price has formed a bullish engulfing pattern, indicating a potential reversal from the downtrend. The RSI_14 has also crossed above 30, suggesting the beginning of an uptrend. Recommend buying to capitalize on the expected price increase.”})

no, this here: I’m suspecting that this messages object might be malformed.

2 Likes

Welcome to the OpenAI dev forum@junhl5806

The problem is with the second message in the messages list.

Message "content" can only be string or an array of content parts with defined types, each can be of type text or image_url when passing in images. You can pass multiple images by adding multiple image_url content parts. Image input is only supported when using the gpt-4-vision-preview model.

Here’s API reference for more information.

3 Likes

The data_json and data_current files have a data type of json and the instructions file has a data type of ‘.md’, but is the ‘.md’ file a problem? If it is a problem, should I change this to the json file as well?

“content” needs to be type string, unless you use this content part type (which I don’t think you want). It can’t be a generic JSON.

You can dump the json into a string, and pass it that way, however. But in any case, it needs to be a string.


https://platform.openai.com/docs/api-reference/chat/create#chat-create-messages

3 Likes

Actually, there is a process of grouping the json file into a list, and it seems that the list itself was sent as data. I solved it because it converts the list into a json file. Thank you for your help!

2 Likes

Glad they could help. We’ve got a great dev community growing here.

Hope you stick around and are able to help someone in the future to “pass it forward!”

Happy you got it sorted…

2 Likes