开源大模型api接口调用
(一) kimi api接口调用
1.先申请api-key,申请地址https://platform.moonshot.cn/console/api-keys
2.请求接口
import requestspayload = {"messages": [{"role": "user","content": "请总结下面这段话的主旨,字数不超过30个。7月15日,国家统计局发布数据显示,初步核算,上半年国内生产总值660536亿元,按不变价格计算,同比增长5.3%。分季度看,今年一季度国内生产总值同比增长5.4%,二季度增长5.2%。从环比看,二季度国内生产总值增长1.1%。总体看,上半年国民经济迎难而上、稳中向好."}],"model": "kimi-k2-0711-preview","max_tokens": 50,"temperature": 0.6,"n": 5, # 生成序列的个数, n在[1,5]"stream": False
}headers = {"Authorization": "moonshot ai网站申请的api-key"}
resp = requests.post(url="https://api.moonshot.cn/v1/chat/completions",json=payload, headers=headers)
print(resp.json())
接口返回结果:
{"id": "chatcmpl-6878b37b99bd601430d3fc5d","object": "chat.completion","created": 1752740732,"model": "kimi-k2-0711-preview","choices": [{"index": 0,"message": {"role": "assistant","content": "上半年GDP同比增长5.3%,经济稳中向好。"},"finish_reason": "stop"},{"index": 1,"message": {"role": "assistant","content": "上半年GDP增长5.3%,经济稳中向好。"},"finish_reason": "stop"},{"index": 2,"message": {"role": "assistant","content": "上半年GDP同比增长5.3%,经济稳中向好。"},"finish_reason": "stop"},{"index": 3,"message": {"role": "assistant","content": "上半年GDP同比增长5.3%,国民经济稳中向好。"},"finish_reason": "stop"},{"index": 4,"message": {"role": "assistant","content": "上半年GDP同比增长5.3%,经济稳中向好。"},"finish_reason": "stop"}],"usage": {"prompt_tokens": 85,"completion_tokens": 60,"total_tokens": 145,"cached_tokens": 85}
}
(二)qwen3接口调用
1.先申请api-key,https://bailian.console.aliyun.com/?tab=model#/api-key添加链接描述
2.接口测试
import requestspayload = {"messages": [{"role": "user","content": "阅读下面的新闻,总结新闻的标题,字数不超过30个。7月15日,国家统计局发布数据显示,初步核算,上半年国内生产总值660536亿元,按不变价格计算,同比增长5.3%。分季度看,今年一季度国内生产总值同比增长5.4%,二季度增长5.2%。从环比看,二季度国内生产总值增长1.1%。总体看,上半年国民经济迎难而上、稳中向好。"}],"model": "qwen3-32b","lora_name": "","max_tokens": 50,"temperature": 0.6,"n": 1, # n>1时,生成的结果较差,kimi较好,n在[1,4]"stream": True,"enable_thinking": True
}headers = {"Authorization": "网站申请的api-key"}
resp = requests.post(url="https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",json=payload, headers=headers)
print(resp.json())
备注:qwen3参数里增加thinking之后,结果会更好点