Azure Bot Service 集成大模型实战
在使用 Azure Bot Service 部署机器人服务时,赋予其更智能的对话能力往往是最关键的一步。最直接且有效的方式,就是在现有的 Bot 代码中嵌入大语言模型(LLM)调用逻辑。这样当用户发送消息时,Bot 不再只是简单的关键词匹配,而是能生成自然流畅的回答。
核心思路
整个流程其实并不复杂:
- 封装一个独立的函数来处理 LLM 请求,负责与 Azure OpenAI 等接口交互。
- 在 Bot 的消息处理活动(Activity Handler)中调用这个函数。
- 将返回的结果发送给用户。
下面以 Python 为例,展示如何落地这套方案。
第一步:封装 LLM 调用函数
首先,我们需要编写一个能够调用大模型的辅助函数。这里以 Azure OpenAI 为例。
注意:生产环境中请务必使用环境变量存储密钥,不要硬编码在代码里。
import requests
def get_openai_answer(prompt):
# 实际项目中建议从环境变量读取
api_key = "your_api_key_here"
endpoint = "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
}
system_prompt = "您是一个有趣的聊天智能体,能愉快的和人类聊天"
data = {
"messages": [
{"role": "system", "content": system_prompt},
{"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[][][][]


