二、準(zhǔn)備工作

首先,確保你已經(jīng)安裝了Python環(huán)境和以下庫(kù):

pip install qwen_agent requests #其它所需的模塊

這里如果沒有裝所需的庫(kù),運(yùn)行時(shí)會(huì)提示,根據(jù)提示安裝缺的庫(kù)即可。
沒有ollama也先去安裝ollama并運(yùn)行qwen大模型,過程非常簡(jiǎn)單,網(wǎng)上很多,不再贅述。

三、Agent結(jié)構(gòu)

qwen智能體基本結(jié)構(gòu)是這樣的:先定義工具類tools,然后定義智能體的任務(wù)描述,然后創(chuàng)建一個(gè)智能體,再然后就是web發(fā)布智能體服務(wù),進(jìn)行雙向通訊。

四、python模塊實(shí)現(xiàn)

4.1 實(shí)現(xiàn)手機(jī)號(hào)歸屬地查詢工具

我們首先定義一個(gè)工具M(jìn)obileAddress,用于查詢手機(jī)號(hào)的歸屬地。這個(gè)工具將使用一個(gè)外部API來獲取歸屬地信息。

@register_tool('get_mobile_address')
class MobileAddress(BaseTool):
description = '手機(jī)號(hào)歸屬地查詢服務(wù),輸入手機(jī)號(hào),返回該手機(jī)號(hào)的歸屬地。'
parameters = [{
'name': 'mobile',
'type': 'string',
'description': '輸入的手機(jī)號(hào)',
'required': True
}]

def call(self, params: str, **kwargs) -> str:
print("調(diào)用了function:", len(params))
print("字符串內(nèi)容:",params)

try:
params_json = json.loads(params[:-1])
prompt = params_json["mobile"]
print("轉(zhuǎn)化后的號(hào)碼:", prompt)
except json.JSONDecodeError as e:
print("JSON解析錯(cuò)誤:", e)
return "參數(shù)格式錯(cuò)誤"
res=p.find(prompt)
print("原始查詢結(jié)果:",res)
return res

4.2實(shí)現(xiàn)天氣查詢工具

接下來,我們定義另一個(gè)工具WeatherByAddress,用于根據(jù)城市名稱查詢天氣信息。這個(gè)工具將使用另一個(gè)外部API來獲取天氣數(shù)據(jù)。

@register_tool('get_weather')
class WeatherByAddress(BaseTool):
description = '根據(jù)提供的城市名稱,查找代碼,并通過互聯(lián)網(wǎng)請(qǐng)求查詢天氣信息。'
parameters = [{'name': 'city', 'type': 'string', 'description': '城市名稱', 'required': True}]

def call(self, params: str, **kwargs) -> str:
try:
params_json = json.loads(params)
city_name = params_json["city"]
# 假設(shè)我們有一個(gè)城市代碼的映射字典
city_code = {'Beijing': '101010100'} # 示例代碼
url = f'https://www.weather.com.cn/weather1d/{city_code[city_name]}.shtml'
response = requests.get(url)
if response.status_code == 200:
html_content = response.text
match = re.search(r'var hour3data=(\{.*?\});', html_content)
if match:
hour3data = match.group(1)
return hour3data
else:
return "未找到天氣小時(shí)數(shù)據(jù)"
else:
return "請(qǐng)求失敗,狀態(tài)碼: {}".format(response.status_code)
except json.JSONDecodeError as e:
return "參數(shù)格式錯(cuò)誤"

4.3定義創(chuàng)建Agent主體

最后,我們創(chuàng)建一個(gè)Assistant實(shí)例,這個(gè)agent將使用我們定義的工具來處理用戶的輸入,并返回歸屬地和天氣信息。

from qwen_agent.agents import Assistant

# 配置LLM
llm_cfg = {
'model': 'qwen',#這里可以根據(jù)自己的大模型類型修改配置參數(shù)
'model_server': 'http://localhost:11434/v1',#這里可以根據(jù)自己的大模型類型修改配置參數(shù)
'generate_cfg': {'top_p': 0.8}
}

# 創(chuàng)建agent
system_instruction = '你扮演一個(gè)助手,會(huì)調(diào)用工具,首先獲取用戶輸入的手機(jī)號(hào)碼,并調(diào)用手機(jī)號(hào)歸屬地查詢服務(wù)工具獲得城市地址,然后再調(diào)用天氣查詢工具獲得所在城市的天氣信息,最后進(jìn)行整理,輸出手機(jī)歸屬地和天氣信息'
tools = ['get_mobile_address', 'get_weather']
bot = Assistant(llm=llm_cfg, system_message=system_instruction, description='function calling', function_list=tools)

4.4創(chuàng)建聊天界面

我們將使用FastAPI來創(chuàng)建一個(gè)簡(jiǎn)單的Web界面,用戶可以通過這個(gè)界面輸入手機(jī)號(hào),并獲取歸屬地和天氣信息。

from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("chat.html", {"request": request})

@app.post("/chat")
async def chat(message: str = Form(...)):
messages = [{'role': 'user', 'content': message}]
responses = bot.run(messages=messages)
return {"responses": [content['content'] for content in responses]}

# 運(yùn)行FastAPI應(yīng)用
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='0.0.0.0', port=9000, workers=1)

創(chuàng)建一個(gè)簡(jiǎn)單的html頁(yè)面,如下:

<!DOCTYPE html>
<html>
<head>
<title>Chat Interface</title>
<script>
function send_message() {
var message = document.getElementById("message").value;
if (message.trim() === "") {
alert("Message cannot be empty!");
return;
}
fetch("/chat", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: "message=" + encodeURIComponent(message),
})
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => {
var responses = data.responses;
var chat_window = document.getElementById("chat-window");
responses.forEach(response => {
var response_div = document.createElement("div");
response_div.innerText = response; // Fixed to access response directly
chat_window.appendChild(response_div);
});
document.getElementById("message").value = "";
chat_window.scrollTop = chat_window.scrollHeight;
})
.catch(error => console.error("Error:", error));
}
</script>
</head>
<body>
<div id="chat-window" style="width: 80%; height: 400px; border: 1px solid #000; overflow-y: scroll;"></div>
<input type="text" id="message" placeholder="Type a message..." style="height: 100px;width: 80%;">
<button onclick="send_message()" style="background-color: blue; color: white; font-size: larger; padding: 10px 20px;">Send</button>
</body>
</html>

五、小結(jié)

至此,我們實(shí)現(xiàn)了一個(gè)anget,他可以接收我們輸入的電話號(hào)碼,并且調(diào)用本地大模型進(jìn)行處理,先是調(diào)用一個(gè)手機(jī)號(hào)碼歸屬地查詢tool,再去調(diào)用一個(gè)天氣查詢爬蟲tool,最后大模型綜合tool的反饋信息進(jìn)行整合后輸出給用戶。以上是簡(jiǎn)單的實(shí)現(xiàn),為了更加的準(zhǔn)確好用需要進(jìn)一步優(yōu)化,包括qwen-anget本身好像有點(diǎn)問題,有時(shí)候只能調(diào)用一個(gè)手機(jī)號(hào)碼歸屬地函數(shù)發(fā)揮不是很穩(wěn)定因此需要優(yōu)化prompt,第二,可以加入更多檢查工具,比如,輸入的號(hào)碼檢查,讓大模型自己先檢查一下對(duì)不對(duì),比如對(duì)回答進(jìn)行一些過濾,過濾掉不必要的信息等。

本文章轉(zhuǎn)載微信公眾號(hào)@機(jī)智新語

上一篇:

如何基于?k8s.io/apiserver?開發(fā)自定義APIServer

下一篇:

Python云計(jì)算接口:10個(gè)云服務(wù)API的集成方法
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)