Pythonの可変長引数の呼び方 / ChatGPTサンプル
Python で可変長引数をもったメソッドを考えてみましょう。以下の a.py があるとき
deftest1(*args):return sum(args)
deftest2(**kwargs):
a1 = kwargs.get("a1",None)
a2 = kwargs.get("a2",None)
return a1+a2それぞれ、ObjectScriptからは次のように呼ぶことができます。 **kwargs は、Dynamic Object 変数の後ろに、ドット3つを付けます。
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
この方法を使うことで、みなさんが大好きな ChatGPT も、Language=python だけでなく、ObjectScriptルーチンからも実行できます。 OpenAI ライブラリ の ChatCompletion.create メソッドが OpenAIのページで解説されている ように、引数が **kwargs タイプです。 上の方法を使って、以下のようなルーチンから実行可能です。
ルーチン各行のコメントは Python で実行するときのコードです。対比にご注目くださいませ。
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())実行例
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?
Python とも親和性の高い ObjectScript、ぜひお楽しみくださいませ。
ディスカッション (0)0