Spaces:
Runtime error
Runtime error
Delete openai_function_calling_sample_code.py
Browse files
openai_function_calling_sample_code.py
DELETED
|
@@ -1,299 +0,0 @@
|
|
| 1 |
-
# -*- coding: utf-8 -*-
|
| 2 |
-
"""openai_function_calling_sample_code.ipynb
|
| 3 |
-
|
| 4 |
-
Automatically generated by Colaboratory.
|
| 5 |
-
|
| 6 |
-
Original file is located at
|
| 7 |
-
https://colab.research.google.com/drive/1FBRyZ2hTn04o_nvNDaZFtroebmN4jiz-
|
| 8 |
-
|
| 9 |
-
# Function Calling について LangChain Agent と比較しながら試してみた
|
| 10 |
-
|
| 11 |
-
こちらの記事のサンプルコードになります:https://qiita.com/yu-Matsu/items/12b686fe4cab343f50b3
|
| 12 |
-
|
| 13 |
-
## 必要なライブラリのインストール
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
# !pip install openai==0.27.6
|
| 17 |
-
# !pip install langchain==0.0.205
|
| 18 |
-
|
| 19 |
-
"""## 一部ライブラリのインポート、APIキーの設定"""
|
| 20 |
-
|
| 21 |
-
import json
|
| 22 |
-
import os
|
| 23 |
-
import sys
|
| 24 |
-
import openai
|
| 25 |
-
import dotenv
|
| 26 |
-
|
| 27 |
-
dotenv.load_dotenv(".env")
|
| 28 |
-
openai.api_key = os.environ.get("OPENAI_API_KEY")
|
| 29 |
-
# print("OPENAI_API_KEY: ", openai.api_key)
|
| 30 |
-
|
| 31 |
-
print("""## 普通にChatGPTに天気を聞いてみる""")
|
| 32 |
-
|
| 33 |
-
def chat_gpt_without_functions(text):
|
| 34 |
-
response = openai.ChatCompletion.create(
|
| 35 |
-
model="gpt-3.5-turbo-0613",
|
| 36 |
-
messages=[
|
| 37 |
-
{"role": "user", "content": text},
|
| 38 |
-
]
|
| 39 |
-
)
|
| 40 |
-
|
| 41 |
-
content = response["choices"][0]["message"]["content"]
|
| 42 |
-
print(content)
|
| 43 |
-
|
| 44 |
-
return content
|
| 45 |
-
|
| 46 |
-
print("""# 挨拶は普通に返ってくるが...""")
|
| 47 |
-
chat_gpt_without_functions("こんにちは")
|
| 48 |
-
|
| 49 |
-
print("""# 天気を聞いても返してくれない""")
|
| 50 |
-
chat_gpt_without_functions("東京の天気を教えて")
|
| 51 |
-
|
| 52 |
-
print("""## 今回利用する天気を返す関数""")
|
| 53 |
-
|
| 54 |
-
print("""# locationに応じて固定値で天気を返すだけの簡単な関数""")
|
| 55 |
-
def weather_function(location):
|
| 56 |
-
match location:
|
| 57 |
-
case "東京" | "Tokyo":
|
| 58 |
-
weather = "晴れ"
|
| 59 |
-
case "大阪" | "Osaka":
|
| 60 |
-
weather = "曇り"
|
| 61 |
-
case "北海道" | "Hokkaido":
|
| 62 |
-
weather = "雪"
|
| 63 |
-
case _ :
|
| 64 |
-
weather = "不明"
|
| 65 |
-
|
| 66 |
-
weather_answer = [
|
| 67 |
-
{"天気": weather}
|
| 68 |
-
]
|
| 69 |
-
|
| 70 |
-
return json.dumps(weather_answer)
|
| 71 |
-
|
| 72 |
-
print("""# 実際に Function callingを動かしてみる""")
|
| 73 |
-
|
| 74 |
-
def chat_gpt_with_function(text):
|
| 75 |
-
# AIが呼び出せる関数の定義
|
| 76 |
-
functions = [
|
| 77 |
-
# 何をする関数かについて記述
|
| 78 |
-
{
|
| 79 |
-
"name": "weather",
|
| 80 |
-
"description": "天気を調べる",
|
| 81 |
-
"parameters": {
|
| 82 |
-
"type": "object",
|
| 83 |
-
"properties": {
|
| 84 |
-
# location引数についての情報を記述
|
| 85 |
-
"location": {
|
| 86 |
-
"type": "string",
|
| 87 |
-
"description": "天気を知りたい場所を入力。例: 東京",
|
| 88 |
-
},
|
| 89 |
-
},
|
| 90 |
-
"required": ["location"],
|
| 91 |
-
},
|
| 92 |
-
}
|
| 93 |
-
]
|
| 94 |
-
|
| 95 |
-
# ユーザーの入力から、Functions Callingが必要かどうか判断する
|
| 96 |
-
response = openai.ChatCompletion.create(
|
| 97 |
-
model="gpt-3.5-turbo-0613",
|
| 98 |
-
messages=[
|
| 99 |
-
{"role": "user", "content": text},
|
| 100 |
-
],
|
| 101 |
-
functions=functions,
|
| 102 |
-
function_call="auto",
|
| 103 |
-
)
|
| 104 |
-
|
| 105 |
-
# Function Callingが必要なければ、そのままAIの回答になる
|
| 106 |
-
message = response["choices"][0]["message"]
|
| 107 |
-
|
| 108 |
-
# Functions Callingが必要な場合は、messageに関数名と引数を格納されている
|
| 109 |
-
if message.get("function_call"):
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
print("------function_callの中身------")
|
| 113 |
-
print(message["function_call"])
|
| 114 |
-
print("--------------------------------------")
|
| 115 |
-
|
| 116 |
-
# messageから実行する関数と引数を取得
|
| 117 |
-
function_name = message["function_call"]["name"]
|
| 118 |
-
arguments = json.loads(message["function_call"]["arguments"])
|
| 119 |
-
|
| 120 |
-
# 関数を実行
|
| 121 |
-
if function_name == "weather":
|
| 122 |
-
function_response = weather_function(
|
| 123 |
-
location=arguments.get("location"),
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
# 関数の実行結果を元にAIの回答を生成
|
| 127 |
-
second_response = openai.ChatCompletion.create(
|
| 128 |
-
model="gpt-3.5-turbo-0613",
|
| 129 |
-
messages=[
|
| 130 |
-
{"role": "user", "content": text},
|
| 131 |
-
message,
|
| 132 |
-
{
|
| 133 |
-
"role": "function",
|
| 134 |
-
"name": function_name,
|
| 135 |
-
"content": function_response,
|
| 136 |
-
},
|
| 137 |
-
],
|
| 138 |
-
)
|
| 139 |
-
|
| 140 |
-
content = "AIの回答: " + second_response.choices[0]["message"]["content"]
|
| 141 |
-
else:
|
| 142 |
-
content = "AIの回答: " + message["content"]
|
| 143 |
-
|
| 144 |
-
print(content)
|
| 145 |
-
return content
|
| 146 |
-
|
| 147 |
-
print("""# 挨拶をした場合は、Functionを呼び出す必要がないと判断される""")
|
| 148 |
-
chat_gpt_with_function("こんにちは")
|
| 149 |
-
|
| 150 |
-
print("""# 天気を聞いた場合、Functionを呼び出す必要があると判断され、関数名と引数の情報が「function_call」に格納されている""")
|
| 151 |
-
chat_gpt_with_function("東京の天気を教えて")
|
| 152 |
-
|
| 153 |
-
print("""## LangChain の Agent の場合""")
|
| 154 |
-
|
| 155 |
-
from langchain.llms import OpenAI
|
| 156 |
-
from langchain.agents import initialize_agent, Tool
|
| 157 |
-
from langchain.agents.mrkl import prompt
|
| 158 |
-
|
| 159 |
-
def lang_chain_agent(text):
|
| 160 |
-
llm = OpenAI(model_name='gpt-3.5-turbo-0613')
|
| 161 |
-
# toolsに利用したいToolを格納する。LangChainで用意されたToolを利用することも出来る。
|
| 162 |
-
# 代表的なTool一覧:https://book.st-hakky.com/docs/agents-of-langchain/
|
| 163 |
-
tools = [
|
| 164 |
-
Tool(
|
| 165 |
-
name = "Weather",
|
| 166 |
-
func=weather_function,
|
| 167 |
-
description="天気を知りたい場所を入力。例: 東京",
|
| 168 |
-
)
|
| 169 |
-
]
|
| 170 |
-
|
| 171 |
-
# エージェントの準備
|
| 172 |
-
agent = initialize_agent(
|
| 173 |
-
tools,
|
| 174 |
-
llm,
|
| 175 |
-
agent="zero-shot-react-description",
|
| 176 |
-
agent_kwargs=dict(suffix='Answer should be in Japanese.' + prompt.SUFFIX),
|
| 177 |
-
verbose=True,
|
| 178 |
-
return_intermediate_steps=True)
|
| 179 |
-
|
| 180 |
-
response = agent({"input": text})
|
| 181 |
-
|
| 182 |
-
return response
|
| 183 |
-
|
| 184 |
-
print("""
|
| 185 |
-
# 東京の天気について質問すると、toolsで用意した「Weather」が利用され、その結果を元にAIの回答が生成されていることが分かる
|
| 186 |
-
# 動作が安定しない可能性があるため、失敗する場合は何度か実行してみて下さい
|
| 187 |
-
lang_chain_agent("東京の天気を教えて")
|
| 188 |
-
""")
|
| 189 |
-
|
| 190 |
-
print("""## LangChain で Function Calling を利用してみる""")
|
| 191 |
-
|
| 192 |
-
from langchain.schema import (
|
| 193 |
-
AIMessage,
|
| 194 |
-
HumanMessage,
|
| 195 |
-
FunctionMessage
|
| 196 |
-
)
|
| 197 |
-
from langchain.chat_models import ChatOpenAI
|
| 198 |
-
|
| 199 |
-
def lang_chain_with_function_calling(text):
|
| 200 |
-
# AIが利用する関数の定義
|
| 201 |
-
functions = [
|
| 202 |
-
# 何をする関数かについて記述
|
| 203 |
-
{
|
| 204 |
-
"name": "weather",
|
| 205 |
-
"description": "天気を調べる",
|
| 206 |
-
"parameters": {
|
| 207 |
-
"type": "object",
|
| 208 |
-
"properties": {
|
| 209 |
-
# location引数についての情報を記述
|
| 210 |
-
"location": {
|
| 211 |
-
"type": "string",
|
| 212 |
-
"description": "天気を知りたい場所を入力。例: 東京",
|
| 213 |
-
},
|
| 214 |
-
},
|
| 215 |
-
"required": ["location"],
|
| 216 |
-
},
|
| 217 |
-
}
|
| 218 |
-
]
|
| 219 |
-
|
| 220 |
-
# ユーザーの入力をmessagesに格納
|
| 221 |
-
messages=[HumanMessage(content=text)]
|
| 222 |
-
|
| 223 |
-
llm=ChatOpenAI(model_name='gpt-3.5-turbo-0613')
|
| 224 |
-
|
| 225 |
-
# ユーザーの入力内容から、Functions Callingが必要かどうか判断する
|
| 226 |
-
# Function Callingが必要なければ、こちらの結果がAIの回答になる
|
| 227 |
-
message = llm.predict_messages(
|
| 228 |
-
messages, functions=functions
|
| 229 |
-
)
|
| 230 |
-
|
| 231 |
-
print("==================")
|
| 232 |
-
print(message)
|
| 233 |
-
print("==================")
|
| 234 |
-
|
| 235 |
-
# Functions Callingが必要な場合は、additional_kwargsに関数名と引数を格納されている
|
| 236 |
-
if message.additional_kwargs:
|
| 237 |
-
|
| 238 |
-
# messageから実行する関数と引数を取得
|
| 239 |
-
function_name = message.additional_kwargs["function_call"]["name"]
|
| 240 |
-
arguments = json.loads(message.additional_kwargs["function_call"]["arguments"])
|
| 241 |
-
|
| 242 |
-
# 関数を実行
|
| 243 |
-
function_response = weather_function(
|
| 244 |
-
location=arguments.get("location"),
|
| 245 |
-
)
|
| 246 |
-
|
| 247 |
-
# 実行結果をFunctionMessageとしてmessagesに追加
|
| 248 |
-
function_message = FunctionMessage(name=function_name, content=function_response)
|
| 249 |
-
messages.append(function_message)
|
| 250 |
-
|
| 251 |
-
# FuncitonMessageを元に、AIの回答を取得
|
| 252 |
-
second_response = llm.predict_messages(
|
| 253 |
-
messages=messages, functions=functions
|
| 254 |
-
)
|
| 255 |
-
content = "AIの回答: " + second_response.content
|
| 256 |
-
else:
|
| 257 |
-
content = "AIの回答: " + message.content
|
| 258 |
-
|
| 259 |
-
print(content)
|
| 260 |
-
return content
|
| 261 |
-
|
| 262 |
-
print("""# 挨拶の場合は、contentにAIのレスポンスが格納されており、Functionの情報は含まれていない""")
|
| 263 |
-
lang_chain_with_function_calling("こんにちは")
|
| 264 |
-
|
| 265 |
-
print("""# 天気を聞いた場合、contentにAIのレスポンスは含まれず、additional_kwgargsに呼び出すFunctionの情報が格納されている""")
|
| 266 |
-
lang_chain_with_function_calling("東京の天気を教えて")
|
| 267 |
-
|
| 268 |
-
print("""# Agent にも対応""")
|
| 269 |
-
|
| 270 |
-
from langchain.agents import AgentType
|
| 271 |
-
|
| 272 |
-
def lang_chain_agent_with_function_calling(text):
|
| 273 |
-
llm = ChatOpenAI(model_name='gpt-3.5-turbo-0613')
|
| 274 |
-
# カスタムツールの登録は従来のAgentと同様
|
| 275 |
-
tools = [
|
| 276 |
-
Tool(
|
| 277 |
-
name = "Weather",
|
| 278 |
-
func=weather_function,
|
| 279 |
-
description="天気を知りたい場所を入力。例: 東京"
|
| 280 |
-
)
|
| 281 |
-
]
|
| 282 |
-
|
| 283 |
-
# エージェントの準備
|
| 284 |
-
agent = initialize_agent(
|
| 285 |
-
tools,
|
| 286 |
-
llm,
|
| 287 |
-
agent=AgentType.OPENAI_FUNCTIONS, # ここで、AgentType.OPENAI_FUNCTIONSを指定する
|
| 288 |
-
verbose=True,
|
| 289 |
-
return_intermediate_steps=True)
|
| 290 |
-
|
| 291 |
-
response = agent({"input": text})
|
| 292 |
-
print(response)
|
| 293 |
-
return response
|
| 294 |
-
|
| 295 |
-
print("""# 挨拶の場合はFunctionが利用されていないことが実行結果(intermediate_steps)から分かる""")
|
| 296 |
-
lang_chain_agent_with_function_calling("こんにちは")
|
| 297 |
-
|
| 298 |
-
print("""# 天気を聞いた場合、intermediate_stepsに��AIMessageとしてFunctionが呼び出されていることが分かる""")
|
| 299 |
-
lang_chain_agent_with_function_calling("今日の東京の天気を教えて")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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