AIGC(生成式AI)试用 45 -- 个人知识库 DocsGpt 一切从DocsGPT的API调用开始。0. 启动DocsGpt1) 启动 Docker Desktop2) 启动 DocsGPT# Launch DocsGPT with Docker Composedocker compose -f deployment/docker-compose.yaml up -d# Launch DocsGPT with Ollama, CPUdocker compose --env-file .env -f deployment/docker-compose.yaml -f deployment/optional/docker-compose.optional.ollama-cpu.yaml up -d1. Python API调用(千问) 提问python调用API方法Python 中调用 API通常指 HTTP 接口如 RESTful API最常用的方式是使用requests库。场景方法获取数据requests.get(url, params...)提交 JSONrequests.post(url, json...)上传文件requests.post(url, files...)带 Tokenheaders{Authorization: Bearer xxx}安全健壮加timeouttry-exceptraise_for_status()import requests # GET方法 Parameters {} response requests.get(GET_URL, Parameters) # return: response.status_code, response.text # POST方法 Data {} # headers, json response requests.post(post_URL, Data, headers)2. 调用DocsGPT --answerAnswer related operationsanalyticsAnalytics and reporting operationsattachmentsFile attachments and media operationsconversationsConversation management operationsmodelsAvailable modelsagentsAgent management operationspromptsPrompt management operationssharingConversation sharing operationssourcesSource document management operationstoolsTool management operationsconnectorsConnector operations- payload Parameters -- 待确认、实际验证question用户提问或输入api_keyagent API keychunk上下文数量指定从向量数据库中检索多少个相关文本片段chunks作为上下文retriever检索器类型即如何从文档中查找相关信息:default;parent_document, 先子块再父文档;multi_querytemperature控制大语言模型LLM生成文本的随机性/创造性0.0~2.0确定~随机注意幻觉的产生passthrough是否启用 “直通模式”True不查RAG文档直接提问执行RAG流程检索提问history对话历史, JSONmodel_id指定LLM模型类型prompt_idlocal 或 prompt_id本地无需验证isNoneDocFalse查看RAG文档save_conversationTrue: 保留对话历史toolsLLM 可调用的外部函数/插件attachments上传附件知识库补充json_schemaLLM 输出必须符合的 JSON 结构用于强制格式化响应- POST api/answerimport requests purl http://localhost:7091/api/answer payload { question: who are you?, ## history: [string], ## conversation_id: string, prompt_id: default, chunks: 2, retriever: , ## api_key: string, active_docs: , isNoneDoc: True, save_conversation: True, model_id: docsgpt-local, passthrough: {}, temperature: 0.0, top_k: 5 } response requests.post(purl, jsonpayload) if response.status_code 200: result response.json() print(f Answer: {result.get(answer)}, \n StatusCode: {response.status_code}, \n Text: {response.text}) else: print(fFail: {response.status_code}, {response.text}) ############### Answer: I am your DocsGPT. I am an AI assistant designed to provide helpful and accurate responses, assist with documentation, and engage in meaningful conversations. I aim to be proactive and helpful in answering your questions based on both your input and any additional context provided., StatusCode: 200, Text: { answer: I am your DocsGPT. I am an AI assistant designed to provide helpful and accurate responses, assist with documentation, and engage in meaningful conversations. I aim to be proactive and helpful in answering your questions based on both your input and any additional context provided., conversation_id: 6967afe8066b58e22408544f, sources: [], thought: , tool_calls: [] } ################ Error List -- model_id: deepseek-r1:1.5b, Fail: 500, { error: Invalid model_id deepseek-r1:1.5b. Available models: docsgpt-local, gpt-5.1, gpt-5-mini } -- not set model_id Answer: None, StatusCode: 200, Text: { answer: null, conversation_id: null, sources: null, thought: Please try again later. We apologize for any inconvenience., tool_calls: null } -- history: [], Fail: 500, { error: the JSON object must be str, bytes or bytearray, not list } -- conversation_id: string, Fail: 500, { error: Conversation not found or unauthorized }- POST streamimport requests, json purl http://localhost:7091/stream payload { question: who are you?, ## history: [string], ## conversation_id: , ## prompt_id: default, ## chunks: 2, ## retriever: string, #### api_key: string, ## active_docs: string, ## isNoneDoc: True, ## index: 0, ## save_conversation: True, model_id: docsgpt-local, ## attachments: [string], ## passthrough: {} } response requests.post(purl, jsonpayload) if response.status_code 200: result response.iter_lines() answer jid for line in result: if line: text line.decode(utf-8, errorsignore) data text.split(data:)[1].strip() jdata json.loads(data) if jdata.get(answer): answer answer jdata[answer] if jdata.get(id): jid jdata[id] print(f Answer: {answer}, \n StatusCode: {response.status_code}, \n ID: {jid}) else: print(fFail: {response.status_code}, {jid}) ########################## Answer: I am DocsGPT, an AI assistant designed to help you with documents and answer questions. I analyze uploaded documents (PDF, DOCX, TXT, etc.) to provide contextualized answers. I can also use available tools, like APIs, to fetch real-time data when needed. My goal is to deliver accurate, relevant, and actionable responses., StatusCode: 200, ID: 696a382be304c4e05c085443 ########################## Error List -- Response [200] class requests.models.Response result response.iter_lines() -- json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) line: bdata: {type: id, id: 696a3ab5e304c4e05c085453} text line.decode(utf-8, errorsignore) text: data: {type: id, id: 696a3ab5e304c4e05c085453}- POST api/create_promptimport requests, json curl http://localhost:7091/api/create_prompt gsurl http://localhost:7091/api/get_prompts gurl http://localhost:7091/api/get_single_prompt purl http://localhost:7091/stream payload { content: , name: who are you?, } response requests.post(curl, jsonpayload) result response.json() payload { question: 你是谁来自哪里能做什么, ## history: [string], ## conversation_id: , prompt_id: f{result.get(id)}, ## chunks: 2, ## retriever: string, #### api_key: string, ## active_docs: string, ## isNoneDoc: True, ## index: 0, ## save_conversation: True, model_id: docsgpt-local, ## attachments: [string], ## passthrough: {} } response requests.post(purl, jsonpayload) if response.status_code 200: result response.iter_lines() answer jid for line in result: if line: text line.decode(utf-8, errorsignore) data text.split(data:)[1].strip() jdata json.loads(data) if jdata.get(answer): answer answer jdata[answer] if jdata.get(id): jid jdata[id] print(f Answer: {answer}, \n StatusCode: {response.status_code}, \n ID: {jid}) else: print(fFail: {response.status_code}) ############################################# Answer: 我是 **Kimi**由 **月之暗面科技有限公司**Moonshot AI训练的大语言模型。我出生于 **2023 年 10 月**知识截止于 **2025 年 4 月**。 我擅长用自然流畅的语言和你交流能做的事情包括但不限于 - 回答各类知识和信息咨询 - 帮你阅读、总结长文档或网页内容 - 协助写作、翻译、润色文本 - 帮你写代码、解释代码、调试程序 - 制定计划、提供建议、模拟对话等 你可以随时向我提问我会尽力帮你解决。, StatusCode: 200, ID: 696cf48bbb06b2fb690853c9- POSTapi/create_agentimport requests, json purl http://localhost:7091/api/create_agent payload { name: NewAgent, description: This is new angent, ## image: {}, source: Default, ## sources: [ ## string ## ], chunks: 2, retriever: string, prompt_id: default, ## tools: [ ## string ## ], agent_type: Classic, status: published, ## json_schema: {}, ## limited_token_mode: true, ## token_limit: 0, ## limited_request_mode: true, ## request_limit: 0, ## models: [ ## string ## ], default_model_id: docsgpt-local, } response requests.post(purl, jsonpayload, streamTrue) if response.status_code 200: result response.json() print(result: , result) print(result) print(f Answer: {result.get(answer)}, \n StatusCode: {response.status_code}, \n Text: {response.text}) else: print(fFail: {response.status_code}, {response.text}) ##################################### Fail: 201, { id: 696cdd93e304c4e05c0854eb, key: 7524f0b4-e4ec-4cc6-9cd5-faa2869274ca ########################## Error List -- Fail: 400, { message: Status must be either draft or published, success: false } -- Fail: 400, { message: Either source or sources field is required for published agents, success: false } -- Fail: 400, { message: Missing required fields: description, chunks, retriever, prompt_id, agent_type, success: false }- Getapi/get_agent(s)import requests, json purl http://localhost:7091/api/delete_agent gurl http://localhost:7091/api/get_agent gsurl http://localhost:7091/api/get_agents response requests.get(gsurl) result response.json() for gid in result: response requests.get(gurl?idgid.get(id)) result response.json() print(----------Agent: ) for agent in result: print(agent,: ,result[agent]) ################################### ----------Agent: agent_type : classic chunks : 2 created_at : Wed, 31 Dec 2025 14:09:38 GMT default_model_id : description : pic word recognize id : 69552ea240d00b40db5f1543 image : json_schema : None key : 8d64...4b85 last_used_at : Wed, 31 Dec 2025 15:50:50 GMT limited_request_mode : False limited_token_mode : False models : [] name : PicWordReg pinned : False prompt_id : 69552e8040d00b40db5f1542 request_limit : 0 retriever : shared : True shared_metadata : {shared_at: Wed, 31 Dec 2025 14:09:46 GMT, shared_by: } shared_token : ml7EmEkaTFYeHh_QAkWOnhvqsN5wEpkpKEwbdeSM3Qk source : sources : [] status : published token_limit : 0 tool_details : [] tools : [] updated_at : Wed, 31 Dec 2025 14:09:38 GMT3. Issues- api/answer, stream的区别特性非流式如/api/answer流式streamtrue响应方式一次性返回完整答案逐字/逐 token 返回等待时间需等待模型生成完整内容后才返回延迟高首字几乎立即返回延迟低网络传输单次 HTTP 响应持续的 HTTP 流如 SSE、Chunked Transfer用户体验“转圈 → 突然全部出现”“打字机效果”边生成边显示资源占用服务端需缓存完整结果服务端边生成边发送内存更省适用场景后台处理、批量任务聊天界面、实时交互效果对比用户点击“发送”等待 5 秒模型思考 生成屏幕突然显示完整回答→感觉卡顿但代码简单用户点击“发送”0.5 秒后第一个字出现后续文字像打字机一样逐字输出→体验流畅有“正在思考”的反馈场景后台自动化任务如生成报告API 被其他程序调用非人交互Web 聊天界面如微信、网页助手移动 App 聊天简单、适合机器调用但用户体验差复杂一点但提供实时反馈是聊天类应用的标准做法。4. DocsGPT PortPort: 5173, DocsGPT runningsetup.ps1: Write-ColorText DocsGPT is running at http://localhost:5173DocsGPT-main\application\app.py: redirect(http://localhost:5173)Port: 11434, AI Model.env: OPENAI_BASE_URLhttp://host.docker.internal:11434deployment\optional\docker-compose.optional.ollama-cpu.yaml: ports: - 11434:11434Port: 7091, API accessdeployment\docker-compose-local.yaml: VITE_API_HOSThttp://localhost:70914. DocsGPT environmentollamaollama list ########################################################## NAME ID SIZE MODIFIED deepseek-r1:1.5b a42b25d8c10a 1.1 GB 11 months agoDockerdocker --version docker-compose --version docker system info ########################################################## Docker version 29.1.3, build f52814d Docker Compose version v2.40.3-desktop.1 Client: Version: 29.1.3 Context: desktop-linux ...... Server: Containers: 9 Running: 6 wsl --list --verbose ########################################################## NAME STATE VERSION * docker-desktop Running 2 docker images ########################################################## i Info → U In Use IMAGE ID DISK USAGE CONTENT SIZE EXTRA arc53/docsgpt-fe:develop 89a336ecda3a 973MB 236MB U arc53/docsgpt:develop f49f4d12dd3c 12GB 4.28GB U docsgpt-oss-backend:latest 61116975e170 15.2GB 5.45GB U docsgpt-oss-frontend:latest 7bdb0c8f98ed 973MB 236MB U docsgpt-oss-worker:latest 9c3988fdb2f3 15.2GB 5.45GB U mongo:6 03cda579c8ca 1.06GB 273MB U ollama/ollama:latest 2c9595c555fd 6.14GB 2.17GB U redis:6-alpine 37e002448575 45.1MB 12.9MB UFieldTypeRequiredApplies toNotesquestionstringYes/api/answer,/streamUser query.api_keystringUsually/api/answer,/streamRecommended for agent API use. Loads agent config from key.conversation_idstringNo/api/answer,/streamContinue an existing conversation.historystring(JSON-encoded array)No/api/answer,/streamUsed for new conversations. Format:[{\prompt\:\...\,\response\:\...\}].model_idstringNo/api/answer,/streamOverride model for this request.save_conversationbooleanNo/api/answer,/streamDefaulttrue. Iffalse, no conversation is persisted.passthroughobjectNo/api/answer,/streamDynamic values injected into prompt templates.prompt_idstringNo/api/answer,/streamIgnored whenapi_keyalready defines prompt.active_docsstringorstring[]No/api/answer,/streamOverrides active docs when not using key-owned source config.retrieverstringNo/api/answer,/streamRetriever type (for exampleclassic).chunksnumberNo/api/answer,/streamRetrieval chunk count, default2.isNoneDocbooleanNo/api/answer,/streamSkip document retrieval.agent_idstringNo/api/answer,/streamAlternative toapi_keywhen using authenticated user context.参考AIGC生成式AI试用 43 -- 个人知识库-CSDN博客