openAI
横空出世一年之际,各种各样的 AI 模型都出现了,包括 GPT-3,GPT-4,ChatGPT,LLaMA 等模型
其中 Groq api
在上下文长度和响应速度上比 openAi 要好很多,而且还是免费的,故决定使用 Groq
来构建自己的 Ai 聊天机器人 Api 接口
# 注册
注册 Groq
可以使用 Github
或者 Google
进行登录
登录之后可以申请一个 API key
作为身份认证凭证
# 测试
可以在 Playground
对各种模型进行测试
目前支持的模型有:
LLaMA3 8b
LLaMA3 70b
Mixtral 8x7b
Gemma 7b
使用 curl
命令测试
curl -X POST "https://api.groq.com/openai/v1/chat/completions" \ | |
-H "Authorization: Bearer $GROQ_API_KEY" \ | |
-H "Content-Type: application/json" \ | |
-d '{"messages": [{"role": "user", "content": "Explain the importance of fast language models"}], "model": "llama3-8b-8192"}' |
# 编写服务端
这里使用 koa 框架来构建一个代理服务端
const Koa = require('koa'); | |
const Router = require('koa-router'); | |
const bodyParser = require('koa-bodyparser'); | |
const Groq = require("groq-sdk"); | |
const groq = new Groq({ | |
apiKey: $GROQ_API_KEY // 替换为自己的 API key | |
}); | |
async function main(messages) { | |
const chatCompletion = await getGroqChatCompletion(messages); | |
return chatCompletion.choices[0]?.message || null; | |
} | |
async function getGroqChatCompletion(body) { | |
return groq.chat.completions.create({ | |
messages:body.messages, | |
model: body.model, | |
max_tokens:body.maxTokens, | |
temperature:body.temperature | |
}); | |
} | |
const app = new Koa(); | |
const router = new Router(); | |
app.use(bodyParser()); | |
router.post('/api/endpoint', async (ctx) => { | |
ctx.request.body.messages = ctx.request.body.messages.map(v=>{ | |
if(v.role == "user"){ | |
v.content+=" 尽量使用中文进行回复" | |
} | |
return v; | |
}); | |
const res = await main(ctx.request.body); | |
ctx.body = { data:res, code: 200, msg: 'success' }; | |
}); | |
app.use(router.routes()); | |
app.listen(3000, () => { | |
console.log('Server listening on port 3000'); | |
}); |
# 使用 Postman 测试
# 结束
下一篇将介绍如何在本地搭建一个离线的 LLM 模型