代理

代理

使用代理(agent)可以賦予語言模型其他能力,以便完成你下的指令,例如提供文件编辑、google搜尋的工具,便可以使語言模型提供更準確地回答,也可以請他幫忙儲存或刪除文件。

範例

在範例1中,創建了一個可以讓使用者輸入文字的工具,也提供給代理一個將文字儲存成json檔案的工具。創建代理後,我們指示它詢問用戶問題,並將結果儲存到default.json中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

def input_func(question: str):
response = input(question)
return str({"question": question, "answer": response})



input_tool = akasha.create_tool(
"user_question_tool",
"This is the tool to ask user question, the only one param question is the question string that has not been answered and we want to ask user.",
func=input_func)

ao = akasha.test_agent(verbose=True,
tools=[
input_tool,
akasha.get_saveJSON_tool(),
],
model="openai:gpt-3.5-turbo")
print(
ao("逐個詢問使用者以下問題,若所有問題都回答了,則將所有問題和回答儲存成default.json並結束。問題為:1.房間燈關了嗎? \n2. 有沒有人在家? \n3.有哪些電器開啟?\n"
))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

I have successfully saved all the questions and answers into the "default.json" file. The conversation is now complete.

### default.json ###
[
{
"question": "房間燈關了嗎?",
"answer": "no"
},
{
"question": "有沒有人在家?",
"answer": "no"
},
{
"question": "有哪些電器開啟?",
"answer": "phone, shower"
}
]



在範例二中,我們添加了wikipedia工具,讓語言模型能透過Wikipedia API查詢必要的資訊來幫助回答。由於wiki的回答中可能包含不必要的資訊,我們可以使用retri_observation來擷取與問題有關的回答。

1
2
3
4
5
6
7
8
9
10

ao = akasha.test_agent(
verbose=True,
tools=[input_tool,
akasha.get_saveJSON_tool(),
akasha.get_wiki_tool()],
retri_observation=True,
model="openai:gpt-3.5-turbo")
print(ao("請用中文回答李遠哲跟黃仁勳誰比較老?將查到的資訊和答案儲存成json檔案,檔名為AGE.json"))

1
2
3
4
5
6
7
8
9
根據查到的資訊,李遠哲(Yuan T. Lee)比黃仁勳(Jensen Huang)更老。李遠哲於1936年11月19日出生,而黃仁勳的出生日期是1963年2月17日。我已將這些資訊儲存成名為"AGE.json"的
JSON檔案。

### AGE.json ###
{
"李遠哲": "1936-11-19",
"黃仁勳": "1963-02-17",
"答案": "李遠哲比黃仁勳更老"
}


stream

若你想及時得到每輪agent的回應,可以使用stream function,此函式將每輪agent的回應回傳為generator

1
2
3
4
5
6
7
8
9
10
11

ao = akasha.test_agent(
verbose=True,
tools=[input_tool,
akasha.get_saveJSON_tool(),
akasha.get_wiki_tool()],
retri_observation=True,
model="openai:gpt-3.5-turbo")
st = ao.stream("請用中文回答李遠哲跟黃仁勳誰比較老?將查到的資訊和答案儲存成json檔案,檔名為AGE.json")
for s in st:
print(s)




test_agent 中的所有參數:

1
2
3
4
5
6
7
8
9
10
11
12
Args:
model (str, optional): 使用的大語言模型. Defaults to "gpt-3.5-turbo".\n
verbose (bool, optional): 是否顯示log文字. Defaults to False.\n
language (str, optional): 用來計算文字長度(max_doc_len)的語言. Defaults to "zh"
temperature (float, optional): 大語言模型的temperature(0.0 ~ 1.0) . Defaults to 0.0.\n
keep_logs (bool, optional)**: 是否紀錄執行的log. Defaults to False.\n
max_round (int, optional)**: agent最多執行次數,超過即跳出,避免無線迴圈. Defaults to 20.\n
max_input_tokens (int, optional): agent保留的之前做過的思考與動作的文字最大長度. Defaults to 3200.\n
max_past_observation (int, optional)**: agent保留的之前做過的思考與動作的最多次數. Defaults to 10.\n
retri_observation (bool, optional)**: 若設為True, agent會利用大語言模型去擷取tool回傳內容,避免多餘文字輸入. Defaults to False.\n