手把手教你使用Qwen-Agent開發(fā)智能體應(yīng)用實(shí)戰(zhàn)教程 原創(chuàng)
一、環(huán)境準(zhǔn)備
1.1 安裝框架
# 全功能安裝(RAG/代碼解釋器/GUI支持)
pip install -U "qwen-agent[rag,code_interpreter,python_executor,gui]"
# 簡約安裝版本
pip install -U qwen-agent
1.2 模型服務(wù)配置
方法 1:官方服務(wù)
export DASHSCOPE_API_KEY='your-api-key'
方法 2:本地部署(vLLM 示例)
from vllm import LLM, SamplingParams
llm = LLM(model="Qwen2-7B-Chat")
二、核心功能開發(fā)
2.1 工具定義與使用
from qwen_agent.tools.base import BaseTool, register_tool
import json5
@register_tool('calculate')
class Calculator(BaseTool):
description = '基礎(chǔ)運(yùn)算計算器'
parameters = [{'name': 'formula', 'type': 'string'}]
def call(self, params: str) -> float:
return eval(json5.loads(params)['formula'])
# 調(diào)用示例
calc = Calculator()
print(calc.call('{"formula": "(3 + 5) * 2"}')) # 輸出 16.0
2.2 記憶功能實(shí)現(xiàn)
from qwen_agent.agents import Assistant
class HistoryAssistant(Assistant):
def _postprocess_messages(self, messages):
return messages[-10:] # 保留最近5輪對話
assistant = HistoryAssistant(llm={'model': 'qwen-max'})
三、完整示例開發(fā)
3.1 城市信息查詢助手
from qwen_agent.agents import Assistant
from qwen_agent.tools import BaseTool, register_tool
import requests
import json5
@register_tool('city_info')
class CityInfoTool(BaseTool):
description = "城市基礎(chǔ)信息查詢"
parameters = [{'name': 'name', 'type': 'string'}]
def call(self, params):
city = json5.loads(params)['name']
response = requests.get(f"https://api.example.com/cities/{city}")
return response.json()
# 配置助手
assistant = Assistant(
llm={'model': 'qwen-max'},
function_list=['city_info','code_interpreter'],
system_message="你是一個城市百科助手"
)
# 測試查詢
response = assistant.run([{'role': 'user', 'content': '上海有多少個行政區(qū)?'}])
print(response[-1]['content'])
執(zhí)行流程:
- 用戶輸入自然語言問題
- 模型解析需調(diào)用 city_info 工具
- 工具通過 API 獲取結(jié)構(gòu)化數(shù)據(jù)
- 模型轉(zhuǎn)譯數(shù)據(jù)為自然語言回答
3.2 圖像處理流程(集成代碼解釋器)
import urllib
from qwen_agent.agents import Assistant
assistant = Assistant(
function_list=['code_interpreter'],
system_message="圖像處理專家"
)
def process_image(prompt):
messages = [{'role':'user', 'content': prompt}]
for resp in assistant.run(messages):
if 'function_call' in resp:
code = resp['function_call']['arguments']
exec(code) # 示例簡化執(zhí)行
return resp[-1]['content']
process_image('將https://example.com/image.jpg的水平寬度擴(kuò)大1.5倍')
四、進(jìn)階開發(fā)技巧
4.1 RAG 文檔問答實(shí)現(xiàn)
from qwen_agent import retrieve
# 構(gòu)建知識庫
retrieve.build_index('documents/')
class DocQA(Assistant):
def _preprocess(self, query):
contexts = retrieve.search(query)
return f"根據(jù)文檔:{contexts}\n回答:{query}"
qa = DocQA(llm={'model': 'qwen-max-longcontext'})
4.2 可視化界面集成
from qwen_agent.gui import WebUI
WebUI(assistant).launch(server_name='0.0.0.0', server_port=7860)
五、典型應(yīng)用場景
5.1 客戶服務(wù)機(jī)器人
class CustomerService(Assistant):
def __init__(self):
super().__init__(
system_message="你是XX公司客服,回答范圍限于產(chǎn)品功能和訂單查詢",
function_list=[product_lookup, order_status]
)
def _validate_query(self, query):
if '價格' in query:
return "具體產(chǎn)品價格請訪問官網(wǎng)查詢"
return super()._validate_query(query)
5.2 數(shù)據(jù)分析助手
@register_tool('data_analysis')
class DataAnalyzer:
def call(self, params):
df = pd.read_csv(params['file'])
return df.describe().to_markdown()
assistant = Assistant(function_list=['data_analysis', 'code_interpreter'])
六、技術(shù)要點(diǎn)總結(jié)
- 工具生態(tài)系統(tǒng)
支持自定義工具注冊機(jī)制,靈活擴(kuò)展功能 - 動態(tài)流程控制
支持工具調(diào)用鏈、條件分支、循環(huán)處理等復(fù)雜邏輯 - 性能優(yōu)化建議
? RAG 緩存機(jī)制提升高頻查詢響應(yīng)
? 量化壓縮降低部署資源消耗
? 設(shè)置執(zhí)行超時保障系統(tǒng)穩(wěn)定性
七、調(diào)試與優(yōu)化
# 開啟調(diào)試模式
assistant = Assistant(verbose=True)
# 性能監(jiān)控
from qwen_agent.monitor import perf_counter
@perf_counter
def critical_function():
pass
本文轉(zhuǎn)載自公眾號九歌AI大模型 作者:九歌AI
原文鏈接:??https://mp.weixin.qq.com/s/PD5xisqJ-qzmiD9X-KgEBQ??
?著作權(quán)歸作者所有,如需轉(zhuǎn)載,請注明出處,否則將追究法律責(zé)任
贊
收藏
回復(fù)
分享
微博
QQ
微信
舉報

回復(fù)
相關(guān)推薦