Why http via proxy not working?

You do need the option proxy(localhost:10077). Rather than just Data in the http_post/4 call, you need json(Data). I think you do not need Headers = headers([content_type('application/json; charset="utf-8"')]). If it doesn’t work, try

?- debug(http(_)).

to get feedback on what it is trying to do. As we’ve been here several times, here is code that works :slight_smile: It assumes your key in a file key.

:- use_module(library(http/http_client)).
:- use_module(library(http/http_json)).
:- use_module(library(http/json)).


get_key(Key) :-
    setup_call_cleanup(
        open(key, read, In),
        read_line_to_string(In, Key),
        close(In)).

query_gpt(_{query:Query}, Reply) :-
    get_key(Key),
    Url = 'https://api.openai.com/v1/chat/completions',
    Data = _{ model: 'gpt-3.5-turbo',
              temperature:0.7,
              messages:[
                  _{ role: user,
                     content: Query
                   }
              ]
            },
    http_post(Url, json(Data), Reply0,
              [ json(Data),
                authorization(bearer(Key)),
                status_code(Status),
                json_object(dict)
              ]),
    Reply = Reply0.put(status, Status).

Test run:

?- query_gpt(_{query:"Can you write an elevator pitch on what Prolog is?"}, Solution).
Solution =
_{ choices:[ _{ finish_reason:"stop",
		index:0,
		message:_{ content:"Prolog is a logic programming language that enables computers to reason about problems and provide solutions. It is based on a declarative programming paradigm, which means that users can express what they want the program to do rather than how to do it. Prolog is particularly useful for tasks such as natural language processing, expert systems, and AI. It is an efficient and expressive language that allows users to create complex and flexible programs with ease.",
			   role:"assistant"
			 }
	      }
	   ],
   created:1686055220,
   id:"chatcmpl-7OQGyb9gna0sVD6Ri4s7IjSmFO2GM",
   model:"gpt-3.5-turbo-0301",
   object:"chat.completion",
   status:200,
   usage:_{completion_tokens:86,prompt_tokens:20,total_tokens:106}
 }
1 Like