問題描述
使用Azure Bot Service來部署機器人服務,如何把大模型嵌入其中呢?
比如在對話消息時候,能讓大模型來提供回答?
問題解答
其實很簡單,在Bot代碼中添加大模型的調用就行。
以Python代碼為例, 首先是準備好調用LLM的請求代碼
## 示例中使用的是Azure OpenAI的模型
import requests
# Azure OpenAI 客户端
def get_openai_answer(prompt):
api_key = "your api key"
endpoint = "your deployment endpoint, like: https://<your azure ai name>.openai.azure.com/openai/deployments/<LLM Name>/chat/completions?api-version=2025-01-01-preview"
if not api_key or not endpoint:
raise ValueError("請配置 Azure OpenAI 信息")
headers = {
"Content-Type": "application/json",
"api-key": api_key
}
systemprompt = f"""" 您是一個有趣的聊天智能體,能愉快的和人類聊天"""
data = {
"messages": [
{"role": "system", "content": systemprompt},
{"role": "user", "content": prompt}
],
"max_tokens": 5000,
"temperature": 0.7
}
response = requests.post(endpoint, headers=headers, json=data)
response.raise_for_status()
result = response.json()
return result["choices"][0]["message"]["content"]
# 示例用法
if __name__ == "__main__":
prompt = "請介紹一下Azure OpenAI的主要功能。"
print(get_openai_answer(prompt))
然後,在 EchoBot 的 on_message_activity 中調用OpenAI接口即可
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import ActivityHandler, MessageFactory, TurnContext
from botbuilder.schema import ChannelAccount
from bots.call_openai import get_openai_answer
class EchoBot(ActivityHandler):
async def on_members_added_activity(self, members_added: [ChannelAccount], turn_context: TurnContext):
for member in members_added:
if member.id != turn_context.activity.recipient.id:
await turn_context.send_activity("Hello and welcome, this is python code.")
async def on_message_activity(self, turn_context: TurnContext):
#call LLM API to get response
llmresponse = get_openai_answer(turn_context.activity.text)
return await turn_context.send_activity(
MessageFactory.text(f"{llmresponse}")
)
測試效果:
[完]
參考資料
發送和接收文本消息:https://docs.azure.cn/zh-cn/bot-service/bot-builder-howto-send-messages?view=azure-bot-service-4.0&tabs=python#send-a-typing-indicator
當在複雜的環境中面臨問題,格物之道需:濁而靜之徐清,安以動之徐生。 雲中,恰是如此!