Written by

Senior Developer Support Engineer at InterSystems
Article Seisuke Nakahashi · Apr 27, 2023 2m read

How to call Variable-length arguments Python methods from ObjectScript / sample routine calling ChatGPT

Let's say you have Python including variable-length arguments methods. How can you call it from ObjectScript? 

deftest1(*args):return sum(args)
  
deftest2(**kwargs):
  a1 = kwargs.get("a1",None)
  a2 = kwargs.get("a2",None)
  return a1+a2

You can call this "a.py" from ObjectScript as below.  For **kwargs argument, create Dynamic Object in ObjectScript and put it into methods with <variablename>... (3 dots) format. 

set a=##class(%SYS.Python).Import("a")
    write a.test1(1,2,3)   ;; 6set req={}
    set req.a1=10set req.a2=20write a.test2(req...)   ;; 30


Do you like playing ChatGPT? With this way, you can call ChatGPT APIs not only from Language=python method but from ObjectScript world.  As described in OpenAI page , ChatCompletion.create method of OpenAI library has **kwargs argument. So you can call this API with the following ObjectScript routine.

Please see comments in each line, it's Python code. I hope it will help you when you need to replace Python codes to ObjectScript codes.

set openai = ##class(%SYS.Python).Import("openai")   // import openaiset openai.organization = "xxxx"// openai.organization = "xxxx"set openai."api_key" = "xxxxxxx"// openai.api_key = "xxxxxxx"set builtins = ##class(%SYS.Python).Builtins()

  //  req = (model="gpt-3.5-turbo", messages=[{"role": "user", "content": question ])// m1 = {"role": "user", "content": "Hi, How are you?"}set m1 = builtins.dict()                         // m1 = {}do m1.setdefault("role","user")                  // m1.update (role = 'user')do m1.setdefault("content","Hi, How are you?")   // m1.update (content = 'Hi, How are you?')// msg = [ m1 ]set msg =builtins.list()    // msg = []do msg.append( m1 )         // msg.append ( m1 )// req = { "model": "gpt-3.5-turbo", "messages" : msg }set req = {}                     // req = {}set req.model = "gpt-3.5-turbo"// req.update (model = 'gpt-3.5-turbo')set req.messages = msg           // req.update (messages = msg)set response = openai.ChatCompletion.create(req...)             // response = openai.ChatCompletion.create(**req)write response.choices."__getitem__"(0)."message"."content",!   // print(response.choices[0]["message"]["content"].strip())

[Sample]
USER>do ^chatGPT
I'm good, thank you for asking! As an AI language model, I don't have emotions, but I'm always here to help you with any inquiries or tasks. How can I assist you today?
Happy ObjectScript coding!